файл пакета→ .shtukbase/packages/hooks/hooks/record-pre.ts
hooks/record-pre.ts
52 строки, 2.6 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // HK-R02, before the write (PreToolUse on Write, Edit, MultiEdit). A record of a collection that would break its
- // schema is not written: the hook works out the file as the tool would leave it and blocks when
- // - the record has no front matter, or front matter that read strictly before and no longer does;
- // - `title` is empty;
- // - a field the schema marks `required: true`, or `requiredWhen` for the record's values, is empty.
- // Links and option values need the rest of the base: record-post.ts checks them right after the write.
- import { existsSync, readFileSync } from 'node:fs';
- import { join } from 'node:path';
- import { schemaProperties, splitFrontMatter, parseYaml } from '../../collections/checks/lib/pages.ts';
- import { empty, values } from '../../collections/checks/lib/schemalib.ts';
- import { BLOCK, collectionOf, contentAfter, projectPath, projectRoot, readPayload } from '../lib/hooklib.ts';
- const strict = (head: string): boolean => {
- try {
- const v = Bun.YAML.parse(head);
- return !!v && typeof v === 'object' && !Array.isArray(v);
- } catch {
- return false;
- }
- };
- const { p } = readPayload();
- if (!p) process.exit(0);
- const root = projectRoot(p);
- const input = p.tool_input ?? {};
- const rel = projectPath(root, input.file_path);
- const coll = rel ? collectionOf(root, rel) : null;
- if (!rel || !coll) process.exit(0);
- const text = contentAfter(root, String(p.tool_name ?? ''), input);
- if (text === null) process.exit(0);
- const out: string[] = [];
- const [head] = splitFrontMatter(text);
- const before = existsSync(join(root, rel)) ? splitFrontMatter(readFileSync(join(root, rel), 'utf8'))[0] : '';
- if (!head.trim()) out.push('no head (front matter between the --- lines)');
- else {
- if (!strict(head) && (!before || strict(before))) out.push('the head cannot be read as YAML');
- const fm = parseYaml(head);
- if (empty(fm.title)) out.push('empty title');
- for (const [name, spec] of Object.entries(schemaProperties(root, coll.slice(1) + '.md'))) {
- if (!spec || typeof spec !== 'object' || !empty(fm[name])) continue;
- const s = spec as Record<string, any>;
- if (s.required === true) out.push(`empty required field ${name}`);
- else if (s.requiredWhen && typeof s.requiredWhen === 'object')
- for (const [f, vals] of Object.entries(s.requiredWhen))
- if (values(vals).map(String).includes(String(fm[f] ?? ''))) out.push(`empty field ${name}: it is required when ${f}: ${fm[f]}`);
- }
- }
- if (out.length) {
- process.stderr.write(`The record ${rel} (collection ${coll}) was not written: ${out.join('; ')}. Norm HK-R02: a database record that breaks a check does not reach the disk silently. Fix the record and try again.\n`);
- process.exit(BLOCK);
- }