mirror of
https://github.com/rcourtman/Pulse.git
synced 2026-11-28 16:58:31 +01:00
Cache file walks and reads in shared-template-audit
SharedPrimitives.guardrails.test.ts runs scripts/shared-template-audit.mjs under Vitest's default 5000ms timeout. Without caching, each of the 152 pattern guards re-walked src/ with statSync/readdirSync and re-read every matching file from disk, taking ~9.3s in Vitest (~25.1s standalone) and timing out the guardrail test locally under Vitest's default timeout. Memoize file existence checks, sorted recursive scope traversal (using dirent file types), and UTF-8 file reads per audit run, skip Set/sort for single-scope guards, and evaluate longer patterns first while preserving exact audit rules, missing-scope checks, and failure messages. Allow overriding the audit root via PULSE_SHARED_TEMPLATE_AUDIT_ROOT for isolated regression testing and add frontend-modern/scripts/__tests__/shared-template-audit.test.mjs. Contract-Neutral: Internal caching and pattern-order optimization in shared-template-audit.mjs plus a unit test; no audit rule, registry schema, UI, API, or subsystem contract delta. Change-source: pulse-maintainer
This commit is contained in:
160
frontend-modern/scripts/__tests__/shared-template-audit.test.mjs
Normal file
160
frontend-modern/scripts/__tests__/shared-template-audit.test.mjs
Normal file
@@ -0,0 +1,160 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
|
||||
const auditPath = path.join(process.cwd(), 'scripts', 'shared-template-audit.mjs');
|
||||
const temporaryRoots = [];
|
||||
|
||||
const writeFile = (root, relativePath, content) => {
|
||||
const fullPath = path.join(root, ...relativePath.split('/'));
|
||||
fs.mkdirSync(path.dirname(fullPath), { recursive: true });
|
||||
fs.writeFileSync(fullPath, content);
|
||||
};
|
||||
|
||||
const makeFixture = (registry, files) => {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'pulse-shared-template-audit-'));
|
||||
temporaryRoots.push(root);
|
||||
writeFile(root, 'scripts/shared-template-registry.json', JSON.stringify(registry, null, 2));
|
||||
for (const [relativePath, content] of Object.entries(files)) {
|
||||
writeFile(root, relativePath, content);
|
||||
}
|
||||
return {
|
||||
root,
|
||||
run: () =>
|
||||
spawnSync(process.execPath, [auditPath], {
|
||||
cwd: root,
|
||||
env: { ...process.env, PULSE_SHARED_TEMPLATE_AUDIT_ROOT: root },
|
||||
encoding: 'utf8',
|
||||
}),
|
||||
};
|
||||
};
|
||||
|
||||
afterEach(() => {
|
||||
while (temporaryRoots.length > 0) {
|
||||
fs.rmSync(temporaryRoots.pop(), { force: true, recursive: true });
|
||||
}
|
||||
});
|
||||
|
||||
describe('shared template audit', () => {
|
||||
it('detects violations across overlapping cached scopes and guards without cross-contamination', () => {
|
||||
const fixture = makeFixture(
|
||||
{
|
||||
rules: [
|
||||
{
|
||||
id: 'canonical-button',
|
||||
summary: 'Use shared Button',
|
||||
category: 'primitives',
|
||||
canonical: { path: 'src/shared/Button.tsx' },
|
||||
requiredConsumers: [{ path: 'src/features/GoodConsumer.tsx' }],
|
||||
},
|
||||
],
|
||||
patternGuards: [
|
||||
{
|
||||
id: 'no-raw-search',
|
||||
summary: 'Use SearchField',
|
||||
category: 'primitives',
|
||||
canonical: { path: 'src/shared/SearchField.tsx' },
|
||||
scopes: ['src/features'],
|
||||
allPatterns: ['type="search"'],
|
||||
allowedPaths: ['src/features/StaleAllowed.tsx'],
|
||||
},
|
||||
{
|
||||
id: 'no-raw-dialog',
|
||||
summary: 'Use Dialog',
|
||||
category: 'primitives',
|
||||
canonical: { path: 'src/shared/Dialog.tsx' },
|
||||
scopes: ['src/features'],
|
||||
allPatterns: ['role="dialog"', 'fixed inset-0'],
|
||||
},
|
||||
],
|
||||
requiredPatternGuards: [
|
||||
{
|
||||
id: 'missing-scope-check',
|
||||
summary: 'Missing scope fails closed',
|
||||
category: 'primitives',
|
||||
canonical: { path: 'src/shared/SearchField.tsx' },
|
||||
scopes: ['src/missing-dir'],
|
||||
triggerPatterns: ['placeholder='],
|
||||
requiredPatterns: ['SearchField'],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
'src/shared/Button.tsx': 'export function Button() { return null; }\n',
|
||||
'src/shared/SearchField.tsx': 'export function SearchField() { return null; }\n',
|
||||
'src/shared/Dialog.tsx': 'export function Dialog() { return null; }\n',
|
||||
'src/features/GoodConsumer.tsx':
|
||||
'import { Button } from "../shared/Button"; export const A = () => <Button />;\n',
|
||||
'src/features/StaleAllowed.tsx': 'export const B = () => <input type="text" />;\n',
|
||||
'src/features/Violating.tsx':
|
||||
'export const C = () => <div role="dialog" class="fixed inset-0"><input type="search" /></div>;\n',
|
||||
},
|
||||
);
|
||||
|
||||
const result = fixture.run();
|
||||
expect(result.status).toBe(1);
|
||||
expect(result.stderr).toContain(
|
||||
'no-raw-search: src/features/Violating.tsx recreates the shared template',
|
||||
);
|
||||
expect(result.stderr).toContain(
|
||||
'no-raw-search: allowed path src/features/StaleAllowed.tsx is stale',
|
||||
);
|
||||
expect(result.stderr).toContain(
|
||||
'no-raw-dialog: src/features/Violating.tsx recreates the shared template',
|
||||
);
|
||||
expect(result.stderr).toContain('pattern guard scope src/missing-dir does not exist');
|
||||
});
|
||||
|
||||
it('passes when all rules and cached pattern guards are satisfied', () => {
|
||||
const fixture = makeFixture(
|
||||
{
|
||||
rules: [
|
||||
{
|
||||
id: 'canonical-button',
|
||||
summary: 'Use shared Button',
|
||||
category: 'primitives',
|
||||
canonical: { path: 'src/shared/Button.tsx' },
|
||||
requiredConsumers: [{ path: 'src/features/GoodConsumer.tsx' }],
|
||||
},
|
||||
],
|
||||
patternGuards: [
|
||||
{
|
||||
id: 'no-raw-search',
|
||||
summary: 'Use SearchField',
|
||||
category: 'primitives',
|
||||
canonical: { path: 'src/shared/SearchField.tsx' },
|
||||
scopes: ['src/features'],
|
||||
allPatterns: ['type="search"'],
|
||||
},
|
||||
],
|
||||
requiredPatternGuards: [
|
||||
{
|
||||
id: 'require-search-field',
|
||||
summary: 'Compose SearchField when searching',
|
||||
category: 'primitives',
|
||||
canonical: { path: 'src/shared/SearchField.tsx' },
|
||||
scopes: ['src/features'],
|
||||
triggerPatterns: ['role="searchbox"'],
|
||||
requiredPatterns: ['SearchField'],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
'src/shared/Button.tsx': 'export function Button() { return null; }\n',
|
||||
'src/shared/SearchField.tsx': 'export function SearchField() { return null; }\n',
|
||||
'src/features/GoodConsumer.tsx':
|
||||
'import { Button } from "../shared/Button"; import { SearchField } from "../shared/SearchField"; export const A = () => <><Button /><SearchField role="searchbox" /></>;\n',
|
||||
},
|
||||
);
|
||||
|
||||
const result = fixture.run();
|
||||
expect(result.status).toBe(0);
|
||||
expect(result.stderr).toBe('');
|
||||
expect(result.stdout).toContain(
|
||||
'Shared template audit passed (1 rule, 1 pattern guard, 1 required pattern guard',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,12 +1,33 @@
|
||||
import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs';
|
||||
import { extname, relative, resolve } from 'node:path';
|
||||
|
||||
const root = resolve(new URL('..', import.meta.url).pathname);
|
||||
const root = resolve(
|
||||
process.env.PULSE_SHARED_TEMPLATE_AUDIT_ROOT || new URL('..', import.meta.url).pathname,
|
||||
);
|
||||
const registryPath = 'scripts/shared-template-registry.json';
|
||||
|
||||
const read = (path) => readFileSync(resolve(root, path), 'utf8');
|
||||
const fileContentsCache = new Map();
|
||||
const fileExistsCache = new Map();
|
||||
const scopeTreeCache = new Map();
|
||||
const collectFilesCache = new Map();
|
||||
|
||||
const read = (path) => {
|
||||
let content = fileContentsCache.get(path);
|
||||
if (content === undefined) {
|
||||
content = readFileSync(resolve(root, path), 'utf8');
|
||||
fileContentsCache.set(path, content);
|
||||
}
|
||||
return content;
|
||||
};
|
||||
const readJson = (path) => JSON.parse(read(path));
|
||||
const fileExists = (path) => existsSync(resolve(root, path));
|
||||
const fileExists = (path) => {
|
||||
let exists = fileExistsCache.get(path);
|
||||
if (exists === undefined) {
|
||||
exists = existsSync(resolve(root, path));
|
||||
fileExistsCache.set(path, exists);
|
||||
}
|
||||
return exists;
|
||||
};
|
||||
const toRegistryPath = (path) => relative(root, path).split('\\').join('/');
|
||||
|
||||
const registry = readJson(registryPath);
|
||||
@@ -44,32 +65,67 @@ const verifyCanonicalExport = (id, canonical) => {
|
||||
return canonicalExport;
|
||||
};
|
||||
|
||||
const listScopeFiles = (scopeRoot) => {
|
||||
const cached = scopeTreeCache.get(scopeRoot);
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
const files = [];
|
||||
const visitDirectory = (directoryPath) => {
|
||||
for (const entry of readdirSync(directoryPath, { withFileTypes: true })) {
|
||||
const entryPath = resolve(directoryPath, entry.name);
|
||||
if (entry.isDirectory()) {
|
||||
visitDirectory(entryPath);
|
||||
} else if (entry.isFile()) {
|
||||
files.push(toRegistryPath(entryPath));
|
||||
} else if (entry.isSymbolicLink()) {
|
||||
visitPath(entryPath);
|
||||
} else {
|
||||
files.push(toRegistryPath(entryPath));
|
||||
}
|
||||
}
|
||||
};
|
||||
const visitPath = (absolutePath) => {
|
||||
const stat = statSync(absolutePath);
|
||||
if (stat.isDirectory()) {
|
||||
visitDirectory(absolutePath);
|
||||
return;
|
||||
}
|
||||
files.push(toRegistryPath(absolutePath));
|
||||
};
|
||||
|
||||
visitPath(scopeRoot);
|
||||
files.sort();
|
||||
scopeTreeCache.set(scopeRoot, files);
|
||||
return files;
|
||||
};
|
||||
|
||||
const collectFiles = (scope, extensions) => {
|
||||
const scopeRoot = resolve(root, scope);
|
||||
if (!existsSync(scopeRoot)) {
|
||||
if (!fileExists(scope)) {
|
||||
failures.push(`pattern guard scope ${scope} does not exist`);
|
||||
return [];
|
||||
}
|
||||
|
||||
const files = [];
|
||||
const visit = (absolutePath) => {
|
||||
const stat = statSync(absolutePath);
|
||||
if (stat.isDirectory()) {
|
||||
for (const entry of readdirSync(absolutePath)) {
|
||||
visit(resolve(absolutePath, entry));
|
||||
}
|
||||
return;
|
||||
}
|
||||
const cacheKey = `${scopeRoot}\0${extensions.join(',')}`;
|
||||
const cached = collectFilesCache.get(cacheKey);
|
||||
if (cached !== undefined) return cached;
|
||||
|
||||
if (extensions.includes(extname(absolutePath))) {
|
||||
files.push(toRegistryPath(absolutePath));
|
||||
}
|
||||
};
|
||||
|
||||
visit(scopeRoot);
|
||||
const extensionSet = new Set(extensions);
|
||||
const files = listScopeFiles(scopeRoot).filter((file) => extensionSet.has(extname(file)));
|
||||
collectFilesCache.set(cacheKey, files);
|
||||
return files;
|
||||
};
|
||||
|
||||
const collectScopedFiles = (scopes, extensions) => {
|
||||
if (scopes.length === 1) {
|
||||
return collectFiles(scopes[0], extensions);
|
||||
}
|
||||
return [...new Set(scopes.flatMap((scope) => collectFiles(scope, extensions)))].sort();
|
||||
};
|
||||
|
||||
const orderPatternsForMatch = (patterns) =>
|
||||
patterns.length <= 1 ? patterns : [...patterns].sort((a, b) => b.length - a.length);
|
||||
|
||||
const getAllowedPath = (entry) => (typeof entry === 'string' ? entry : entry?.path);
|
||||
const filterGuardFiles = (files, guard) => {
|
||||
const pathIncludes = Array.isArray(guard.pathIncludes) ? guard.pathIncludes : [];
|
||||
@@ -135,17 +191,15 @@ for (const guard of patternGuards) {
|
||||
const allowedPaths = new Set(allowedEntries.map(getAllowedPath).filter(Boolean));
|
||||
const ignoredEntries = guard.ignoredPaths ?? [];
|
||||
const ignoredPaths = new Set(ignoredEntries.map(getAllowedPath).filter(Boolean));
|
||||
const files = filterGuardFiles(
|
||||
[...new Set(scopes.flatMap((scope) => collectFiles(scope, extensions)))].sort(),
|
||||
guard,
|
||||
);
|
||||
const orderedPatterns = orderPatternsForMatch(patterns);
|
||||
const files = filterGuardFiles(collectScopedFiles(scopes, extensions), guard);
|
||||
|
||||
for (const file of files) {
|
||||
if (file === guard.canonical.path) continue;
|
||||
if (ignoredPaths.has(file)) continue;
|
||||
|
||||
const source = read(file);
|
||||
const matches = patterns.every((pattern) => source.includes(pattern));
|
||||
const matches = orderedPatterns.every((pattern) => source.includes(pattern));
|
||||
if (!matches) continue;
|
||||
|
||||
if (allowedPaths.has(file)) continue;
|
||||
@@ -216,17 +270,15 @@ for (const guard of requiredPatternGuards) {
|
||||
const allowedPaths = new Set(allowedEntries.map(getAllowedPath).filter(Boolean));
|
||||
const ignoredEntries = guard.ignoredPaths ?? [];
|
||||
const ignoredPaths = new Set(ignoredEntries.map(getAllowedPath).filter(Boolean));
|
||||
const files = filterGuardFiles(
|
||||
[...new Set(scopes.flatMap((scope) => collectFiles(scope, extensions)))].sort(),
|
||||
guard,
|
||||
);
|
||||
const orderedTriggerPatterns = orderPatternsForMatch(triggerPatterns);
|
||||
const files = filterGuardFiles(collectScopedFiles(scopes, extensions), guard);
|
||||
|
||||
for (const file of files) {
|
||||
if (file === guard.canonical.path) continue;
|
||||
if (ignoredPaths.has(file)) continue;
|
||||
|
||||
const source = read(file);
|
||||
const triggered = triggerPatterns.every((pattern) => source.includes(pattern));
|
||||
const triggered = orderedTriggerPatterns.every((pattern) => source.includes(pattern));
|
||||
if (!triggered) continue;
|
||||
|
||||
if (allowedPaths.has(file)) continue;
|
||||
|
||||
Reference in New Issue
Block a user