Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

fix(doctor): say why a check was skipped and what was checked; survive unreadable folders (#7135)

Joeya4c6499e1f66
diff --git a/.changeset/doctor-says-what-it-found.md b/.changeset/doctor-says-what-it-found.md
new file mode 100644
index 0000000000..c53e58db1e
--- /dev/null
+++ b/.changeset/doctor-says-what-it-found.md
@@ -0,0 +1,14 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] Doctor says why it skipped a check and what it checked, and `doctor integration validate` no longer crashes on a folder it cannot read
+@josephfarina
+
+- A check that needs the loaded project quotes the reason the CLI could not load it, instead of only "Skipped".
+- The config check warns when astryx.config imports but the CLI cannot load the project from it. Before, it said the config loaded cleanly.
+- Integration contributions name the integrations they checked; with none loaded, the check reports info and says there is nothing to check.
+- The agent-docs check reads every file init can write (Hermes included) and looks in the project root as well as the working directory, so running doctor from a subfolder no longer reports that there are no agent docs.
+- `astryx doctor integration validate` names a folder it cannot read and keeps checking. A declared root that is a file or that cannot be read is reported as `invalid_root` or `unreadable_root` instead of a raw error or a crash.
+
+Classification: contract-restoring. No check becomes stricter: every new finding is a warning or info, and the only exit-code change is that an unreadable folder outside every root no longer crashes validation.
diff --git a/packages/cli/api/doctor/doctor.mjs b/packages/cli/api/doctor/doctor.mjs
index d023cd3e95..6c71228864 100644
--- a/packages/cli/api/doctor/doctor.mjs
+++ b/packages/cli/api/doctor/doctor.mjs
@@ -24,6 +24,7 @@ import * as fs from 'node:fs';
import * as path from 'node:path';
import {MIN_NODE_VERSION, isNodeVersionSupported} from '../../foundation/env/node-version.mjs';
+import {AGENT_DOC_PATHS} from '../../foundation/agent-docs/agent-doc-state.mjs';
import {CLI_ROOT, findCoreDir, findInstalledPackage} from '../../foundation/fs/paths.mjs';
import {explainPackageManager, getCliInvocation} from '../../foundation/env/package-manager.mjs';
import {
@@ -85,6 +86,9 @@ import {checkAppThemes, checkThemes} from './theme-checks.mjs';
* Combined project-level integration issues, including cross-package template replacement warnings.
* @property {Error|null} [configError] - Error thrown while resolving the config
* path (e.g. multiple config files present), surfaced by checkConfig as a FAIL.
+ * @property {string|null} [projectError] - Why the CLI could not load the
+ * project from its config, when it could not. Checks that need the loaded
+ * project quote it when they skip, so a skip says what was found.
*/
/* ── helpers ──────────────────────────────────────────────────────────── */
@@ -113,6 +117,64 @@ function pkgVersion(dir) {
return pkg?.version ?? null;
}
+/**
+ * The first line of an error message, bounded for a one-line check message.
+ * @param {string} message
+ * @returns {string}
+ */
+function firstLine(message) {
+ return String(message).split('\n')[0].slice(0, 300);
+}
+
+/**
+ * The message of a check that needs the loaded project and could not have it.
+ * It carries the reason the CLI gave, so the line says what Doctor found
+ * instead of only that it did not look.
+ * @param {DoctorContext} ctx
+ * @param {string} what
+ * @returns {string}
+ */
+function skippedBecause(ctx, what) {
+ return ctx.projectError
+ ? `Skipped — ${what}: ${firstLine(ctx.projectError)}`
+ : `Skipped — ${what}.`;
+}
+
+/** Integrations one message names before it counts the rest. */
+const NAMED_INTEGRATIONS = 10;
+
+/**
+ * @param {Array<{name?: string, __spec?: string}>} integrations
+ * @returns {string}
+ */
+function nameIntegrations(integrations) {
+ const names = integrations.map(
+ integration => integration.name ?? integration.__spec ?? '(integration)',
+ );
+ return names.length <= NAMED_INTEGRATIONS
+ ? names.join(', ')
+ : `${names.slice(0, NAMED_INTEGRATIONS).join(', ')} and ${names.length - NAMED_INTEGRATIONS} more`;
+}
+
+/**
+ * The project's root: the folder of its config, else of the nearest
+ * package.json above the working directory (where the config is looked for),
+ * else the working directory.
+ * @param {DoctorContext} ctx
+ * @returns {string}
+ */
+function projectRootOf(ctx) {
+ if (ctx.configPath) return path.dirname(ctx.configPath);
+ let dir = ctx.cwd;
+ for (let i = 0; i < 50; i++) {
+ if (fs.existsSync(path.join(dir, 'package.json'))) return dir;
+ const parent = path.dirname(dir);
+ if (parent === dir) break;
+ dir = parent;
+ }
+ return ctx.cwd;
+}
+
/* ── individual checks ────────────────────────────────────────────────── */
/**
@@ -255,6 +317,18 @@ export async function checkConfig(ctx) {
fix: 'Export a default object from astryx.config.mjs, e.g. `export default { integrations: [] };`.',
};
}
+ // Importing is not the whole test: the CLI also validates the config, and
+ // a config it rejects leaves every project-aware command without the
+ // project. That config is not clean, so this warns (exit code unchanged).
+ if (ctx.projectError) {
+ return {
+ id: 'config',
+ label: 'astryx.config.mjs',
+ status: 'warn',
+ message: `astryx.config.mjs loads, but the CLI could not load the project from it: ${firstLine(ctx.projectError)}`,
+ fix: 'Fix what the message names. `astryx docs authoring config` lists every field astryx.config accepts.',
+ };
+ }
return {
id: 'config',
label: 'astryx.config.mjs',
@@ -304,7 +378,7 @@ export function checkImplicitIntegrations(ctx) {
id,
label,
status: 'info',
- message: 'Skipped — the project configuration could not be read.',
+ message: skippedBecause(ctx, 'the project configuration could not be read'),
};
}
@@ -407,27 +481,30 @@ function describeUnreadableManifests(failures) {
* @returns {DoctorCheck}
*/
export function checkAgentDocs(ctx) {
- const candidates = [
- 'AGENTS.md',
- 'CLAUDE.md',
- path.join('.claude', 'CLAUDE.md'),
- '.cursorrules',
- ];
- const present = candidates.filter(rel => fs.existsSync(path.join(ctx.cwd, rel)));
+ // Every file init can write (one shared list), looked for in the working
+ // directory and in the project root: run from src/, the docs sit at the root.
+ const dirs = [...new Set([ctx.cwd, projectRootOf(ctx)])];
+ const present = dirs.flatMap(dir =>
+ AGENT_DOC_PATHS.map(rel => path.join(dir, rel)).filter(abs =>
+ fs.existsSync(abs),
+ ),
+ );
+ /** @param {string} abs */
+ const shown = abs => path.relative(ctx.cwd, abs) || path.basename(abs);
if (present.length === 0) {
return {
id: 'agent-docs',
label: 'AI agent docs',
status: 'info',
- message: 'No agent docs (CLAUDE.md / AGENTS.md / .cursorrules) found.',
+ message: `No agent docs found: looked for ${AGENT_DOC_PATHS.join(', ')} in ${dirs.map(dir => path.relative(ctx.cwd, dir) || '.').join(' and ')}.`,
fix: `Generate agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,
};
}
- const withMarkers = present.filter(rel => {
+ const withMarkers = present.filter(abs => {
try {
- const content = fs.readFileSync(path.join(ctx.cwd, rel), 'utf-8');
+ const content = fs.readFileSync(abs, 'utf-8');
return (
(content.includes('<!-- ASTRYX:START -->') || content.includes('<!-- XDS:START -->')) &&
(content.includes('<!-- ASTRYX:END -->') || content.includes('<!-- XDS:END -->'))
@@ -442,7 +519,7 @@ export function checkAgentDocs(ctx) {
id: 'agent-docs',
label: 'AI agent docs',
status: 'warn',
- message: `Agent docs present (${present.join(', ')}) but no Astryx section markers found.`,
+ message: `Agent docs present (${present.map(shown).join(', ')}) but no Astryx section markers found.`,
fix: `Add the Astryx section to your agent docs with \`${getCliInvocation(ctx.cwd)} init --features agents\`.`,
};
}
@@ -451,7 +528,7 @@ export function checkAgentDocs(ctx) {
id: 'agent-docs',
label: 'AI agent docs',
status: 'pass',
- message: `Astryx agent docs section present in ${withMarkers.join(', ')}.`,
+ message: `Astryx agent docs section present in ${withMarkers.map(shown).join(', ')}.`,
};
}
@@ -546,15 +623,31 @@ export function checkIntegrationIssues(ctx) {
id: 'integration-issues',
label: 'Integration contributions',
status: 'info',
- message: 'Skipped — the project integration graph could not be loaded.',
+ message: skippedBecause(
+ ctx,
+ 'the project integration graph could not be loaded',
+ ),
};
}
if (issues.length === 0) {
+ // "No problems" is a finding only when something was looked at.
+ const checked = (ctx.integrations ?? []).filter(
+ integration => integration.__loadError == null,
+ );
+ if (checked.length === 0) {
+ return {
+ id: 'integration-issues',
+ label: 'Integration contributions',
+ status: 'info',
+ message:
+ 'No integration is loaded, so there are no integration contributions to check.',
+ };
+ }
return {
id: 'integration-issues',
label: 'Integration contributions',
status: 'pass',
- message: 'Integration contributions and cross-package relationships are valid.',
+ message: `${checked.length} loaded integration${checked.length === 1 ? '' : 's'} checked (${nameIntegrations(checked)}): contributions and cross-package relationships are valid.`,
};
}
const errors = issues.filter(issue => issue.severity === 'error').length;
@@ -651,7 +744,7 @@ export function checkProviderIdentity(ctx) {
id,
label,
status: 'info',
- message: 'Skipped — the project configuration could not be read.',
+ message: skippedBecause(ctx, 'the project configuration could not be read'),
};
}
@@ -1151,33 +1244,48 @@ export async function runChecks(options = {}) {
let integrationIssues = null;
/** @type {Array<{spec: string, error: string}>|null} */
let autolinkFailures = null;
+ /** @type {string|null} */
+ let projectError = null;
+ /** @type {import('../../foundation/config/project.mjs').Project | null} */
+ let project = null;
try {
- const project = await Project.load(cwd);
- integrations = project.loadedIntegrations;
- // An installed dependency whose manifest cannot be loaded is kept out of
- // loadedIntegrations on purpose. The provider ledger still records it.
- autolinkFailures = [...providerLedgerOf(project).values()]
- .filter(
- entry =>
- entry.outcome === 'load-failed' &&
- entry.candidate.source === 'autolinked',
- )
- .map(entry => ({
- spec: entry.candidate.spec ?? entry.label,
- error: entry.error ?? 'its manifest could not be loaded',
- }));
+ project = await Project.load(cwd);
+ } catch (err) {
+ // A project the CLI cannot load leaves the checks that need it
+ // skipped. The reason is kept: those checks and the config
+ // check quote it, so a skip is never silent.
+ projectError = err instanceof Error ? err.message : String(err);
+ }
+ if (project) {
try {
- docsCatalog = await project.docs();
- docsCatalogIssues = (await project.issues()).filter(
- issue => issue.code === 'invalid_doc',
- );
- } catch (err) {
- docsCatalog = null;
- docsCatalogError = err instanceof Error ? err.message : String(err);
+ integrations = project.loadedIntegrations;
+ // An installed dependency whose manifest cannot be loaded is kept out of
+ // loadedIntegrations on purpose. The provider ledger still records it.
+ autolinkFailures = [...providerLedgerOf(project).values()]
+ .filter(
+ entry =>
+ entry.outcome === 'load-failed' &&
+ entry.candidate.source === 'autolinked',
+ )
+ .map(entry => ({
+ spec: entry.candidate.spec ?? entry.label,
+ error: entry.error ?? 'its manifest could not be loaded',
+ }));
+ try {
+ docsCatalog = await project.docs();
+ docsCatalogIssues = (await project.issues()).filter(
+ issue => issue.code === 'invalid_doc',
+ );
+ } catch (err) {
+ docsCatalog = null;
+ docsCatalogError = err instanceof Error ? err.message : String(err);
+ }
+ integrationIssues = await project.issues();
+ } catch {
+ // Best-effort: once the project has loaded, a later read that throws
+ // leaves the remaining fields at their defaults. It is no reason to
+ // blame the config, so it never becomes projectError.
}
- integrationIssues = await project.issues();
- } catch {
- // Best-effort: a missing or invalid config leaves integrations unavailable.
}
/** @type {DoctorContext} */
@@ -1193,6 +1301,7 @@ export async function runChecks(options = {}) {
integrationIssues,
autolinkFailures,
configError,
+ projectError,
};
/** @type {DoctorCheck[]} */
diff --git a/packages/cli/api/doctor/doctor.test.mjs b/packages/cli/api/doctor/doctor.test.mjs
index d02d1b8d2a..d72ad878ff 100644
--- a/packages/cli/api/doctor/doctor.test.mjs
+++ b/packages/cli/api/doctor/doctor.test.mjs
@@ -1018,3 +1018,107 @@ describe('doctor says what it could not check', () => {
expect(check.message).toContain('could not be read');
});
});
+
+describe('doctor says why it skipped and what it checked', () => {
+ const CORE_STUB = {
+ 'node_modules/@astryxdesign/core/package.json': JSON.stringify({
+ name: '@astryxdesign/core',
+ version: '0.6.3',
+ }),
+ };
+
+ /** A project under the working directory, so its config can be imported. */
+ function cwdProject(files) {
+ const dir = fs.mkdtempSync(
+ path.join(process.cwd(), '.astryx-doctor-shape-'),
+ );
+ tmpDirs.push(dir);
+ for (const [rel, content] of Object.entries(files)) {
+ const abs = path.join(dir, rel);
+ fs.mkdirSync(path.dirname(abs), {recursive: true});
+ fs.writeFileSync(abs, content);
+ }
+ return dir;
+ }
+
+ it(
+ 'warns, and quotes the reason, when the CLI cannot load the project from a config that imports',
+ async () => {
+ const dir = cwdProject({
+ 'package.json': '{"name":"app"}',
+ ...CORE_STUB,
+ 'astryx.config.mjs': "export default { integrations: 'oops' };\n",
+ });
+ const {checks, summary} = (await doctor({cwd: dir})).data;
+ const by = Object.fromEntries(checks.map(c => [c.id, c]));
+ expect(by.config.status).toBe('warn');
+ expect(by.config.message).toMatch(
+ /^astryx\.config\.mjs loads, but the CLI could not load the project from it: .*integrations/,
+ );
+ expect(by.config.fix).toContain('astryx docs authoring config');
+ for (const id of ['implicit-integrations', 'provider-identity']) {
+ expect(by[id].message).toMatch(
+ /^Skipped — the project configuration could not be read: .*integrations/,
+ );
+ }
+ expect(by['integration-issues'].message).toMatch(
+ /^Skipped — the project integration graph could not be loaded: .*integrations/,
+ );
+ // A warning: the exit code a released CLI gave this project is unchanged.
+ expect(summary.fail).toBe(0);
+ },
+ SLOW,
+ );
+
+ it(
+ 'passes the config check when the CLI loads the project from it',
+ async () => {
+ const dir = cwdProject({
+ 'package.json': '{"name":"app"}',
+ ...CORE_STUB,
+ 'astryx.config.mjs': 'export default { integrations: [] };\n',
+ });
+ const by = Object.fromEntries(
+ (await doctor({cwd: dir})).data.checks.map(c => [c.id, c]),
+ );
+ expect(by.config.status).toBe('pass');
+ expect(by['implicit-integrations'].message).not.toContain('Skipped');
+ },
+ SLOW,
+ );
+
+ it('says there is nothing to check when no integration is loaded', () => {
+ expect(
+ checkIntegrationIssues({integrationIssues: [], integrations: []}),
+ ).toEqual({
+ id: 'integration-issues',
+ label: 'Integration contributions',
+ status: 'info',
+ message:
+ 'No integration is loaded, so there are no integration contributions to check.',
+ });
+ });
+
+ it('names what it checked when every loaded integration is clean', () => {
+ expect(
+ checkIntegrationIssues({
+ integrationIssues: [],
+ integrations: [{name: '@acme/widgets'}],
+ }),
+ ).toMatchObject({
+ status: 'pass',
+ message:
+ '1 loaded integration checked (@acme/widgets): contributions and cross-package relationships are valid.',
+ });
+ });
+
+ it('bounds the names it lists', () => {
+ const integrations = Array.from({length: 12}, (_, i) => ({
+ name: `@acme/kit-${i}`,
+ }));
+ const c = checkIntegrationIssues({integrationIssues: [], integrations});
+ expect(c.message).toMatch(
+ /^12 loaded integrations checked \(.* and 2 more\): /,
+ );
+ });
+});
diff --git a/packages/cli/api/integration/validate-integration.mjs b/packages/cli/api/integration/validate-integration.mjs
index cc4712c10e..c6d0157a64 100644
--- a/packages/cli/api/integration/validate-integration.mjs
+++ b/packages/cli/api/integration/validate-integration.mjs
@@ -57,6 +57,7 @@ import {
validateLoadedIntegration,
issueError as error,
issueWarning as warning,
+ rootProblem,
} from '../../foundation/integrations/validate-contributions.mjs';
export {validateLoadedIntegration};
@@ -161,9 +162,24 @@ async function findUnreachableContributionIssues(packageDir, loaded) {
/** @param {string} dir */
async function walk(dir) {
if (roots.some(root => pathIsInside(dir, root))) return;
- const entries = fs
- .readdirSync(dir, {withFileTypes: true})
- .sort((a, b) => a.name.localeCompare(b.name));
+ let entries;
+ try {
+ entries = fs
+ .readdirSync(dir, {withFileTypes: true})
+ .sort((a, b) => a.name.localeCompare(b.name));
+ } catch (err) {
+ // One folder the user running astryx cannot read must not end the whole
+ // validation: name it and keep checking the rest of the package.
+ const shown = `${path.relative(packageDir, dir).split(path.sep).join('/') || '.'}/`;
+ const reason = /** @type {any} */ (err)?.code ?? String(err);
+ issues.push(
+ warning(
+ 'unreadable_folder',
+ `Could not read "${shown}" (${reason}), so it was not checked for contributions outside a declared root. Fix: make it readable by the user running astryx, or remove it if it does not belong in the package.`,
+ ),
+ );
+ return;
+ }
for (const entry of entries) {
if (truncated) return;
if (UNREACHABLE_SKIP_DIRS.has(entry.name)) continue;
@@ -312,7 +328,7 @@ async function validateAtPackageDir(
// Roots + contribution checks are shared with validateLoadedIntegration so
// the everyday-command nudge runs the exact same validators.
issues.push(...(await validateLoadedIntegration(loaded)));
- if (loaded.themes)
+ if (loaded.themes && !rootProblem(loaded.themes))
issues.push(...unreadThemeFolderIssues(packageDir, loaded));
if (scanUnreachable) {
issues.push(
diff --git a/packages/cli/api/integration/validate-integration.test.mjs b/packages/cli/api/integration/validate-integration.test.mjs
index 88e20833be..e9a9c766dc 100644
--- a/packages/cli/api/integration/validate-integration.test.mjs
+++ b/packages/cli/api/integration/validate-integration.test.mjs
@@ -680,3 +680,76 @@ describe('validated separates "checked and clean" from "never checked"', () => {
expect(summarizeIssues(res.data.issues).errors).toBeGreaterThan(0);
});
});
+
+describe('unreadable folders are reported, never fatal', () => {
+ // Root reads every folder, so permission cases cannot be staged as root.
+ const asRoot = typeof process.getuid === 'function' && process.getuid() === 0;
+ /** @type {string[]} */
+ const locked = [];
+ afterEach(() => {
+ while (locked.length) fs.chmodSync(locked.pop(), 0o755);
+ });
+ /** @param {string} dir */
+ const lock = dir => {
+ fs.chmodSync(dir, 0o000);
+ locked.push(dir);
+ };
+
+ it.skipIf(asRoot)(
+ 'names a folder it cannot read and checks the rest of the package',
+ async () => {
+ const pkgDir = path.join(tmpDir, 'pkg');
+ writePackage(pkgDir, {
+ manifest: "export default { components: './components' };\n",
+ });
+ fs.mkdirSync(path.join(pkgDir, 'components'));
+ fs.mkdirSync(path.join(pkgDir, 'cache'));
+ lock(path.join(pkgDir, 'cache'));
+ const result = await validateLocalIntegration(pkgDir);
+ expect(byCode(result.issues, 'unreadable_folder')).toEqual([
+ expect.objectContaining({
+ severity: 'warning',
+ message: expect.stringContaining('Could not read "cache/" (EACCES)'),
+ }),
+ ]);
+ expect(summarizeIssues(result.issues).errors).toBe(0);
+ },
+ );
+
+ it.skipIf(asRoot)(
+ 'reports a declared root it cannot read as unreadable_root',
+ async () => {
+ const pkgDir = path.join(tmpDir, 'pkg');
+ writePackage(pkgDir, {
+ manifest:
+ "export default { codemods: './codemods', themes: './themes' };\n",
+ });
+ fs.mkdirSync(path.join(pkgDir, 'codemods'));
+ fs.mkdirSync(path.join(pkgDir, 'themes'));
+ lock(path.join(pkgDir, 'codemods'));
+ lock(path.join(pkgDir, 'themes'));
+ const result = await validateLocalIntegration(pkgDir);
+ expect(
+ byCode(result.issues, 'unreadable_root').map(issue => issue.message),
+ ).toEqual([
+ expect.stringMatching(/^Declared codemods root cannot be read \(EACCES\)/),
+ expect.stringMatching(/^Declared themes root cannot be read \(EACCES\)/),
+ ]);
+ },
+ );
+
+ it('reports a declared root that is a file as invalid_root', async () => {
+ const pkgDir = path.join(tmpDir, 'pkg');
+ writePackage(pkgDir, {
+ manifest: "export default { codemods: './codemods.mjs' };\n",
+ });
+ fs.writeFileSync(path.join(pkgDir, 'codemods.mjs'), 'export default {};\n');
+ const result = await validateLocalIntegration(pkgDir);
+ expect(byCode(result.issues, 'invalid_root')).toEqual([
+ expect.objectContaining({
+ severity: 'error',
+ message: expect.stringContaining('is a file, not a folder'),
+ }),
+ ]);
+ });
+});
diff --git a/packages/cli/clients/cli/commands/doctor.test.mjs b/packages/cli/clients/cli/commands/doctor.test.mjs
index 2d371ac93f..04931a1ad1 100644
--- a/packages/cli/clients/cli/commands/doctor.test.mjs
+++ b/packages/cli/clients/cli/commands/doctor.test.mjs
@@ -202,6 +202,39 @@ describe('doctor — individual checks', () => {
expect(res.status).toBe('pass');
});
+ it('agent-docs: PASS from a subfolder, reading the project root', () => {
+ fs.writeFileSync(path.join(tmpDir, 'package.json'), '{"name":"app"}');
+ fs.writeFileSync(
+ path.join(tmpDir, 'AGENTS.md'),
+ '<!-- ASTRYX:START -->\nstuff\n<!-- ASTRYX:END -->\n',
+ );
+ const src = path.join(tmpDir, 'src');
+ fs.mkdirSync(src);
+ const res = checkAgentDocs({cwd: src});
+ expect(res.status).toBe('pass');
+ expect(res.message).toBe(
+ `Astryx agent docs section present in ${path.join('..', 'AGENTS.md')}.`,
+ );
+ });
+
+ it('agent-docs: reads every file init can write, Hermes included', () => {
+ fs.writeFileSync(
+ path.join(tmpDir, 'HERMES.md'),
+ '<!-- ASTRYX:START -->\nstuff\n<!-- ASTRYX:END -->\n',
+ );
+ expect(checkAgentDocs({cwd: tmpDir})).toMatchObject({
+ status: 'pass',
+ message: 'Astryx agent docs section present in HERMES.md.',
+ });
+ });
+
+ it('agent-docs: INFO names what it looked for and where', () => {
+ const res = checkAgentDocs({cwd: tmpDir});
+ expect(res.status).toBe('info');
+ expect(res.message).toContain('AGENTS.md, CLAUDE.md');
+ expect(res.message).toContain('HERMES.md');
+ });
+
it('peer-deps: INFO when core not installed', () => {
const res = checkPeerDeps({cwd: tmpDir, coreDir: null});
expect(res.status).toBe('info');
diff --git a/packages/cli/foundation/integrations/validate-contributions.mjs b/packages/cli/foundation/integrations/validate-contributions.mjs
index 1aaf1cc79c..3c05fa990d 100644
--- a/packages/cli/foundation/integrations/validate-contributions.mjs
+++ b/packages/cli/foundation/integrations/validate-contributions.mjs
@@ -99,8 +99,40 @@ function checkUnknownKeys(integration, issues) {
}
/**
- * Verify each declared contribution root exists on disk. A declared-but-missing
- * root is a `missing_root` error.
+ * Why a declared root cannot be read as a folder, or null when it can.
+ * A missing root keeps its own issue; a root that is a file or that the
+ * user running astryx cannot read used to surface as a raw errno from
+ * whichever check touched it first, or end validation outright.
+ * @param {string} root
+ * @returns {{kind: 'missing'} | {kind: 'not-a-folder'} | {kind: 'unreadable', code: string} | null}
+ */
+export function rootProblem(root) {
+ let stat;
+ try {
+ stat = fs.statSync(root);
+ } catch (err) {
+ const code = /** @type {any} */ (err)?.code;
+ return code === 'ENOENT' || code === 'ENOTDIR'
+ ? {kind: 'missing'}
+ : {kind: 'unreadable', code: String(code ?? 'unknown error')};
+ }
+ if (!stat.isDirectory()) return {kind: 'not-a-folder'};
+ try {
+ fs.accessSync(root, fs.constants.R_OK | fs.constants.X_OK);
+ } catch (err) {
+ return {
+ kind: 'unreadable',
+ code: String(/** @type {any} */ (err)?.code ?? 'unknown error'),
+ };
+ }
+ return null;
+}
+
+/**
+ * Verify each declared contribution root is a folder Astryx can read. A
+ * declared-but-missing root is a `missing_root` error, a file is an
+ * `invalid_root` error, and a folder that cannot be read is an
+ * `unreadable_root` error. The contribution checks skip all three.
* @param {{components?: string, templates?: string, codemods?: string, docs?: string, themes?: string}} resolved
* absolute resolved roots (undefined when not declared)
* @param {Issue[]} issues
@@ -116,13 +148,29 @@ function checkRoots(resolved, issues) {
for (const kind of kinds) {
const root = resolved[kind];
if (root == null) continue;
- if (!fs.existsSync(root)) {
+ const problem = rootProblem(root);
+ if (problem == null) continue;
+ if (problem.kind === 'missing') {
issues.push(
issueError(
'missing_root',
`Declared ${kind} root does not exist on disk: ${root}`,
),
);
+ } else if (problem.kind === 'not-a-folder') {
+ issues.push(
+ issueError(
+ 'invalid_root',
+ `Declared ${kind} root is a file, not a folder: ${root}. Fix: point "${kind}" in the manifest at the folder that holds them.`,
+ ),
+ );
+ } else {
+ issues.push(
+ issueError(
+ 'unreadable_root',
+ `Declared ${kind} root cannot be read (${problem.code}): ${root}. Fix: make it readable by the user running astryx.`,
+ ),
+ );
}
}
}
@@ -135,7 +183,7 @@ function checkRoots(resolved, issues) {
* @param {Issue[]} issues
*/
async function checkCodemods(integration, issues) {
- if (!integration.codemods || !fs.existsSync(integration.codemods)) return;
+ if (!integration.codemods || rootProblem(integration.codemods)) return;
const context = integration.__packageDir
? createFixContext(integration.__packageDir, integration)
: null;
@@ -232,7 +280,7 @@ async function checkCodemods(integration, issues) {
* @param {Issue[]} issues
*/
async function checkTemplates(integration, issues) {
- if (!integration.templates || !fs.existsSync(integration.templates)) return;
+ if (!integration.templates || rootProblem(integration.templates)) return;
try {
const {errors} = await discoverIntegrationTemplatesForOne(integration);
for (const e of errors) {
@@ -257,7 +305,7 @@ async function checkTemplates(integration, issues) {
* @param {Issue[]} issues
*/
async function checkComponents(integration, issues) {
- if (!integration.components || !fs.existsSync(integration.components)) return;
+ if (!integration.components || rootProblem(integration.components)) return;
const discover = componentDiscovery.discoverValidIntegrationComponents;
if (typeof discover !== 'function') return; // feature not present yet
try {
@@ -330,7 +378,7 @@ async function checkComponents(integration, issues) {
* @param {Issue[]} issues
*/
async function checkDocs(integration, issues) {
- if (!integration.docs || !fs.existsSync(integration.docs)) return;
+ if (!integration.docs || rootProblem(integration.docs)) return;
try {
const {errors} = await discoverIntegrationDocs(integration);
for (const e of errors) {
@@ -349,7 +397,7 @@ async function checkDocs(integration, issues) {
* @param {Issue[]} issues
*/
async function checkThemes(integration, issues) {
- if (!integration.themes || !fs.existsSync(integration.themes)) return;
+ if (!integration.themes || rootProblem(integration.themes)) return;
try {
await discoverIntegrationThemes(integration);
} catch (err) {