ShtukbaseStandard
файл пакета→ .shtukbase/packages/collections/checks/s02_values.ts

checks/s02_values.ts

36 строк, 2.0 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // S2. Values of fields by kind: select — from options, date — an ISO date, number — a number, checkbox — true/false.
  2. // Empty values are not checked (that is s03). The `phase` field (the state of a contour) is checked by the package contours.
  3. import { addr, ctx, empty, hole, isDate, isNumber, iterFields, optionNames, scopeAll, short, values } from './lib/schemalib.ts';
  4. import { type Project, type Result, pystr, truthy } from './lib/speclib.ts';
  5. import { main } from './lib/runner.ts';
  6. 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' };
  7. export function check(p: Project, res: Result): void {
  8. const c = ctx(p);
  9. scopeAll(c, res, 'values');
  10. if (!res.part('values', null)) return;
  11. for (const [coll, name, spec] of iterFields(c, ['select', 'date', 'number', 'checkbox'])) {
  12. const kind: string = spec.kind;
  13. const allowed = kind === 'select' ? optionNames(spec) : new Set<string>();
  14. if (kind === 'select' && !allowed.size) continue; // no options given: any value goes
  15. for (const r of c.records(coll)) {
  16. const v = r.fm[name];
  17. if (empty(v)) continue;
  18. if (Array.isArray(v) && !(kind === 'select' && truthy(spec.multiple)) && v.length !== 1) {
  19. hole(res, addr(r.id), name, 'bad-' + kind, `${name}: a list ${short(v)}, but the field is single`, 'keep one value');
  20. continue;
  21. }
  22. for (const x of values(v)) {
  23. let ok: boolean, want: string;
  24. if (kind === 'select') [ok, want] = [typeof x !== 'object' && allowed.has(pystr(x)), 'one of: ' + [...allowed].sort().join(', ')];
  25. else if (kind === 'date') [ok, want] = [isDate(x), 'a date YYYY-MM-DD'];
  26. else if (kind === 'number') [ok, want] = [isNumber(x), 'a number'];
  27. else [ok, want] = [typeof x === 'boolean', 'true or false'];
  28. if (!ok) hole(res, addr(r.id), name, 'bad-' + kind, `${name}: "${short(x)}" is not a valid value`, want);
  29. }
  30. }
  31. }
  32. }
  33. if (import.meta.main) main({ RULE, check });