Validators using zod

This commit is contained in:
2026-10-25 12:41:46 -03:00
parent 31ae2973d7
commit 4fad43d9cc
24 changed files with 1242 additions and 1788 deletions
+32 -85
View File
@@ -3,8 +3,9 @@
// biomes as data: worldgen/biomes/<name>.json in a mod, see docs/modding/worldgen/biomes.md. which biome a column
// gets is the generator's biome rules (worldgen/biome_source), these say what a biome looks like once it's picked
import * as z from "zod";
import { EverythingRegistry } from "../everything_registry.ts";
import { ID_PATTERN, is_object } from "../mod_data.ts";
import { find_problems, id, type Problems } from "../schema.ts";
import { farming_day } from "../time.ts";
export const SEASONS = ["spring", "summer", "autumn", "winter"] as const;
@@ -12,31 +13,41 @@ export type Season = typeof SEASONS[number];
// how long each season lasts. day 1 to 49 is spring, 50 to 98 summer and so on, a year is 196 days
export const SEASON_DAYS = 49;
// how a biome covers its ground, like minecraft's surface rules. blocks are ids
export interface SurfaceJson {
top: string;
filler: string;
filler_depth: number;
// how a biome covers its ground, like minecraft's surface rules
const surface_schema = z.object({
top: id,
filler: id,
filler_depth: z.int().min(0).max(32),
// the ground's cover under water, filler when not set
underwater_top?: string;
underwater_filler?: string;
underwater_top: id.optional(),
underwater_filler: id.optional(),
// cliffs show bare stone instead of top
bare_cliffs?: boolean;
}
bare_cliffs: z.boolean().optional(),
});
export interface BiomeJson {
id: string;
export type SurfaceJson = z.infer<typeof surface_schema>;
const color = z.string('must be a color like "#79c05a"').regex(/^#[0-9a-fA-F]{6}$/);
const biome_schema = z.object({
id,
// a season it's always in, like winter for snowy biomes. when not set it follows the calendar, see calendar_season
season?: Season;
surface: SurfaceJson;
// "#rrggbb", minecraft's grass, foliage and water colors, which blocks pick with "tint". plains' when not set
colors?: { grass?: string; foliage?: string; water?: string };
season: z.enum(SEASONS).optional(),
surface: surface_schema,
// minecraft's grass, foliage and water colors, which blocks pick with "tint". plains' when not set
colors: z.strictObject({ grass: color.optional(), foliage: color.optional(), water: color.optional() }).optional(),
// how likely each tree cell is to have a tree, and which kinds grow, picked evenly (list one twice to make it
// twice as likely). wood is the logs and leaves a kind grows here when it isn't its own, like big oaks being dark
// oak in the dark forest. the trees feature reads it (bworld's, in its worldgen script), which says what kinds
// and woods there are
trees?: { chance: number; kinds: string[]; wood?: Record<string, string> };
}
// and woods there are, and checks them when it loads
trees: z.object({
chance: z.number().min(0).max(1),
kinds: z.array(z.string()).min(1),
wood: z.record(z.string(), z.string()).optional(),
}).optional(),
});
export type BiomeJson = z.infer<typeof biome_schema>;
// what's registered in "biomes", with the defaults filled in
export interface Biome {
@@ -97,70 +108,6 @@ export function biome_blocks(json: BiomeJson): string[] {
return [top, filler, underwater_top, underwater_filler].filter((id) => id !== undefined);
}
export function validate_biome(json: unknown): string[] {
if (!is_object(json)) return ["biome must be an object"];
const problems: string[] = [];
const id = (value: unknown, field: string) => {
if (!(typeof value === "string" && ID_PATTERN.test(value))) {
problems.push(`${field} must be an id like "my_mod:thing"`);
}
};
id(json.id, "id");
if (json.season !== undefined && !SEASONS.includes(json.season as Season)) {
problems.push(`season must be one of ${SEASONS.join(", ")}`);
}
const surface = json.surface;
if (!is_object(surface)) {
problems.push("surface must be { top, filler, filler_depth }");
} else {
id(surface.top, "surface.top");
id(surface.filler, "surface.filler");
if (surface.underwater_top !== undefined) id(surface.underwater_top, "surface.underwater_top");
if (surface.underwater_filler !== undefined) id(surface.underwater_filler, "surface.underwater_filler");
const depth = surface.filler_depth;
if (!Number.isInteger(depth) || (depth as number) < 0 || (depth as number) > 32) {
problems.push("surface.filler_depth must be a whole number from 0 to 32");
}
if (surface.bare_cliffs !== undefined && typeof surface.bare_cliffs !== "boolean") {
problems.push("surface.bare_cliffs must be true or false");
}
}
if (json.colors !== undefined) {
if (!is_object(json.colors)) {
problems.push("colors must be { grass, foliage, water }");
} else {
for (const [key, value] of Object.entries(json.colors)) {
if (!["grass", "foliage", "water"].includes(key)) problems.push(`colors.${key} isn't a biome color`);
else if (!(typeof value === "string" && /^#[0-9a-fA-F]{6}$/.test(value))) {
problems.push(`colors.${key} must be a color like "#79c05a"`);
}
}
}
}
const trees = json.trees;
if (trees !== undefined) {
if (!is_object(trees)) {
problems.push("trees must be { chance, kinds }");
} else {
if (typeof trees.chance !== "number" || trees.chance < 0 || trees.chance > 1) {
problems.push("trees.chance must be a number from 0 to 1");
}
// which kinds and woods there are is up to the trees feature, bworld's checks them when it loads
if (
!Array.isArray(trees.kinds) || trees.kinds.length === 0 ||
!trees.kinds.every((kind) => typeof kind === "string")
) {
problems.push("trees.kinds must list at least one kind of tree");
}
if (trees.wood !== undefined) {
if (!is_object(trees.wood) || !Object.values(trees.wood).every((wood) => typeof wood === "string")) {
problems.push("trees.wood must be { <kind>: <wood> }");
}
}
}
}
return problems;
export function validate_biome(json: unknown): Problems {
return find_problems(biome_schema, json);
}
+222 -352
View File
@@ -4,7 +4,8 @@
// world generation as data: noises, density functions, noise settings (a generator) and biome sources, see
// docs/modding/worldgen/terrain.md. checked here, compiled by density.ts and generator.ts. the names follow
// minecraft's (density functions, the noise router, surface rules) where the idea is the same
import { ID_PATTERN, is_object, TAG_ID_PATTERN } from "../mod_data.ts";
import * as z from "zod";
import { find_problems, ID_PATTERN, is_object, type Problems, TAG_ID_PATTERN } from "../schema.ts";
// ids of worldgen data can have folders, like "bworld:overworld/erosion"
export const WORLDGEN_ID_PATTERN = TAG_ID_PATTERN;
@@ -142,376 +143,256 @@ export function new_refs(): WorldgenRefs {
return { noises: new Set(), functions: new Set(), blocks: new Set(), biomes: new Set(), biome_sources: new Set() };
}
const ARITHMETIC = ["add", "sub", "mul", "div", "min", "max"];
export const DENSITY_TYPES = [
"constant",
"x",
"y",
"z",
"noise",
...ARITHMETIC,
"abs",
"clamp",
"smoothstep",
"spline",
"range_choice",
"cache_2d",
];
// checking
const worldgen_id = z.string('must be an id like "my_mod:thing" or "my_mod:folder/thing"').regex(WORLDGEN_ID_PATTERN);
const block_id = z.string("must be a block's id").regex(ID_PATTERN);
const biome_id = z.string("must be a biome's id").regex(ID_PATTERN);
const noise_schema: z.ZodType<NoiseJson> = z.object({
id: worldgen_id,
seed_name: z.string().optional(),
wavelength: z.number().positive(),
amplitudes: z.array(z.number()).min(1).refine((amplitudes) => amplitudes.some((a) => a !== 0), "can't all be 0"),
dimensions: z.literal([2, 3]).optional(),
vertical_stretch: z.number().positive().optional(),
quantiles: z.union([
worldgen_id,
z.array(z.number()).min(2).refine((q) => q.every((value, i) => i === 0 || value > q[i - 1]), "must go up"),
], "must be at least 2 numbers going up, or a noise's id").optional(),
}).refine((noise) => noise.vertical_stretch === undefined || noise.dimensions === 3, {
path: ["vertical_stretch"],
message: "is only for 3d noises",
});
const RANGE_KEYS = ["min_inclusive", "min_exclusive", "max_inclusive", "max_exclusive"] as const;
export function validate_noise(json: unknown): string[] {
const problems: string[] = [];
if (!is_object(json)) return ["noise must be an object"];
worldgen_id(json.id, "id", problems);
if (json.seed_name !== undefined && typeof json.seed_name !== "string") problems.push("seed_name must be text");
if (!(typeof json.wavelength === "number" && json.wavelength > 0)) problems.push("wavelength must be above 0");
if (
!Array.isArray(json.amplitudes) || json.amplitudes.length === 0 ||
!json.amplitudes.every((a) => typeof a === "number" && Number.isFinite(a)) ||
json.amplitudes.every((a) => a === 0)
) {
problems.push("amplitudes must be a list of numbers, not all 0");
}
if (json.dimensions !== undefined && json.dimensions !== 2 && json.dimensions !== 3) {
problems.push("dimensions must be 2 or 3");
}
if (json.vertical_stretch !== undefined) {
if (json.dimensions !== 3) problems.push("vertical_stretch is only for 3d noises");
if (!(typeof json.vertical_stretch === "number" && json.vertical_stretch > 0)) {
problems.push("vertical_stretch must be above 0");
// a range's bounds, numbers or (in range_choice) density functions. a range needs at least one
function bounds<T extends z.ZodType>(bound: T) {
return {
min_inclusive: bound.optional(),
min_exclusive: bound.optional(),
max_inclusive: bound.optional(),
max_exclusive: bound.optional(),
};
}
const has_bound = (range: Partial<Record<typeof RANGE_KEYS[number], unknown>>) =>
RANGE_KEYS.some((key) => range[key] !== undefined);
const NEEDS_BOUND = `needs at least one of ${RANGE_KEYS.join(", ")}`;
const range = z.object(bounds(z.number())).refine(has_bound, NEEDS_BOUND);
// a density function, by itself or by its id
const density: z.ZodType<DensityJson> = z.lazy(() =>
z.union(
[z.number(), z.string("must be a density function's id").regex(WORLDGEN_ID_PATTERN), density_object],
'must be a number, a density function\'s id or { "type": ... }',
)
);
const spline: z.ZodType<SplineJson> = z.object({
coordinate: density,
points: z.array(z.object({
location: z.number(),
value: z.union([z.number(), z.lazy(() => spline)], "must be a number or a spline"),
derivative: z.number().optional(),
})).min(1).superRefine((points, ctx) => {
points.forEach((point, i) => {
if (i > 0 && point.location < points[i - 1].location) {
ctx.addIssue({ code: "custom", path: [i, "location"], message: "can't be below the point before's" });
}
});
}),
});
const density_object = z.discriminatedUnion("type", [
z.object({ type: z.literal("constant"), argument: z.number() }),
z.object({ type: z.literal(["x", "y", "z"]) }),
z.object({
type: z.literal("noise"),
noise: z.string("must be a noise's id").regex(WORLDGEN_ID_PATTERN),
even: z.boolean().optional(),
x: density.optional(),
y: density.optional(),
z: density.optional(),
}),
z.object({ type: z.literal(["add", "sub", "mul", "div", "min", "max"]), argument1: density, argument2: density }),
z.object({ type: z.literal(["abs", "cache_2d"]), argument: density }),
z.object({ type: z.literal("clamp"), input: density, min: z.number(), max: z.number() })
.refine(({ min, max }) => min <= max, { path: ["min"], message: "can't be above max" }),
z.object({ type: z.literal("smoothstep"), input: density, from: z.number(), to: z.number() })
.refine(({ from, to }) => from !== to, { path: ["to"], message: "must be different from from" }),
z.object({ type: z.literal("spline"), spline }),
z.object({
type: z.literal("range_choice"),
input: density,
...bounds(density),
when_in_range: density,
when_out_of_range: density,
}).refine(has_bound, NEEDS_BOUND),
]);
const density_function_schema: z.ZodType<DensityFunctionJson> = z.intersection(
z.object({ id: worldgen_id }),
density_object,
);
const surface_rule: z.ZodType<SurfaceRuleJson> = z.lazy(() =>
z.discriminatedUnion("type", [
z.object({ type: z.literal("sequence"), sequence: z.array(surface_rule) }),
z.object({ type: z.literal("condition"), if_true: surface_condition, then_run: surface_rule }),
z.object({ type: z.literal("block"), result_state: z.object({ Name: block_id }) }),
z.object({ type: z.literal("biome_surface"), part: z.enum(BIOME_SURFACE_PARTS) }),
])
);
const surface_condition: z.ZodType<SurfaceConditionJson> = z.lazy(() =>
z.discriminatedUnion("type", [
z.object({ type: z.literal("stone_depth"), offset: z.int() }),
z.object({ type: z.literal(["filler_depth", "surface_underwater", "steep", "bare_cliffs"]) }),
z.object({ type: z.literal("above_preliminary_surface"), offset: z.number().optional() }),
z.object({ type: z.literal("y_at_least"), function: density }),
z.object({ type: z.literal("biome"), biome_is: z.array(biome_id) }),
z.object({ type: z.literal("not"), invert: surface_condition }),
])
);
const cell_height = z.literal([1, 2, 4, 8, 16, 32]);
const noise_settings_schema: z.ZodType<NoiseSettingsJson> = z.object({
id: worldgen_id,
sea_level: z.int().min(0).max(256),
default_block: block_id,
cell_width: z.literal([1, 2, 4, 8, 16]),
terrain: z.object({ density, cell_height }),
caves: z.object({ density, cell_height }),
preliminary_surface: density,
climate: z.record(
z.string("isn't a name a climate value can have: lowercase letters and _, but not surface or steep")
.regex(/^[a-z_]+$/).refine((name) => name !== "surface" && name !== "steep"),
density,
),
steep: z.number().min(0),
biome_source: z.string("must be a biome source's id").regex(WORLDGEN_ID_PATTERN),
fluids: z.array(z.object({
block: block_id,
below: z.int(),
where: z.union([
z.literal("open_sky"),
z.object({ function: density, ...bounds(z.number()) }).refine(has_bound, NEEDS_BOUND),
], 'must be "open_sky" or { "function", <range> }'),
})),
surface_rule,
});
const biome_source_schema: z.ZodType<BiomeSourceJson> = z.object({
id: worldgen_id,
extends: z.string("must be a biome source's id").regex(WORLDGEN_ID_PATTERN).optional(),
rules: z.array(z.object({
id: worldgen_id,
before: worldgen_id.optional(),
after: worldgen_id.optional(),
// steep is true or false, any other name is a range of that climate value
when: z.object({ steep: z.boolean().optional() }).catchall(range).optional(),
biome: biome_id,
})),
}).superRefine((source, ctx) => {
// a rule added to another biome source goes before or after one of its rules
source.rules.forEach((rule, i) => {
const placed = [rule.before, rule.after].filter((id) => id !== undefined).length;
if (source.extends !== undefined && placed !== 1) {
ctx.addIssue({ code: "custom", path: ["rules", i], message: "needs before or after, one of them" });
}
}
const quantiles = json.quantiles;
if (quantiles !== undefined && typeof quantiles !== "string") {
if (
!Array.isArray(quantiles) || quantiles.length < 2 ||
!quantiles.every((q, i) => typeof q === "number" && (i === 0 || q > quantiles[i - 1]))
) {
problems.push("quantiles must be at least 2 numbers going up, or a noise's id");
if (source.extends === undefined && placed > 0) {
ctx.addIssue({
code: "custom",
path: ["rules", i],
message: "can't have before or after, they're for rules added to another biome source with extends",
});
}
} else if (typeof quantiles === "string") {
worldgen_id(quantiles, "quantiles", problems);
}
return problems;
});
});
export function validate_noise(json: unknown): Problems {
return find_problems(noise_schema, json);
}
// the noises a noise file refers to: the one it takes its quantiles from
export function validate_density_function(json: unknown): Problems {
return find_problems(density_function_schema, json);
}
export function validate_noise_settings(json: unknown): Problems {
return find_problems(noise_settings_schema, json);
}
export function validate_biome_source(json: unknown): Problems {
return find_problems(biome_source_schema, json);
}
// what worldgen data that passed its checks refers to
export function noise_refs(json: NoiseJson, refs: WorldgenRefs) {
if (typeof json.quantiles === "string") refs.noises.add(json.quantiles);
}
export function validate_density_function(json: unknown): string[] {
if (!is_object(json)) return ["density_function must be an object"];
const problems: string[] = [];
worldgen_id(json.id, "id", problems);
const { id: _, ...fn } = json;
check_density(fn, "", new_refs(), problems);
return problems;
}
export function density_function_refs(json: DensityFunctionJson, refs: WorldgenRefs) {
const { id: _, ...fn } = json;
check_density(fn, "", refs, []);
density_refs(fn, refs);
}
// checks a density function, adding what it refers to to refs. at is where it is, for messages
export function check_density(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
const where = at ? `${at}: ` : "";
if (typeof json === "number") {
if (!Number.isFinite(json)) problems.push(`${where}must be a finite number`);
return;
}
function density_refs(json: DensityJson, refs: WorldgenRefs) {
if (typeof json === "number") return;
if (typeof json === "string") {
if (WORLDGEN_ID_PATTERN.test(json)) refs.functions.add(json);
else problems.push(`${where}"${json}" isn't a density function's id`);
refs.functions.add(json);
return;
}
if (!is_object(json) || typeof json.type !== "string") {
problems.push(`${where}must be a number, a density function's id or { "type": ... }`);
return;
}
const field = (name: string) => check_density(json[name], at ? `${at}.${name}` : name, refs, problems);
const number = (name: string) => {
if (typeof json[name] !== "number" || !Number.isFinite(json[name])) {
problems.push(`${where}${name} must be a number`);
for (const [key, value] of Object.entries(json)) {
if (key === "noise") refs.noises.add(value as string);
else if (key === "spline") spline_refs(value as SplineJson, refs);
// the other fields that are text or objects are density functions, the rest numbers and true or false
else if (key !== "type" && (typeof value === "string" || is_object(value))) {
density_refs(value as DensityJson, refs);
}
};
switch (json.type) {
case "constant":
number("argument");
break;
case "x":
case "y":
case "z":
break;
case "noise":
if (typeof json.noise === "string" && WORLDGEN_ID_PATTERN.test(json.noise)) refs.noises.add(json.noise);
else problems.push(`${where}noise must be a noise's id`);
if (json.even !== undefined && typeof json.even !== "boolean") {
problems.push(`${where}even must be true or false`);
}
for (const axis of ["x", "y", "z"]) if (json[axis] !== undefined) field(axis);
break;
case "abs":
case "cache_2d":
field("argument");
break;
case "clamp":
field("input");
number("min");
number("max");
if ((json.min as number) > (json.max as number)) problems.push(`${where}min is above max`);
break;
case "smoothstep":
field("input");
number("from");
number("to");
if (json.from === json.to) problems.push(`${where}from and to must be different`);
break;
case "spline":
check_spline(json.spline, at ? `${at}.spline` : "spline", refs, problems);
break;
case "range_choice":
field("input");
if (!RANGE_KEYS.some((key) => json[key] !== undefined)) problems.push(`${where}needs at least one bound`);
for (const key of RANGE_KEYS) if (json[key] !== undefined) field(key);
field("when_in_range");
field("when_out_of_range");
break;
default:
if (ARITHMETIC.includes(json.type)) {
field("argument1");
field("argument2");
} else {
problems.push(`${where}type ${json.type} isn't one of ${DENSITY_TYPES.join(", ")}`);
}
}
}
function check_spline(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
if (!is_object(json) || !Array.isArray(json.points) || json.points.length === 0) {
problems.push(`${at}: must be { "coordinate": ..., "points": [ ... ] }`);
return;
}
check_density(json.coordinate, `${at}.coordinate`, refs, problems);
let last = -Infinity;
json.points.forEach((point: unknown, i: number) => {
const here = `${at}.points[${i}]`;
if (!is_object(point) || typeof point.location !== "number") {
problems.push(`${here}: must be { "location", "value", "derivative" }`);
return;
}
if (point.location < last) problems.push(`${here}: locations must go up`);
last = point.location;
if (typeof point.value !== "number") check_spline(point.value, `${here}.value`, refs, problems);
if (point.derivative !== undefined && typeof point.derivative !== "number") {
problems.push(`${here}: derivative must be a number`);
}
});
function spline_refs(spline: SplineJson, refs: WorldgenRefs) {
density_refs(spline.coordinate, refs);
for (const point of spline.points) if (typeof point.value !== "number") spline_refs(point.value, refs);
}
export function validate_noise_settings(json: unknown): string[] {
if (!is_object(json)) return ["noise_settings must be an object"];
const problems: string[] = [];
noise_settings_refs(json, new_refs(), problems);
return problems;
export function noise_settings_refs(json: NoiseSettingsJson, refs: WorldgenRefs) {
refs.blocks.add(json.default_block);
const { terrain, caves, preliminary_surface, climate } = json;
for (const fn of [terrain.density, caves.density, preliminary_surface, ...Object.values(climate)]) {
density_refs(fn, refs);
}
refs.biome_sources.add(json.biome_source);
for (const fluid of json.fluids) {
refs.blocks.add(fluid.block);
if (fluid.where !== "open_sky") density_refs(fluid.where.function, refs);
}
surface_rule_refs(json.surface_rule, refs);
}
export function noise_settings_refs(json: Record<string, unknown>, refs: WorldgenRefs, problems: string[] = []) {
worldgen_id(json.id, "id", problems);
const whole = (name: string, min: number, max: number) => {
const value = json[name];
if (!(Number.isInteger(value) && (value as number) >= min && (value as number) <= max)) {
problems.push(`${name} must be a whole number from ${min} to ${max}`);
}
};
whole("sea_level", 0, 256);
block_id(json.default_block, "default_block", refs, problems);
if (![1, 2, 4, 8, 16].includes(json.cell_width as number)) problems.push("cell_width must be 1, 2, 4, 8 or 16");
for (const part of ["terrain", "caves"]) {
const value = json[part];
if (!is_object(value)) {
problems.push(`${part} must be { "density", "cell_height" }`);
continue;
}
check_density(value.density, `${part}.density`, refs, problems);
if (![1, 2, 4, 8, 16, 32].includes(value.cell_height as number)) {
problems.push(`${part}.cell_height must be 1, 2, 4, 8, 16 or 32`);
}
function surface_rule_refs(rule: SurfaceRuleJson, refs: WorldgenRefs) {
if (rule.type === "sequence") { for (const inner of rule.sequence) surface_rule_refs(inner, refs); }
if (rule.type === "condition") {
surface_condition_refs(rule.if_true, refs);
surface_rule_refs(rule.then_run, refs);
}
check_density(json.preliminary_surface, "preliminary_surface", refs, problems);
if (!is_object(json.climate)) {
problems.push("climate must be { <name>: <density function> }");
} else {
for (const [name, value] of Object.entries(json.climate)) {
if (!/^[a-z_]+$/.test(name) || name === "surface" || name === "steep") {
problems.push(`climate.${name}: names are lowercase letters and _, and not surface or steep`);
}
check_density(value, `climate.${name}`, refs, problems);
}
}
if (!(typeof json.steep === "number" && json.steep >= 0)) problems.push("steep must be a number, 0 or more");
if (typeof json.biome_source === "string" && WORLDGEN_ID_PATTERN.test(json.biome_source)) {
refs.biome_sources.add(json.biome_source);
} else {
problems.push("biome_source must be a biome source's id");
}
if (!Array.isArray(json.fluids)) {
problems.push("fluids must be a list");
} else {
json.fluids.forEach((fluid: unknown, i: number) => {
const at = `fluids[${i}]`;
if (!is_object(fluid)) {
problems.push(`${at}: must be { "block", "below", "where" }`);
return;
}
block_id(fluid.block, `${at}.block`, refs, problems);
if (!Number.isInteger(fluid.below)) problems.push(`${at}.below must be a whole number`);
if (fluid.where !== "open_sky") {
if (!is_object(fluid.where)) {
problems.push(`${at}.where must be "open_sky" or { "function", <range> }`);
} else {
check_density(fluid.where.function, `${at}.where.function`, refs, problems);
check_range(fluid.where, `${at}.where`, problems);
}
}
});
}
check_surface_rule(json.surface_rule, "surface_rule", refs, problems);
if (rule.type === "block") refs.blocks.add(rule.result_state.Name);
}
function check_surface_rule(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
if (!is_object(json)) {
problems.push(`${at}: must be a rule`);
return;
}
switch (json.type) {
case "sequence":
if (!Array.isArray(json.sequence)) problems.push(`${at}.sequence must be a list of rules`);
else json.sequence.forEach((rule, i) => check_surface_rule(rule, `${at}.sequence[${i}]`, refs, problems));
break;
case "condition":
check_surface_condition(json.if_true, `${at}.if_true`, refs, problems);
check_surface_rule(json.then_run, `${at}.then_run`, refs, problems);
break;
case "block":
if (!is_object(json.result_state)) problems.push(`${at}.result_state must be { "Name": <block> }`);
else block_id(json.result_state.Name, `${at}.result_state.Name`, refs, problems);
break;
case "biome_surface":
if (!BIOME_SURFACE_PARTS.includes(json.part as BiomeSurfacePart)) {
problems.push(`${at}.part must be one of ${BIOME_SURFACE_PARTS.join(", ")}`);
}
break;
default:
problems.push(`${at}: type must be sequence, condition, block or biome_surface`);
}
function surface_condition_refs(condition: SurfaceConditionJson, refs: WorldgenRefs) {
if (condition.type === "y_at_least") density_refs(condition.function, refs);
if (condition.type === "biome") { for (const biome of condition.biome_is) refs.biomes.add(biome); }
if (condition.type === "not") surface_condition_refs(condition.invert, refs);
}
function check_surface_condition(json: unknown, at: string, refs: WorldgenRefs, problems: string[]) {
if (!is_object(json)) {
problems.push(`${at}: must be a condition`);
return;
}
switch (json.type) {
case "stone_depth":
if (!Number.isInteger(json.offset)) problems.push(`${at}.offset must be a whole number`);
break;
case "above_preliminary_surface":
if (json.offset !== undefined && typeof json.offset !== "number") {
problems.push(`${at}.offset must be a number`);
}
break;
case "filler_depth":
case "surface_underwater":
case "steep":
case "bare_cliffs":
break;
case "y_at_least":
check_density(json.function, `${at}.function`, refs, problems);
break;
case "biome":
if (!Array.isArray(json.biome_is) || !json.biome_is.every((b) => typeof b === "string")) {
problems.push(`${at}.biome_is must be a list of biome ids`);
} else {
for (const biome of json.biome_is) refs.biomes.add(biome);
}
break;
case "not":
check_surface_condition(json.invert, `${at}.invert`, refs, problems);
break;
default:
problems.push(
`${at}: type must be stone_depth, filler_depth, above_preliminary_surface, surface_underwater, steep, ` +
`bare_cliffs, y_at_least, biome or not`,
);
}
}
export function validate_biome_source(json: unknown): string[] {
if (!is_object(json)) return ["biome_source must be an object"];
const problems: string[] = [];
biome_source_refs(json, new_refs(), problems);
return problems;
}
export function biome_source_refs(json: Record<string, unknown>, refs: WorldgenRefs, problems: string[] = []) {
worldgen_id(json.id, "id", problems);
if (json.extends !== undefined) {
if (typeof json.extends === "string" && WORLDGEN_ID_PATTERN.test(json.extends)) {
refs.biome_sources.add(json.extends);
} else problems.push("extends must be a biome source's id");
}
if (!Array.isArray(json.rules)) {
problems.push("rules must be a list");
return;
}
json.rules.forEach((rule: unknown, i: number) => {
const at = `rules[${i}]`;
if (!is_object(rule)) {
problems.push(`${at}: must be { "id", "when", "biome" }`);
return;
}
worldgen_id(rule.id, `${at}.id`, problems);
const placed = [rule.before, rule.after].filter((id) => id !== undefined);
if (json.extends !== undefined && placed.length !== 1) {
problems.push(`${at}: a rule added to another biome source needs before or after, one of them`);
}
if (json.extends === undefined && placed.length > 0) {
problems.push(`${at}: before and after are for rules added to another biome source, with extends`);
}
for (const id of placed) worldgen_id(id, `${at}.before/after`, problems);
if (typeof rule.biome === "string" && ID_PATTERN.test(rule.biome)) refs.biomes.add(rule.biome);
else problems.push(`${at}.biome must be a biome's id`);
if (rule.when !== undefined) {
if (!is_object(rule.when)) {
problems.push(`${at}.when must be { <climate value>: <range>, "steep": true or false }`);
} else {
for (const [name, condition] of Object.entries(rule.when)) {
if (name === "steep") {
if (typeof condition !== "boolean") problems.push(`${at}.when.steep must be true or false`);
} else {
check_range(condition, `${at}.when.${name}`, problems);
}
}
}
}
});
}
// a range of numbers, with at least one bound
function check_range(json: unknown, at: string, problems: string[]) {
if (!is_object(json)) {
problems.push(`${at} must be a range like { "min_inclusive": 0 }`);
return;
}
let bounds = 0;
for (const key of RANGE_KEYS) {
if (json[key] === undefined) continue;
bounds++;
if (typeof json[key] !== "number") problems.push(`${at}.${key} must be a number`);
}
if (bounds === 0) problems.push(`${at} needs at least one of ${RANGE_KEYS.join(", ")}`);
export function biome_source_refs(json: BiomeSourceJson, refs: WorldgenRefs) {
if (json.extends !== undefined) refs.biome_sources.add(json.extends);
for (const rule of json.rules) refs.biomes.add(rule.biome);
}
// a test of whether a value is in the range, with only the bounds it has: value >= min, value < max
@@ -529,14 +410,3 @@ export function range_test(range: RangeJson): (value: number) => boolean {
}
return (value) => tests.every((test) => test(value));
}
function worldgen_id(value: unknown, field: string, problems: string[]) {
if (!(typeof value === "string" && WORLDGEN_ID_PATTERN.test(value))) {
problems.push(`${field} must be an id like "my_mod:thing" or "my_mod:folder/thing"`);
}
}
function block_id(value: unknown, field: string, refs: WorldgenRefs, problems: string[]) {
if (typeof value === "string" && ID_PATTERN.test(value)) refs.blocks.add(value);
else problems.push(`${field} must be a block's id`);
}
+147 -206
View File
@@ -7,7 +7,18 @@
import { EverythingRegistry } from "../everything_registry.ts";
import type { BlockRegistry } from "../everything_registry.ts";
import { CHUNK_HEIGHT, CHUNK_SIZE } from "../constants.ts";
import { ID_PATTERN, is_object, TAG_ID_PATTERN } from "../mod_data.ts";
import * as z from "zod";
import {
add_problems,
by_kind,
find_problems,
id_or_tag,
ID_PATTERN,
is_object,
json_object,
type Problems,
TAG_ID_PATTERN,
} from "../schema.ts";
import { list_matches } from "../tags.ts";
import { can_stand_on } from "../utils.ts";
import { AIR_ID } from "../protocol.ts";
@@ -66,56 +77,108 @@ export interface FeatureRefs {
custom: Set<string>;
}
export function validate_feature(json: unknown): string[] {
const problems: string[] = [];
feature_refs(json, { blocks: new Set(), biomes: new Set(), custom: new Set() }, problems);
return problems;
// a built in name, with its namespace or without, see builtin_name
const builtin = (...names: string[]) => z.literal(names.flatMap((name) => [name, `minecraft:${name}`]));
const block_id = z.string("must be a block's id").regex(ID_PATTERN);
const biome_id = z.string("must be a biome's id").regex(ID_PATTERN);
// a block, see state_id
const block_state_schema = z.union(
[block_id, z.object({ state: z.object({ Name: block_id }) }), z.object({ Name: block_id })],
'must be a block\'s id or { "type": "simple_state_provider", "state": { "Name": ... } }',
);
// a whole number, see int_provider
const int_provider_schema: z.ZodType = z.lazy(() =>
z.union([
z.int(),
z.discriminatedUnion("type", [
z.object({ type: builtin("constant"), value: z.int() }),
z.object({ type: builtin("uniform"), min_inclusive: z.int(), max_inclusive: z.int() }).refine(
({ min_inclusive, max_inclusive }) => min_inclusive <= max_inclusive,
{ path: ["min_inclusive"], message: "can't be above max_inclusive" },
),
z.object({
type: builtin("weighted_list"),
distribution: z.array(z.object({ data: int_provider_schema, weight: z.int().min(1) })).min(1),
}),
], "must be constant, uniform or weighted_list"),
], 'must be a whole number or { "type": "uniform", ... }')
);
// a y, see anchor
const anchor_schema = z.union([
z.strictObject({ absolute: z.int() }),
z.strictObject({ above_bottom: z.int() }),
z.strictObject({ below_top: z.int() }),
], 'must be one of { "absolute": y }, { "above_bottom": n } or { "below_top": n }');
// see height_provider
const height_schema = z.union([
anchor_schema,
z.discriminatedUnion("type", [
z.object({ type: builtin("constant"), value: anchor_schema }),
z.object({ type: builtin("uniform"), min_inclusive: anchor_schema, max_inclusive: anchor_schema }),
], "must be constant or uniform"),
], 'must be a height, like { "absolute": 10 } or { "type": "uniform", ... }');
// see block_predicate. offset moves where it looks
const predicate_base = z.object({
offset: z.tuple([z.int(), z.int(), z.int()], "must be [x, y, z], whole numbers").optional(),
});
const block_predicate_schema: z.ZodType = z.lazy(() =>
z.discriminatedUnion("type", [
predicate_base.extend({
type: builtin("matching_blocks"),
blocks: z.union([id_or_tag, z.array(id_or_tag)], "must be a block, a #tag, or a list of them"),
}),
predicate_base.extend({ type: builtin("solid", "replaceable", "true") }),
predicate_base.extend({ type: builtin("would_survive"), state: block_state_schema }),
predicate_base.extend({ type: builtin("not"), predicate: block_predicate_schema }),
predicate_base.extend({ type: builtin("all_of", "any_of"), predicates: z.array(block_predicate_schema) }),
], "must be matching_blocks, solid, replaceable, would_survive, not, all_of, any_of or true")
);
// a mod's own modifier is checked by the worldgen script that registers it
const placement_modifier = by_kind<PlacementJson>("type", (type) => {
const name = builtin_name(type);
if (name === undefined) return json_object;
return Object.hasOwn(MODIFIERS, name) ? MODIFIERS[name].schema : undefined;
}, "isn't a built in placement modifier");
const feature_schema: z.ZodType<FeatureJson> = z.object({
id: z.string('must be an id like "my_mod:thing" or "my_mod:folder/thing"').regex(TAG_ID_PATTERN),
type: z.string(),
config: json_object.optional(),
placement: z.array(placement_modifier).optional(),
biomes: z.union([biome_id, z.array(biome_id)], "must be a biome's id or a list of them").optional(),
step: z.enum(FEATURE_STEPS).optional(),
}).superRefine((feature, ctx) => {
// a built in type's config. a mod's own type is checked by the worldgen script that registers it, like modifiers
const name = builtin_name(feature.type);
if (name === undefined) return;
if (!Object.hasOwn(FEATURE_TYPES, name)) {
return ctx.addIssue({ code: "custom", path: ["type"], message: `${feature.type} isn't built in` });
}
add_problems(ctx, FEATURE_TYPES[name].schema, feature.config ?? {}, ["config"]);
});
export function validate_feature(json: unknown): Problems {
return find_problems(feature_schema, json);
}
export function feature_refs(json: unknown, refs: FeatureRefs, problems: string[] = []) {
if (!is_object(json)) {
problems.push("feature must be an object");
return;
}
if (!(typeof json.id === "string" && TAG_ID_PATTERN.test(json.id))) {
problems.push(`id must be an id like "my_mod:thing" or "my_mod:folder/thing"`);
}
if (json.step !== undefined && !FEATURE_STEPS.includes(json.step as FeatureStep)) {
problems.push(`step must be one of ${FEATURE_STEPS.join(", ")}`);
}
if (json.biomes !== undefined) {
const biomes = typeof json.biomes === "string" ? [json.biomes] : json.biomes;
if (!Array.isArray(biomes) || !biomes.every((b) => typeof b === "string" && ID_PATTERN.test(b))) {
problems.push("biomes must be a biome's id or a list of them");
} else {
for (const biome of biomes) refs.biomes.add(biome);
}
}
if (json.config !== undefined && !is_object(json.config)) problems.push("config must be an object");
if (typeof json.type !== "string") {
problems.push("type must be a feature type");
} else {
const name = builtin_name(json.type);
if (name === undefined) refs.custom.add(json.type);
else if (!(name in FEATURE_TYPES)) problems.push(`type ${json.type} isn't built in`);
else FEATURE_TYPES[name].check((json.config ?? {}) as Record<string, unknown>, "config", refs, problems);
}
if (json.placement !== undefined) {
if (!Array.isArray(json.placement)) {
problems.push("placement must be a list of placement modifiers");
return;
}
json.placement.forEach((modifier: unknown, i: number) => {
const at = `placement[${i}]`;
if (!is_object(modifier) || typeof modifier.type !== "string") {
problems.push(`${at}: must be { "type": ... }`);
return;
}
const name = builtin_name(modifier.type);
if (name === undefined) refs.custom.add(modifier.type);
else if (!(name in MODIFIERS)) problems.push(`${at}: ${modifier.type} isn't a built in placement modifier`);
else MODIFIERS[name].check(modifier, at, refs, problems);
});
// what a feature that passed its checks uses
export function feature_refs(json: FeatureJson, refs: FeatureRefs) {
for (const biome of [json.biomes ?? []].flat()) refs.biomes.add(biome);
const type = builtin_name(json.type);
if (type === undefined) refs.custom.add(json.type);
else FEATURE_TYPES[type].refs?.(json.config ?? {}, refs);
for (const modifier of json.placement ?? []) {
const name = builtin_name(modifier.type);
if (name === undefined) refs.custom.add(modifier.type);
else MODIFIERS[name].refs?.(modifier, refs);
}
}
@@ -183,15 +246,19 @@ export function compile_feature(
// built in feature types
interface Builtin<T> {
check(json: Record<string, unknown>, at: string, refs: FeatureRefs, problems: string[]): void;
// its json: a feature type's config, or the placement modifier
schema: z.ZodType;
// what it uses, when it uses something
refs?(json: Record<string, unknown>, refs: FeatureRefs): void;
compile(json: Record<string, unknown>): T;
}
const FEATURE_TYPES: Record<string, Builtin<(chunk: FeatureChunk, origin: Position) => boolean>> = {
// one block, where it can stand
simple_block: {
check(json, at, refs, problems) {
check_state(json.to_place, `${at}.to_place`, refs, problems);
schema: z.object({ to_place: block_state_schema }),
refs(json, refs) {
refs.blocks.add(state_id(json.to_place));
},
compile(json) {
const id = state_id(json.to_place);
@@ -204,29 +271,15 @@ const FEATURE_TYPES: Record<string, Builtin<(chunk: FeatureChunk, origin: Positi
},
// layers of blocks stacked up (or down) from the origin, cut short where allowed_placement doesn't hold
block_column: {
check(json, at, refs, problems) {
if (!Array.isArray(json.layers) || json.layers.length === 0) {
problems.push(`${at}.layers must be a list of { "height", "provider" }`);
} else {
json.layers.forEach((layer: unknown, i: number) => {
const here = `${at}.layers[${i}]`;
if (!is_object(layer)) {
problems.push(`${here} must be { "height", "provider" }`);
return;
}
check_int(layer.height, `${here}.height`, problems);
check_state(layer.provider, `${here}.provider`, refs, problems);
});
}
if (json.direction !== undefined && json.direction !== "up" && json.direction !== "down") {
problems.push(`${at}.direction must be "up" or "down"`);
}
if (json.allowed_placement !== undefined) {
check_predicate(json.allowed_placement, `${at}.allowed_placement`, refs, problems);
}
if (json.prioritize_tip !== undefined && typeof json.prioritize_tip !== "boolean") {
problems.push(`${at}.prioritize_tip must be true or false`);
}
schema: z.object({
layers: z.array(z.object({ height: int_provider_schema, provider: block_state_schema })).min(1),
direction: z.enum(["up", "down"]).optional(),
allowed_placement: block_predicate_schema.optional(),
prioritize_tip: z.boolean().optional(),
}),
refs(json, refs) {
for (const layer of json.layers as { provider: unknown }[]) refs.blocks.add(state_id(layer.provider));
if (json.allowed_placement !== undefined) predicate_refs(json.allowed_placement, refs);
},
compile(json) {
const layers = (json.layers as { height: unknown; provider: unknown }[]).map((layer) => ({
@@ -259,14 +312,12 @@ const FEATURE_TYPES: Record<string, Builtin<(chunk: FeatureChunk, origin: Positi
type Modifier = (chunk: FeatureChunk, positions: Position[]) => Position[];
const HEIGHTMAPS = ["WORLD_SURFACE_WG", "WORLD_SURFACE", "MOTION_BLOCKING", "OCEAN_FLOOR_WG", "OCEAN_FLOOR"];
const HEIGHTMAPS = ["WORLD_SURFACE_WG", "WORLD_SURFACE", "MOTION_BLOCKING", "OCEAN_FLOOR_WG", "OCEAN_FLOOR"] as const;
const MODIFIERS: Record<string, Builtin<Modifier>> = {
// each position becomes count of them
count: {
check(json, at, _refs, problems) {
check_int(json.count, `${at}.count`, problems);
},
schema: z.object({ count: int_provider_schema }),
compile(json) {
const count = int_provider(json.count);
return (chunk, positions) =>
@@ -275,11 +326,7 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
},
// one in chance positions are kept
rarity_filter: {
check(json, at, _refs, problems) {
if (!(Number.isInteger(json.chance) && (json.chance as number) >= 1)) {
problems.push(`${at}.chance must be a whole number, 1 or more`);
}
},
schema: z.object({ chance: z.int().min(1) }),
compile(json) {
const chance = json.chance as number;
return (chunk, positions) => positions.filter(() => chunk.rng.next() < 1 / chance);
@@ -287,7 +334,7 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
},
// somewhere random in the chunk, across
in_square: {
check() {},
schema: z.object({}),
compile() {
return (chunk, positions) =>
positions.map((p) => {
@@ -299,10 +346,7 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
},
// moved by up to xz_spread across and y_spread up or down
random_offset: {
check(json, at, _refs, problems) {
check_int(json.xz_spread ?? 0, `${at}.xz_spread`, problems);
check_int(json.y_spread ?? 0, `${at}.y_spread`, problems);
},
schema: z.object({ xz_spread: int_provider_schema.optional(), y_spread: int_provider_schema.optional() }),
compile(json) {
const xz = int_provider(json.xz_spread ?? 0);
const y = int_provider(json.y_spread ?? 0);
@@ -312,9 +356,7 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
},
// at a height
height_range: {
check(json, at, _refs, problems) {
check_height(json.height, `${at}.height`, problems);
},
schema: z.object({ height: height_schema }),
compile(json) {
const height = height_provider(json.height);
return (chunk, positions) => positions.map((p) => ({ x: p.x, y: height(chunk), z: p.z }));
@@ -323,11 +365,7 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
// on top of the column: WORLD_SURFACE on its highest block, OCEAN_FLOOR on its highest that isn't a liquid.
// positions outside the chunk are dropped
heightmap: {
check(json, at, _refs, problems) {
if (!HEIGHTMAPS.includes(json.heightmap as string)) {
problems.push(`${at}.heightmap must be one of ${HEIGHTMAPS.join(", ")}`);
}
},
schema: z.object({ heightmap: z.enum(HEIGHTMAPS) }),
compile(json) {
const floor = String(json.heightmap).startsWith("OCEAN_FLOOR");
return (chunk, positions) =>
@@ -341,8 +379,9 @@ const MODIFIERS: Record<string, Builtin<Modifier>> = {
},
// where a block predicate holds
block_predicate_filter: {
check(json, at, refs, problems) {
check_predicate(json.predicate, `${at}.predicate`, refs, problems);
schema: z.object({ predicate: block_predicate_schema }),
refs(json, refs) {
predicate_refs(json.predicate, refs);
},
compile(json) {
const predicate = block_predicate(json.predicate);
@@ -359,44 +398,22 @@ function counts_for_heightmap(id: string | undefined, floor: boolean) {
// block predicates, like minecraft's
type Predicate = (chunk: FeatureChunk, x: number, y: number, z: number) => boolean;
const PREDICATES = ["matching_blocks", "solid", "replaceable", "would_survive", "not", "all_of", "any_of", "true"];
function check_predicate(json: unknown, at: string, refs: FeatureRefs, problems: string[]) {
if (!is_object(json) || typeof json.type !== "string") {
problems.push(`${at} must be a block predicate, { "type": ... }`);
return;
}
const name = builtin_name(json.type);
if (name === undefined || !PREDICATES.includes(name)) {
problems.push(`${at}: ${json.type} isn't one of ${PREDICATES.join(", ")}`);
return;
}
if (
json.offset !== undefined &&
!(Array.isArray(json.offset) && json.offset.length === 3 && json.offset.every(Number.isInteger))
) {
problems.push(`${at}.offset must be [x, y, z], whole numbers`);
}
switch (name) {
case "matching_blocks": {
const blocks = typeof json.blocks === "string" ? [json.blocks] : json.blocks;
if (!Array.isArray(blocks) || !blocks.every((b) => typeof b === "string")) {
problems.push(`${at}.blocks must be a block, a #tag, or a list of them`);
} else {
for (const block of blocks) refs.blocks.add(block);
}
// the blocks a predicate tests for
function predicate_refs(json: unknown, refs: FeatureRefs) {
const predicate = json as Record<string, unknown>;
switch (builtin_name(predicate.type as string)) {
case "matching_blocks":
for (const block of [predicate.blocks].flat()) refs.blocks.add(block as string);
break;
}
case "would_survive":
check_state(json.state, `${at}.state`, refs, problems);
refs.blocks.add(state_id(predicate.state));
break;
case "not":
check_predicate(json.predicate, `${at}.predicate`, refs, problems);
predicate_refs(predicate.predicate, refs);
break;
case "all_of":
case "any_of":
if (!Array.isArray(json.predicates)) problems.push(`${at}.predicates must be a list`);
else json.predicates.forEach((p, i) => check_predicate(p, `${at}.predicates[${i}]`, refs, problems));
for (const inner of predicate.predicates as unknown[]) predicate_refs(inner, refs);
}
}
@@ -456,18 +473,6 @@ function inside(chunk: FeatureChunk, x: number, z: number) {
// block states: a block's id, or minecraft's { "type": "simple_state_provider", "state": { "Name": id } }
function check_state(json: unknown, at: string, refs: FeatureRefs, problems: string[]) {
const id = typeof json === "string"
? json
: is_object(json) && is_object(json.state)
? json.state.Name
: is_object(json)
? json.Name
: undefined;
if (typeof id === "string" && ID_PATTERN.test(id)) refs.blocks.add(id);
else problems.push(`${at} must be a block's id or { "type": "simple_state_provider", "state": { "Name": ... } }`);
}
function state_id(json: unknown): string {
if (typeof json === "string") return json;
const object = json as Record<string, unknown>;
@@ -479,41 +484,6 @@ function state_id(json: unknown): string {
type IntProvider = (chunk: FeatureChunk) => number;
function check_int(json: unknown, at: string, problems: string[]) {
if (Number.isInteger(json)) return;
if (!is_object(json)) {
problems.push(`${at} must be a whole number or { "type": "uniform", ... }`);
return;
}
switch (builtin_name(String(json.type))) {
case "constant":
if (!Number.isInteger(json.value)) problems.push(`${at}.value must be a whole number`);
break;
case "uniform":
if (!Number.isInteger(json.min_inclusive) || !Number.isInteger(json.max_inclusive)) {
problems.push(`${at} needs whole numbers min_inclusive and max_inclusive`);
} else if ((json.min_inclusive as number) > (json.max_inclusive as number)) {
problems.push(`${at}: min_inclusive is above max_inclusive`);
}
break;
case "weighted_list":
if (!Array.isArray(json.distribution) || json.distribution.length === 0) {
problems.push(`${at}.distribution must be a list of { "data", "weight" }`);
} else {
json.distribution.forEach((entry: unknown, i: number) => {
if (!is_object(entry) || !(Number.isInteger(entry.weight) && (entry.weight as number) > 0)) {
problems.push(`${at}.distribution[${i}] needs a whole number weight above 0`);
} else {
check_int(entry.data, `${at}.distribution[${i}].data`, problems);
}
});
}
break;
default:
problems.push(`${at}.type must be constant, uniform or weighted_list`);
}
}
function int_provider(json: unknown): IntProvider {
if (typeof json === "number") return () => json;
const object = json as Record<string, unknown>;
@@ -548,35 +518,6 @@ function int_provider(json: unknown): IntProvider {
// heights: an anchor ({ "absolute" }, { "above_bottom" } or { "below_top" }), { "type": "constant", "value": anchor }
// or { "type": "uniform", "min_inclusive": anchor, "max_inclusive": anchor }
function check_height(json: unknown, at: string, problems: string[]) {
if (!is_object(json)) {
problems.push(`${at} must be a height, like { "absolute": 10 } or { "type": "uniform", ... }`);
return;
}
if (json.type === undefined) return check_anchor(json, at, problems);
switch (builtin_name(String(json.type))) {
case "constant":
check_anchor(json.value, `${at}.value`, problems);
break;
case "uniform":
check_anchor(json.min_inclusive, `${at}.min_inclusive`, problems);
check_anchor(json.max_inclusive, `${at}.max_inclusive`, problems);
break;
default:
problems.push(`${at}.type must be constant or uniform`);
}
}
function check_anchor(json: unknown, at: string, problems: string[]) {
const keys = ["absolute", "above_bottom", "below_top"];
if (
!is_object(json) || Object.keys(json).length !== 1 || !keys.includes(Object.keys(json)[0]) ||
!Number.isInteger(Object.values(json)[0])
) {
problems.push(`${at} must be one of { "absolute": y }, { "above_bottom": n } or { "below_top": n }`);
}
}
function anchor(json: unknown): number {
const object = json as Record<string, number>;
if (object.absolute !== undefined) return object.absolute;