package file→ .shtukbase/packages/design-base/lib/files.ts
lib/files.ts
108 lines, 4.7 KB.
- // Which files of the project the design checks look at. The working directory is the project root.
- // Settings live on the page /design/design-checks.md (front matter): `scan` (folders or files to look in; default:
- // the whole project), `ignore` (globs to skip), `packageFiles` (true: also look at files that packages laid as pages;
- // default false — those are the packages' business, and their own norms cover them).
- // Folders that are never product code are skipped always: node_modules, .git, .shtukbase, build outputs, caches.
- import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
- import { join } from 'node:path';
- import { readPage } from '../../collections/checks/lib/pages.ts';
- export const SETTINGS = 'design/design-checks.md';
- export const SKIP_DIRS = new Set([
- 'node_modules', '.git', '.shtukbase', 'dist', 'build', 'out', '.next', '.turbo', '.cache', 'coverage',
- 'target', '.svelte-kit', '.vercel', '.output', 'storybook-static', '.claude', '.agents',
- ]);
- /** Test, story and generated files: not the product's screens. */
- export const NOT_PRODUCT = /(\.(test|spec|stories|story|d|fixtures?|mocks?)\.[a-z]+$)|(^|\/)(__tests__|__mocks__|fixtures?)\//;
- export type Scope = { root: string; scan: string[]; ignore: RegExp[]; packageFiles: boolean };
- const list = (v: unknown): string[] =>
- Array.isArray(v) ? v.map(String).map((s) => s.trim()).filter(Boolean) : typeof v === 'string' && v.trim() ? [v.trim()] : [];
- /** Front matter of a project page (relative path), or {} when there is no such page. */
- export function settings(rel: string, root = process.cwd()): Record<string, any> {
- const p = join(root, rel);
- return existsSync(p) ? readPage(p).fm : {};
- }
- /** A glob (`*` inside a name, `**` across folders) or a plain path prefix → a regexp on relative paths. */
- export function glob(g: string): RegExp {
- const s = g.replace(/^\.?\/+/, '').replace(/\/+$/, '');
- if (!/[*?]/.test(s)) return new RegExp(`^${s.replace(/[.+^${}()|[\]\\]/g, '\\$&')}(/|$)`);
- let re = '';
- for (let i = 0; i < s.length; i++) {
- const c = s[i];
- if (c === '*' && s[i + 1] === '*') { re += '.*'; i++; if (s[i + 1] === '/') i++; }
- else if (c === '*') re += '[^/]*';
- else if (c === '?') re += '[^/]';
- else re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
- }
- return new RegExp(`^${re}(/|$)`);
- }
- export function scope(root = process.cwd()): Scope {
- const fm = settings(SETTINGS, root);
- return {
- root,
- scan: list(fm.scan).map((s) => s.replace(/^\/+|\/+$/g, '')),
- ignore: list(fm.ignore).map(glob),
- packageFiles: fm.packageFiles === true,
- };
- }
- /** Files that packages laid into the project as pages (from .shtukbase/packages.lock). */
- export function packageFiles(root = process.cwd()): Set<string> {
- const p = join(root, '.shtukbase', 'packages.lock');
- const out = new Set<string>();
- if (!existsSync(p)) return out;
- for (const line of readFileSync(p, 'utf8').split('\n')) {
- const m = /^\s{4,}("?)([^"{}]+?)\1:\s*\{base:/.exec(line);
- if (m) out.add(m[2]);
- }
- return out;
- }
- function walk(root: string, rel: string, out: string[]): void {
- const abs = join(root, rel);
- if (!existsSync(abs)) return;
- if (!statSync(abs).isDirectory()) { out.push(rel); return; }
- for (const name of readdirSync(abs).sort()) {
- if (SKIP_DIRS.has(name)) continue;
- walk(root, rel ? `${rel}/${name}` : name, out);
- }
- }
- /** Project files (relative paths) with one of the extensions, inside the scope. `product`: skip tests and stories. */
- export function projectFiles(exts: string[], sc: Scope = scope(), product = true): string[] {
- const all: string[] = [];
- for (const start of sc.scan.length ? sc.scan : ['']) walk(sc.root, start, all);
- const laid = sc.packageFiles ? new Set<string>() : packageFiles(sc.root);
- const seen = new Set<string>();
- return all.filter((rel) => {
- if (seen.has(rel)) return false;
- seen.add(rel);
- const ext = rel.slice(rel.lastIndexOf('.') + 1).toLowerCase();
- if (!exts.includes(ext)) return false;
- if (laid.has(rel)) return false;
- if (product && NOT_PRODUCT.test(rel)) return false;
- return !sc.ignore.some((re) => re.test(rel));
- });
- }
- export function read(rel: string, root = process.cwd()): string {
- return readFileSync(join(root, rel), 'utf8');
- }
- /** 1-based line of an offset in a text. */
- export function lineAt(text: string, offset: number): number {
- let n = 1;
- for (let i = 0; i < offset && i < text.length; i++) if (text.charCodeAt(i) === 10) n++;
- return n;
- }
- /** Prints findings (one per line) and sets the exit code: the shape of every check of the design packages. */
- export function report(out: string[]): void {
- if (out.length) console.log(out.join('\n'));
- process.exitCode = out.length ? 1 : 0;
- }