包文件→ .shtukbase/packages/collections/checks/s02_values.ts
checks/s02_values.ts
36 行, 2.0 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // S2. Values of fields by kind: select — from options, date — an ISO date, number — a number, checkbox — true/false.
- // Empty values are not checked (that is s03). The `phase` field (the state of a contour) is checked by the package contours.
- import { addr, ctx, empty, hole, isDate, isNumber, iterFields, optionNames, scopeAll, short, values } from './lib/schemalib.ts';
- import { type Project, type Result, pystr, truthy } from './lib/speclib.ts';
- import { main } from './lib/runner.ts';
- export const RULE = { id: 's02', title: 'Schema: select, date, number and flag values are valid', scope: 'all records of all collections, fields select / date / number / checkbox' };
- export function check(p: Project, res: Result): void {
- const c = ctx(p);
- scopeAll(c, res, 'values');
- if (!res.part('values', null)) return;
- for (const [coll, name, spec] of iterFields(c, ['select', 'date', 'number', 'checkbox'])) {
- const kind: string = spec.kind;
- const allowed = kind === 'select' ? optionNames(spec) : new Set<string>();
- if (kind === 'select' && !allowed.size) continue; // no options given: any value goes
- for (const r of c.records(coll)) {
- const v = r.fm[name];
- if (empty(v)) continue;
- if (Array.isArray(v) && !(kind === 'select' && truthy(spec.multiple)) && v.length !== 1) {
- hole(res, addr(r.id), name, 'bad-' + kind, `${name}: a list ${short(v)}, but the field is single`, 'keep one value');
- continue;
- }
- for (const x of values(v)) {
- let ok: boolean, want: string;
- if (kind === 'select') [ok, want] = [typeof x !== 'object' && allowed.has(pystr(x)), 'one of: ' + [...allowed].sort().join(', ')];
- else if (kind === 'date') [ok, want] = [isDate(x), 'a date YYYY-MM-DD'];
- else if (kind === 'number') [ok, want] = [isNumber(x), 'a number'];
- else [ok, want] = [typeof x === 'boolean', 'true or false'];
- if (!ok) hole(res, addr(r.id), name, 'bad-' + kind, `${name}: "${short(x)}" is not a valid value`, want);
- }
- }
- }
- }
- if (import.meta.main) main({ RULE, check });