файл пакета→ .shtukbase/packages/collections/checks/lib/pages.ts
checks/lib/pages.ts
217 строк, 10.6 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // Reading pages from disk: front matter, paths, collection records. Read-only, Bun only, no dependencies.
- // The base of every check of the standard: speclib.ts and schemalib.ts build on it, other packages import it
- // from `.shtukbase/packages/collections/checks/lib/pages.ts`.
- import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
- import { posix } from 'node:path';
- /** A page's front matter as data; values are whatever YAML gives (string, number, boolean, null, array, object). */
- export type Head = Record<string, any>;
- /** A record of a collection: `id` is the project path `/work/tasks/x.md`, `file` the file name, `kind` the caller's label. */
- export type Rec = { id: string; kind: string; fm: Head; body: string; title: string; file: string };
- export function readText(path: string): string {
- return readFileSync(path, 'utf8');
- }
- /** Python-style `str(v)`: None / True / False, lists and objects as Python prints them (messages stay the same). */
- export function pystr(v: unknown, nested = false): string {
- if (v === null || v === undefined) return 'None';
- if (typeof v === 'boolean') return v ? 'True' : 'False';
- if (typeof v === 'string') {
- if (!nested) return v;
- const q = v.includes("'") && !v.includes('"') ? '"' : "'";
- return q + v.replace(/\\/g, '\\\\').replace(/\n/g, '\\n').replace(/\t/g, '\\t').replaceAll(q, '\\' + q) + q;
- }
- if (Array.isArray(v)) return '[' + v.map((x) => pystr(x, true)).join(', ') + ']';
- if (typeof v === 'object') return '{' + Object.entries(v).map(([k, x]) => `${pystr(k, true)}: ${pystr(x, true)}`).join(', ') + '}';
- return String(v);
- }
- /** Python truthiness: the empty string, 0, null, false, `[]` and `{}` are false. */
- export function truthy(v: unknown): boolean {
- if (Array.isArray(v)) return v.length > 0;
- if (v && typeof v === 'object') return Object.keys(v).length > 0;
- return !!v;
- }
- /** Splits a page into the front matter text (between the first two `---` lines; '' when there is none) and the body. */
- export function splitFrontMatter(text: string): [string, string] {
- text = text.replace(/^+/, '');
- if (!text.startsWith('---')) return ['', text];
- const lines = text.split('\n');
- if (lines[0].trim() !== '---') return ['', text];
- for (let i = 1; i < lines.length; i++)
- if (lines[i].trimEnd() === '---') return [lines.slice(1, i).join('\n'), lines.slice(i + 1).join('\n')];
- return ['', text];
- }
- const asMap = (v: unknown): Head | null => (v && typeof v === 'object' && !Array.isArray(v) ? (v as Head) : null);
- /** Bun 1.3 reads a plain `1118-040008` or `12-3` as the number before the dash; YAML means a string. Quote such
- * values when they stand alone on a line or in a one-line flow list, so ids that start with digits survive. */
- const DIGIT_DASH = /^(\s*(?:-\s+)?(?:[^\s:#'"][^:]*:\s+)?)(\d+(?:-\d+)+)(\s*(?:#.*)?)$/gm;
- function quoteDigitDash(text: string): string {
- return text
- .replace(DIGIT_DASH, '$1"$2"$3')
- .replace(/\[[^\]\n'"]*\]/g, (list) => list.replace(/(^\[|,)(\s*)(\d+(?:-\d+)+)(?=\s*[,\]])/g, '$1$2"$3"'));
- }
- function tryYaml(text: string): Head | null {
- try {
- return asMap(Bun.YAML.parse(quoteDigitDash(text)));
- } catch {
- return null;
- }
- }
- /** Front matter text → object. Strict YAML first. Pages written by hand often are not strict (`title: A: b`, a quote
- * inside a quoted value, `@name`): then each top-level entry is parsed on its own, and a one-line value that is not
- * valid YAML is taken as the plain text it is. An entry that still cannot be read is skipped, so the record lacks that
- * field and the checks name it, instead of the whole run failing. */
- export function parseYaml(text: string): Head {
- const whole = tryYaml(text);
- if (whole) return whole;
- const out: Head = {};
- for (const block of text.split(/\n(?=[^\s#-])/)) {
- const part = tryYaml(block);
- if (part) Object.assign(out, part);
- else {
- const m = /^([^\s:#][^:]*?):[ \t]+(.+?)\s*$/.exec(block);
- const plain = m && tryYaml(`${m[1]}: ${JSON.stringify(m[2].replace(/^"(.*)"$/s, '$1'))}`);
- if (plain) Object.assign(out, plain);
- }
- }
- return out;
- }
- /** One page: its parsed front matter and its body. */
- export function readPage(path: string): { fm: Head; body: string } {
- const [head, body] = splitFrontMatter(readText(path));
- return { fm: parseYaml(head), body };
- }
- /** Collapses `..` and `.` and drops a trailing slash (what Python's `os.path.normpath` does). */
- function normpath(p: string): string {
- const n = posix.normalize(p);
- return n.length > 1 && n.endsWith('/') ? n.slice(0, -1) : n;
- }
- /** Where a bare name in a relation field is looked up, by field name (old, kept for the checks that rely on it). */
- const DEFAULT_COLL: Record<string, string> = {
- intent: '/product/intents', intents: '/product/intents',
- sc: '/product/scenarios', includes: '/product/scenarios', extends: '/product/scenarios',
- leadsTo: '/product/scenarios', needs: '/product/scenarios', feeds: '/product/scenarios',
- configuredIn: '/product/scenarios',
- actor: '/product/roles', notifies: '/product/roles', serves: '/business/roles',
- function: '/business/functions', realizes: '/business/requirements',
- requirements: '/business/requirements', supports: '/business/steps', roles: '/business/roles',
- runs: '/product/actions', calls: '/product/actions',
- };
- /** Any relation value (path, `[[wikilink]]`, `[text](path)`, bare name) → project path `/a/b.md`, or null. */
- export function normPath(v: unknown, prop?: string | null, ownId?: string | null): string | null {
- if (v === null || v === undefined) return null;
- let s = pystr(v).trim().replace(/^["']+|["']+$/g, '');
- s = s.replace(/^\[\[(.*)\]\]$/s, '$1');
- const m = /^\[[^\]]*\]\(([^)]+)\)$/.exec(s);
- if (m) s = m[1];
- s = s.split('#')[0].trim();
- if (!s) return null;
- if (!s.startsWith('/')) {
- if (s.includes('/') && ownId) s = normpath(posix.join(posix.dirname(ownId), s));
- else if (prop && Object.hasOwn(DEFAULT_COLL, prop)) s = DEFAULT_COLL[prop] + '/' + s;
- else s = '/' + s;
- }
- return s.endsWith('.md') ? s : s + '.md';
- }
- /** The state name of a status value: last path part, lower case (`/work/states/Done.md` → `done.md`), or null. */
- export function normStatus(v: unknown): string | null {
- if (v === null || v === undefined) return null;
- const s = pystr(v).trim().replace(/^\/+|\/+$/g, '');
- return s.split('/').pop()!.toLowerCase() || null;
- }
- /** Records of a collection folder (`work/tasks`, relative to the project): its `.md` files in name order. */
- export function loadCollection(project: string, kind: string, folder: string): Rec[] {
- const d = posix.join(project, folder);
- if (!existsSync(d) || !statSync(d).isDirectory()) return [];
- const recs: Rec[] = [];
- for (const name of readdirSync(d).sort()) {
- if (!name.endsWith('.md') || name.startsWith('.')) continue;
- const full = posix.join(d, name);
- if (!statSync(full, { throwIfNoEntry: false })?.isFile()) continue;
- const [head, body] = splitFrontMatter(readText(full));
- const fm = parseYaml(head);
- const heading = /^\s{0,3}#\s+(.+?)\s*$/m.exec(body)?.[1];
- const title = truthy(fm.title) ? fm.title : heading || name.slice(0, -3);
- recs.push({ id: '/' + folder + '/' + name, kind, fm, body: body.replace(/^\n+|\n+$/g, ''), title: pystr(title), file: name });
- }
- return recs;
- }
- /** `properties:` of a collection page (`work/tasks.md`): `{field: {kind, collection, multiple, ...}}`; {} if none. */
- export function schemaProperties(project: string, relFile: string): Head {
- const path = posix.join(project, relFile);
- if (!existsSync(path)) return {};
- const props = parseYaml(splitFrontMatter(readText(path))[0]).properties;
- return props && typeof props === 'object' && !Array.isArray(props) ? props : {};
- }
- /** Folders of matching nested projects and their repo-relative places, returned as absolute paths. */
- export function excludedFolders(projectDir: string, root: string, names: readonly string[]): string[] {
- const excluded = new Set<string>();
- if (!names.length) return [];
- const repo = posix.resolve(root);
- function visit(dir: string, nested: boolean): void {
- const entries = readdirSync(dir, { withFileTypes: true });
- if (nested && entries.some((e) => e.name === '.shtukbase' && e.isDirectory())) {
- const header = posix.join(dir, 'base', 'packages.md');
- const { name, folder } = existsSync(header) ? readPage(header).fm : {};
- if ([posix.basename(dir), name, folder].some((value) => names.includes(value))) {
- excluded.add(dir);
- const index = posix.join(dir, 'index.md');
- const places = existsSync(index) ? readPage(index).fm.places : undefined;
- if (Array.isArray(places)) {
- for (const place of places) {
- if (typeof place !== 'string' || !place.trim() || posix.isAbsolute(place)) continue;
- const full = posix.resolve(repo, place.trim());
- const rel = posix.relative(repo, full);
- if (rel !== '..' && !rel.startsWith('../')) excluded.add(full);
- }
- }
- }
- }
- for (const e of entries) {
- if (!e.isDirectory() || ['.git', 'node_modules', '.shtukbase'].includes(e.name)) continue;
- if (e.name === 'worktrees' && posix.basename(dir) === '.claude') continue;
- visit(posix.join(dir, e.name), true);
- }
- }
- visit(posix.resolve(projectDir), false);
- return [...excluded];
- }
- /** Walks a folder top down like Python's `os.walk` (links to folders are not entered): yields the folder path relative to
- * `root` ('.' for the root) and its file names. `enter(name, depth)` says which sub-folders to go into (depth 0 = in the root).
- * Skip folders can be absolute or relative to `root`. */
- export function* walk(root: string, enter: (name: string, depth: number) => boolean, skip: readonly string[] = []): Generator<[string, string[]]> {
- const excluded = skip.map((dir) => posix.resolve(root, dir));
- yield* walkFolder(posix.resolve(root), enter, excluded, '.', 0);
- }
- function* walkFolder(
- root: string, enter: (name: string, depth: number) => boolean, excluded: readonly string[], rel: string, depth: number,
- ): Generator<[string, string[]]> {
- const dir = posix.join(root, rel);
- if (excluded.some((folder) => dir === folder || dir.startsWith(posix.join(folder, '/')))) return;
- const files: string[] = [];
- const dirs: string[] = [];
- for (const e of readdirSync(dir, { withFileTypes: true }).sort((a, b) => (a.name < b.name ? -1 : 1))) {
- const isDir = e.isDirectory() || (e.isSymbolicLink() && statSync(posix.join(dir, e.name), { throwIfNoEntry: false })?.isDirectory());
- if (!isDir) files.push(e.name);
- else if (e.isDirectory() && enter(e.name, depth)) dirs.push(e.name);
- }
- yield [rel, files];
- for (const d of dirs) yield* walkFolder(root, enter, excluded, posix.join(rel, d), depth + 1);
- }