/** * Reading definition files: JSONC objects whose unknown keys are refused, so explanations stay * in comments and in the patch notes instead of growing into data fields. */ import { readFileSync } from 'node:fs'; import { parseJsonc } from '@wto/jsonc'; import { DefinitionError } from './errors.ts'; export function readJsonObject(path: string): Record { let data: unknown; try { data = parseJsonc(readFileSync(path, 'utf-8')); } catch (error) { throw new DefinitionError(`${path}: ${(error as Error).message}`); } return asObject(data, path); } export function asObject(value: unknown, where: string): Record { if (!value || typeof value !== 'object' || Array.isArray(value)) throw new DefinitionError(`${where}: expected an object`); return value as Record; } export function rejectUnknownKeys(object: Record, allowed: ReadonlySet, where: string): void { const unknown = Object.keys(object).filter((key) => !allowed.has(key)); if (unknown.length) { throw new DefinitionError(`${where}: unknown key(s) ${unknown.join(', ')}; explanations belong in comments or the patch notes`); } } export function requiredString(value: unknown, where: string): string { if (typeof value !== 'string' || value === '') throw new DefinitionError(`${where} must be a non-empty string`); return value; } export function stringList(value: unknown, where: string): string[] { if (value === undefined) return []; if (!Array.isArray(value) || !value.every((item) => typeof item === 'string')) throw new DefinitionError(`${where} must be a list of strings`); return value; } /** The "variants" list of a definition, each entry an object, and their written_for names unique. */ export function variantObjects(value: unknown, where: string): Record[] { if (!Array.isArray(value) || value.length === 0) throw new DefinitionError(`${where}: "variants" must be a non-empty list`); const variants = value.map((item, index) => asObject(item, `${where} variants[${index}]`)); const names = variants.map((variant, index) => requiredString(variant.written_for, `${where} variants[${index}].written_for`)); const duplicate = names.find((name, index) => names.indexOf(name) !== index); if (duplicate) throw new DefinitionError(`${where}: two variants are written for ${duplicate}`); return variants; }