mirror of
https://github.com/profullstack/logicsrc.git
synced 2026-08-14 14:57:28 +00:00
Scaffold LogicSRC and CommandBoard plugins
This commit is contained in:
parent
59927e140c
commit
5c9ea821f6
67 changed files with 5958 additions and 0 deletions
52
packages/validators/src/index.ts
Normal file
52
packages/validators/src/index.ts
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
import * as Ajv2020Module from "ajv/dist/2020.js";
|
||||
import * as addFormatsModule from "ajv-formats";
|
||||
import type { ErrorObject } from "ajv";
|
||||
import { parse } from "yaml";
|
||||
import { isSchemaKind, schemas, type SchemaKind } from "./schemas.js";
|
||||
|
||||
const Ajv2020 = (Ajv2020Module as unknown as { default: new (options: Record<string, unknown>) => { compile: (schema: unknown) => { (data: unknown): boolean; errors?: ErrorObject[] | null } } }).default;
|
||||
const addFormats = (addFormatsModule as unknown as { default: (ajv: InstanceType<typeof Ajv2020>) => void }).default;
|
||||
|
||||
export type ValidationResult =
|
||||
| { ok: true; kind: SchemaKind; data: unknown }
|
||||
| { ok: false; kind: SchemaKind; errors: ErrorObject[] };
|
||||
|
||||
export function createValidator() {
|
||||
const ajv = new Ajv2020({ allErrors: true, strict: true });
|
||||
addFormats(ajv);
|
||||
return ajv;
|
||||
}
|
||||
|
||||
export function parseDocument(input: string, fileName = "document") {
|
||||
if (fileName.endsWith(".json")) {
|
||||
return JSON.parse(input) as unknown;
|
||||
}
|
||||
|
||||
return parse(input) as unknown;
|
||||
}
|
||||
|
||||
export function validate(kind: SchemaKind, data: unknown): ValidationResult {
|
||||
const ajv = createValidator();
|
||||
const validateDocument = ajv.compile(schemas[kind]);
|
||||
const ok = validateDocument(data);
|
||||
|
||||
if (ok) {
|
||||
return { ok: true, kind, data };
|
||||
}
|
||||
|
||||
return {
|
||||
ok: false,
|
||||
kind,
|
||||
errors: validateDocument.errors ?? []
|
||||
};
|
||||
}
|
||||
|
||||
export function assertSchemaKind(value: string): SchemaKind {
|
||||
if (!isSchemaKind(value)) {
|
||||
throw new Error(`Unknown schema kind "${value}". Expected one of: ${Object.keys(schemas).join(", ")}`);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
export { schemas, type SchemaKind };
|
||||
Loading…
Add table
Add a link
Reference in a new issue