Validators using zod
This commit is contained in:
@@ -0,0 +1,141 @@
|
||||
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
// the pieces mod data's zod schemas are made of, and the problems they find, worded for mod authors. it imports
|
||||
// nothing else of the game's, so every file can make its schemas with these as it loads, whatever imports it first
|
||||
import * as z from "zod";
|
||||
|
||||
// a list of what's wrong with some json, empty when it's fine
|
||||
export type Problems = string[];
|
||||
|
||||
export const ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+$/;
|
||||
// a tag's id may have folders, like c:ingots/iron. see docs/modding/resources/tags.md
|
||||
export const TAG_ID_PATTERN = /^[a-z0-9_]+:[a-z0-9_]+(\/[a-z0-9_]+)*$/;
|
||||
|
||||
export const id = z.string('must be an id like "my_mod:thing"').regex(ID_PATTERN);
|
||||
// an id, or a #tag of them
|
||||
export const id_or_tag = z.string('must be an id like "my_mod:thing" or a tag like "#my_mod:things"').refine(
|
||||
(value) => value.startsWith("#") ? TAG_ID_PATTERN.test(value.slice(1)) : ID_PATTERN.test(value),
|
||||
);
|
||||
export const loot_table_id = z.string('must be a loot table id, like "my_mod:blocks/thing"').regex(TAG_ID_PATTERN);
|
||||
// text players see
|
||||
export const text = z.string().min(1);
|
||||
export const vec3 = z.tuple([z.number(), z.number(), z.number()], "must be [x, y, z]");
|
||||
// any json object, for what's only stored, like components
|
||||
export const json_object = z.record(z.string(), z.unknown());
|
||||
|
||||
// json that says what kind of thing it is in one field, like a loot condition's "condition", checked by the schema
|
||||
// schema_for gives for its kind: the engine's kinds, and mods' own for the rest. no schema is a kind there isn't, which
|
||||
// unknown says what's wrong with
|
||||
export function by_kind<T extends Record<string, unknown>>(
|
||||
field: string,
|
||||
schema_for: (kind: string) => z.ZodType | undefined,
|
||||
unknown: string,
|
||||
): z.ZodType<T> {
|
||||
const kinded: z.ZodType = z.looseObject({ [field]: z.string() }).superRefine((json, ctx) => {
|
||||
const schema = schema_for(json[field]);
|
||||
if (schema) add_problems(ctx, schema, json);
|
||||
else ctx.addIssue({ code: "custom", path: [field], message: unknown });
|
||||
});
|
||||
// the kind's schema checked the rest of T
|
||||
return kinded as z.ZodType<T>;
|
||||
}
|
||||
|
||||
// checks json with schema as part of a bigger check, like a feature's config by its type. the problems go to ctx, under
|
||||
// path from where it is
|
||||
export function add_problems(ctx: z.RefinementCtx, schema: z.ZodType, json: unknown, path: PropertyKey[] = []) {
|
||||
for (const issue of schema.safeParse(json, { error: describe }).error?.issues ?? []) {
|
||||
ctx.addIssue({ ...issue, path: [...path, ...issue.path] } as z.core.$ZodRawIssue);
|
||||
}
|
||||
}
|
||||
|
||||
// what's wrong with json for a schema, each as where it is and what it should be, like "tool.durability must be 1 or
|
||||
// more". a schema's own message wins over the ones from describe
|
||||
export function find_problems(schema: z.ZodType, json: unknown): Problems {
|
||||
const result = schema.safeParse(json, { error: describe });
|
||||
return result.success ? [] : result.error.issues.flatMap((issue) => issue_problems(issue, []));
|
||||
}
|
||||
|
||||
function issue_problems(issue: z.core.$ZodIssue, outer: PropertyKey[]): Problems {
|
||||
const path = [...outer, ...issue.path];
|
||||
if (issue.code === "unrecognized_keys") {
|
||||
const where = field_name(path);
|
||||
return issue.keys.map((key) => `${where ? `${where} ` : ""}can't have ${JSON.stringify(key)}`);
|
||||
}
|
||||
// a union's options are the kinds of thing the json can be, like a texture id or { variable: texture id }. when
|
||||
// it's only one of them, that one's problems say more than the union's message
|
||||
if (issue.code === "invalid_union") {
|
||||
const fitting = issue.errors.filter((issues) => !issues.every(wrong_kind));
|
||||
if (fitting.length === 1) return fitting[0].flatMap((inner) => issue_problems(inner, path));
|
||||
}
|
||||
const where = field_name(path);
|
||||
return [where ? `${where} ${issue.message}` : issue.message];
|
||||
}
|
||||
|
||||
// a problem saying json isn't the kind of thing at all: it's the wrong type, none of a union's kinds, or not the
|
||||
// value a literal like "open_sky" is
|
||||
function wrong_kind(issue: z.core.$ZodIssue): boolean {
|
||||
return issue.path.length === 0 &&
|
||||
(issue.code === "invalid_type" || issue.code === "invalid_union" || issue.code === "invalid_value");
|
||||
}
|
||||
|
||||
// a path into the json as it's written in js, like tool.durability, parts[0].when or variants["age=3"]
|
||||
function field_name(path: PropertyKey[]): string {
|
||||
return path.map((key, i) => {
|
||||
if (typeof key === "number") return `[${key}]`;
|
||||
const name = String(key);
|
||||
return /^\w+$/.test(name) ? (i === 0 ? name : `.${name}`) : `[${JSON.stringify(name)}]`;
|
||||
}).join("");
|
||||
}
|
||||
|
||||
const TYPE_NAMES: Record<string, string> = {
|
||||
number: "a number",
|
||||
int: "a whole number",
|
||||
string: "text",
|
||||
boolean: "true or false",
|
||||
array: "a list",
|
||||
tuple: "a list",
|
||||
object: "an object",
|
||||
record: "an object",
|
||||
};
|
||||
|
||||
// zod's messages, in words for mod authors. what isn't here keeps zod's own
|
||||
const describe: z.core.$ZodErrorMap = (issue) => {
|
||||
switch (issue.code) {
|
||||
case "invalid_type":
|
||||
return issue.input === undefined
|
||||
? "is required"
|
||||
: `must be ${TYPE_NAMES[issue.expected] ?? issue.expected}`;
|
||||
case "too_small":
|
||||
if (issue.origin === "array" || issue.origin === "string") {
|
||||
if (issue.minimum === 1) return "can't be empty";
|
||||
return `must have at least ${issue.minimum} ${issue.origin === "string" ? "characters" : "entries"}`;
|
||||
}
|
||||
return issue.inclusive ? `must be ${issue.minimum} or more` : `must be above ${issue.minimum}`;
|
||||
case "too_big":
|
||||
if (issue.origin === "array" || issue.origin === "string") {
|
||||
return `must have at most ${issue.maximum} ${issue.origin === "string" ? "characters" : "entries"}`;
|
||||
}
|
||||
return issue.inclusive ? `must be at most ${issue.maximum}` : `must be below ${issue.maximum}`;
|
||||
case "invalid_value":
|
||||
return `must be ${or_list(issue.values.map((value) => JSON.stringify(value)))}`;
|
||||
// a record's key, its schema says what's wrong with it
|
||||
case "invalid_key":
|
||||
return issue.issues[0]?.message;
|
||||
// a discriminated union's field that isn't one of its kinds
|
||||
case "invalid_union":
|
||||
if (Array.isArray(issue.options)) {
|
||||
return `must be ${or_list(issue.options.map((kind) => JSON.stringify(kind)))}`;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// "a", "b" or "c"
|
||||
function or_list(values: string[]): string {
|
||||
return values.length < 2 ? values.join("") : `${values.slice(0, -1).join(", ")} or ${values.at(-1)}`;
|
||||
}
|
||||
|
||||
// a json object, not null or an array
|
||||
export function is_object(value: unknown): value is Record<string, unknown> {
|
||||
return typeof value === "object" && value !== null && !Array.isArray(value);
|
||||
}
|
||||
Reference in New Issue
Block a user