silverbullet/common/syscalls/jsonschema.ts

55 lines
1.2 KiB
TypeScript
Raw Permalink 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 => {
try {
const validate = ajv.compile(schema);
if (validate(object)) {
return;
} else {
let text = ajv.errorsText(validate.errors);
text = text.replaceAll("/", ".");
text = text.replace(/^data[\.\s]/, "");
return text;
}
2024-10-10 18:52:28 +08:00
} catch (e: any) {
return e.message;
2024-08-02 23:14:40 +08:00
}
},
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
};
}