Skip to content

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

TypeScript

fix(cli): a failed write reports ERR_WRITE_FAILED, not a raw Node errno (#6621)

Joey31feb2177843
diff --git a/.changeset/cli-write-failed-error-code.md b/.changeset/cli-write-failed-error-code.md
new file mode 100644
index 0000000000..36b99ec99c
--- /dev/null
+++ b/.changeset/cli-write-failed-error-code.md
@@ -0,0 +1,20 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] A write that fails reports ERR_WRITE_FAILED instead of a raw Node errno.
+
+`astryx template` into an unwritable directory returned
+`{"error": "EACCES: permission denied, open '/home/you/project/readonly/x.tsx'",
+"code": "ERR_UNKNOWN"}`, and `swizzle` returned the `mkdir` equivalent. Two
+things were wrong: ERR_WRITE_FAILED is already in the frozen error registry for
+exactly this case, and the message carried an absolute host path where every
+other Astryx message names its target relative to the project.
+
+Both now throw ERR_WRITE_FAILED with the errno kept (it is the part that says
+what to fix) and the target named relative to the project. Nothing is left
+half-written: a `swizzle` that fails part-way removes the files it already
+copied and puts back any it replaced before it reports the error, and the
+message names any file it could not restore.
+
+@josephfarina
diff --git a/packages/cli/api/error.mjs b/packages/cli/api/error.mjs
index 29a3c04a53..89a313051b 100644
--- a/packages/cli/api/error.mjs
+++ b/packages/cli/api/error.mjs
@@ -12,6 +12,7 @@
*/
import {ERROR_CODES} from '../foundation/response/error-codes.mjs';
+import * as path from 'node:path';
export class AstryxError extends Error {
/** @type {import('../foundation/response/base').Suggestion[] | undefined} */
@@ -36,3 +37,44 @@ export class AstryxError extends Error {
if (Array.isArray(suggestions) && suggestions.length) this.suggestions = suggestions;
}
}
+
+/**
+ * The error for a write that failed on the filesystem: no permission, a
+ * read-only mount, a full disk, a path component that is not a directory.
+ *
+ * A raw Node errno error reached the envelope as
+ * `{"error": "EACCES: permission denied, open '/home/you/p/readonly/x.tsx'",
+ * "code": "ERR_UNKNOWN"}` — the wrong code (ERR_WRITE_FAILED is in the frozen
+ * registry for exactly this) and an absolute host path in the message. This
+ * keeps the errno, which is the part that tells you what to fix, and reports
+ * the target the way every other Astryx message does: relative to the project.
+ *
+ * A caller that wrote files before the failure must undo them first and pass
+ * the ones it could not restore as `unrestored`, so the message never says
+ * nothing was written when something was.
+ *
+ * @param {string} target absolute path the write was aimed at
+ * @param {string} cwd project root, for the relative form
+ * @param {unknown} cause the error the filesystem call threw
+ * @param {string[]} [unrestored] absolute paths an undo could not put back
+ * @returns {AstryxError}
+ */
+export function writeFailed(target, cwd, cause, unrestored = []) {
+ const rel = path.relative(cwd, target) || target;
+ const errno =
+ typeof (/** @type {any} */ (cause)?.code) === 'string'
+ ? /** @type {any} */ (cause).code
+ : null;
+ const why = errno === 'EACCES' || errno === 'EPERM' ? ' (no permission)' : '';
+ const outcome =
+ unrestored.length === 0
+ ? 'Nothing was written.'
+ : `Earlier writes could not all be undone: ${unrestored
+ .map(file => path.relative(cwd, file) || file)
+ .join(', ')}.`;
+ return new AstryxError(
+ `Could not write ${rel}${errno ? `: ${errno}` : ''}${why}. ${outcome}`,
+ undefined,
+ ERROR_CODES.ERR_WRITE_FAILED,
+ );
+}
diff --git a/packages/cli/api/swizzle/copy/copy.mjs b/packages/cli/api/swizzle/copy/copy.mjs
index f3b7178814..49b7f1c101 100644
--- a/packages/cli/api/swizzle/copy/copy.mjs
+++ b/packages/cli/api/swizzle/copy/copy.mjs
@@ -25,7 +25,7 @@ import {
findIntegrationComponentSource,
} from '../../../foundation/discovery/component-discovery.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
-import {AstryxError} from '../../error.mjs';
+import {AstryxError, writeFailed} from '../../error.mjs';
/** Default issue tracker for maintainer feedback after swizzling. */
const DEFAULT_ISSUES_URL = 'https://github.com/facebook/astryx/issues/new';
@@ -290,11 +290,21 @@ export async function swizzleCopy(component, options = {}) {
);
}
- fs.mkdirSync(outputDir, {recursive: true});
+ const outputDirExisted = fs.existsSync(outputDir);
+ try {
+ fs.mkdirSync(outputDir, {recursive: true});
+ } catch (err) {
+ throw writeFailed(outputDir, cwd, err);
+ }
const files = fs.readdirSync(componentDir);
let copied = 0;
let usesStyleX = false;
+ // A copy that fails part-way undoes what it already wrote, so the report is
+ // true and a retry does not trip over half a component. Each entry keeps
+ // the bytes the file had before this run (null when the copy created it).
+ /** @type {Array<{dest: string, original: Buffer|null}>} */
+ const written = [];
for (const file of files) {
if (isExcludedFromCopy(file)) continue;
const srcPath = path.join(componentDir, file);
@@ -309,7 +319,25 @@ export async function swizzleCopy(component, options = {}) {
) {
usesStyleX = true;
}
- fs.writeFileSync(path.join(outputDir, file), content);
+ const dest = path.join(outputDir, file);
+ try {
+ // The snapshot read is guarded too: a destination that cannot be read
+ // back (no permission, or a directory with this name) must still undo
+ // the earlier writes and report ERR_WRITE_FAILED.
+ const original = fs.existsSync(dest) ? fs.readFileSync(dest) : null;
+ written.push({dest, original});
+ fs.writeFileSync(dest, content);
+ } catch (err) {
+ const unrestored = undoCopy(written);
+ if (!outputDirExisted) {
+ try {
+ fs.rmdirSync(outputDir);
+ } catch {
+ // Not empty (something could not be undone), or already gone.
+ }
+ }
+ throw writeFailed(dest, cwd, err, unrestored);
+ }
copied++;
}
@@ -333,3 +361,38 @@ export async function swizzleCopy(component, options = {}) {
if (feedback) data.feedback = feedback;
return {type: 'swizzle.copy', data};
}
+
+/**
+ * Undo the writes of a copy that failed part-way, newest first: delete the
+ * files the copy created and put back the bytes of the files it replaced. A
+ * file whose bytes are already the original ones is left alone, so a write
+ * that failed before changing anything is not reported as unrestored.
+ *
+ * @param {Array<{dest: string, original: Buffer|null}>} written
+ * @returns {string[]} the files it could not restore
+ */
+function undoCopy(written) {
+ /** @type {string[]} */
+ const unrestored = [];
+ for (const {dest, original} of [...written].reverse()) {
+ try {
+ if (original == null) {
+ fs.rmSync(dest, {force: true});
+ continue;
+ }
+ /** @type {Buffer|null} */
+ let current = null;
+ try {
+ current = fs.readFileSync(dest);
+ } catch {
+ current = null;
+ }
+ if (current == null || !current.equals(original)) {
+ fs.writeFileSync(dest, original);
+ }
+ } catch {
+ unrestored.push(dest);
+ }
+ }
+ return unrestored;
+}
diff --git a/packages/cli/api/swizzle/swizzle.doc.mjs b/packages/cli/api/swizzle/swizzle.doc.mjs
index c95c6c0898..bf594dfa1f 100644
--- a/packages/cli/api/swizzle/swizzle.doc.mjs
+++ b/packages/cli/api/swizzle/swizzle.doc.mjs
@@ -101,6 +101,10 @@ export const doc = {
code: 'ERR_FILE_EXISTS',
when: 'copying would overwrite existing files and overwrite is not set',
},
+ {
+ code: 'ERR_WRITE_FAILED',
+ when: 'the output directory or a copied file could not be written (no permission, read-only mount, full disk)',
+ },
],
examples: [
{
diff --git a/packages/cli/api/template/copy/copy.mjs b/packages/cli/api/template/copy/copy.mjs
index 793f9b46f5..803b856db8 100644
--- a/packages/cli/api/template/copy/copy.mjs
+++ b/packages/cli/api/template/copy/copy.mjs
@@ -16,7 +16,7 @@ import {
isFilePathArg,
PathSafetyError,
} from '../../../foundation/fs/path-safety.mjs';
-import {AstryxError} from '../../error.mjs';
+import {AstryxError, writeFailed} from '../../error.mjs';
import {ERROR_CODES} from '../../../foundation/response/error-codes.mjs';
import {stripTemplateAssetRefs} from '../../../foundation/discovery/template-adapter.mjs';
@@ -80,13 +80,17 @@ export function templateCopy(match, {targetPath, cwd, overwrite = false}) {
);
}
- fs.mkdirSync(outputDir, {recursive: true});
-
// Strip demo image references so the scaffolded file renders without a
- // Meta-only network dependency.
+ // Meta-only network dependency. Read before any write, so a failure below
+ // leaves nothing behind.
const source = fs.readFileSync(match.filePath, 'utf-8');
const outputSource = stripTemplateAssetRefs(source);
- fs.writeFileSync(outputFilePath, outputSource);
+ try {
+ fs.mkdirSync(outputDir, {recursive: true});
+ fs.writeFileSync(outputFilePath, outputSource);
+ } catch (err) {
+ throw writeFailed(outputFilePath, cwd, err);
+ }
const relOutput = path.relative(cwd, outputDir) || '.';
return {
diff --git a/packages/cli/api/template/template.doc.mjs b/packages/cli/api/template/template.doc.mjs
index d0643d233b..e9cdb51e33 100644
--- a/packages/cli/api/template/template.doc.mjs
+++ b/packages/cli/api/template/template.doc.mjs
@@ -153,6 +153,10 @@ export const doc = {
code: 'ERR_FILE_EXISTS',
when: 'the copy target already exists and overwrite is not set',
},
+ {
+ code: 'ERR_WRITE_FAILED',
+ when: 'the copy target could not be written (no permission, read-only mount, full disk); nothing is written',
+ },
],
examples: [
{label: 'List templates', code: 'const {data} = await template();'},
diff --git a/packages/cli/clients/cli/commands/write-failure.test.mjs b/packages/cli/clients/cli/commands/write-failure.test.mjs
new file mode 100644
index 0000000000..39186a3a50
--- /dev/null
+++ b/packages/cli/clients/cli/commands/write-failure.test.mjs
@@ -0,0 +1,175 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file A write that fails on the filesystem reports ERR_WRITE_FAILED.
+ *
+ * An unwritable target produced `{"error": "EACCES: permission denied, open
+ * '/abs/host/path/readonly/x.tsx'", "code": "ERR_UNKNOWN"}` — the raw Node
+ * errno error, with the wrong code and an absolute host path in the message.
+ * ERR_WRITE_FAILED is in the frozen registry for exactly this case, and every
+ * other Astryx message names its target relative to the project.
+ */
+
+import {describe, it, expect, beforeEach, afterEach} from 'vitest';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {fileURLToPath} from 'node:url';
+import {runCli} from '../../../test-utils/run-cli.mjs';
+
+const REPO = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../../../../..');
+
+// chmod means nothing to root, so the unwritable directory would be writable
+// and the command would succeed. Skip rather than assert something false.
+const asRoot = typeof process.getuid === 'function' && process.getuid() === 0;
+
+let dir;
+let readonlyDir;
+
+beforeEach(() => {
+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-write-fail-'));
+ fs.writeFileSync(
+ path.join(dir, 'package.json'),
+ JSON.stringify({
+ name: 'scratch',
+ version: '1.0.0',
+ dependencies: {'@astryxdesign/core': '0.6.3'},
+ }),
+ );
+ fs.mkdirSync(path.join(dir, 'node_modules', '@astryxdesign'), {recursive: true});
+ fs.symlinkSync(
+ path.join(REPO, 'packages', 'core'),
+ path.join(dir, 'node_modules', '@astryxdesign', 'core'),
+ 'dir',
+ );
+ readonlyDir = path.join(dir, 'readonly');
+ fs.mkdirSync(readonlyDir);
+ fs.chmodSync(readonlyDir, 0o500);
+});
+
+afterEach(() => {
+ try {
+ fs.chmodSync(readonlyDir, 0o700);
+ } catch {
+ // already gone
+ }
+ fs.rmSync(dir, {recursive: true, force: true});
+});
+
+/** @param {string[]} args */
+const json = async args => {
+ const {status, stdout} = await runCli(['--json', ...args], {cwd: dir});
+ return {status, body: JSON.parse(stdout)};
+};
+
+describe.skipIf(asRoot)('a failed write reports ERR_WRITE_FAILED', () => {
+ it('template into an unwritable directory', async () => {
+ const {status, body} = await json(['template', 'ai-chat', 'readonly/x.tsx']);
+
+ expect(status).toBe(1);
+ expect(body.code).toBe('ERR_WRITE_FAILED');
+ expect(body.error).toContain('readonly/x.tsx');
+ expect(body.error).toContain('EACCES');
+ // The whole point of the relative form: no absolute host path escapes.
+ expect(body.error).not.toContain(dir);
+ expect(fs.existsSync(path.join(readonlyDir, 'x.tsx'))).toBe(false);
+ });
+
+ it('swizzle into an unwritable directory', async () => {
+ const {status, body} = await json([
+ 'swizzle',
+ 'Button',
+ '--output',
+ 'readonly/sub',
+ ]);
+
+ expect(status).toBe(1);
+ expect(body.code).toBe('ERR_WRITE_FAILED');
+ expect(body.error).toContain('readonly/sub');
+ expect(body.error).not.toContain(dir);
+ expect(fs.existsSync(path.join(readonlyDir, 'sub'))).toBe(false);
+ });
+
+ it('still writes normally into a writable directory', async () => {
+ const {status, body} = await json(['template', 'ai-chat', 'src/page.tsx']);
+
+ expect(status, JSON.stringify(body).slice(0, 200)).toBe(0);
+ expect(body.type).toBe('template.copy');
+ expect(fs.existsSync(path.join(dir, 'src', 'page.tsx'))).toBe(true);
+ });
+});
+
+describe.skipIf(asRoot)('a swizzle that fails part-way undoes what it wrote', () => {
+ it('restores replaced files, removes created ones, and says nothing was written', async () => {
+ // Learn the component's files, in copy order, from a successful swizzle.
+ const probe = await json(['swizzle', 'Button', '--output', 'probe']);
+ expect(probe.status, JSON.stringify(probe.body).slice(0, 200)).toBe(0);
+ const files = probe.body.data.files;
+ expect(files.length).toBeGreaterThan(1);
+ const outDir = path.join(dir, 'out', path.basename(probe.body.data.outputDir));
+
+ // The first file exists (replaceable), the middle ones do not, and the
+ // last one is read-only, so --overwrite fails after writing the others.
+ const first = files[0];
+ const middle = files.slice(1, -1);
+ const last = files[files.length - 1];
+ fs.mkdirSync(outDir, {recursive: true});
+ fs.writeFileSync(path.join(outDir, first), 'before first\n');
+ fs.writeFileSync(path.join(outDir, last), 'before last\n');
+ fs.chmodSync(path.join(outDir, last), 0o444);
+
+ const {status, body} = await json([
+ 'swizzle',
+ 'Button',
+ '--output',
+ 'out',
+ '--overwrite',
+ ]);
+ fs.chmodSync(path.join(outDir, last), 0o644);
+
+ expect(status).toBe(1);
+ expect(body.code).toBe('ERR_WRITE_FAILED');
+ expect(body.error).toContain(last);
+ expect(body.error).toContain('Nothing was written.');
+ expect(body.error).not.toContain(dir);
+ expect(fs.readFileSync(path.join(outDir, first), 'utf8')).toBe('before first\n');
+ expect(fs.readFileSync(path.join(outDir, last), 'utf8')).toBe('before last\n');
+ for (const file of middle) {
+ expect(fs.existsSync(path.join(outDir, file))).toBe(false);
+ }
+ });
+
+ it('undoes the copy when a destination cannot be read back', async () => {
+ const probe = await json(['swizzle', 'Button', '--output', 'probe']);
+ expect(probe.status, JSON.stringify(probe.body).slice(0, 200)).toBe(0);
+ const files = probe.body.data.files;
+ const outDir = path.join(dir, 'out', path.basename(probe.body.data.outputDir));
+
+ // A directory where the last file goes: the rollback snapshot cannot read
+ // it, and the earlier files are already written when the copy reaches it.
+ const first = files[0];
+ const middle = files.slice(1, -1);
+ const last = files[files.length - 1];
+ fs.mkdirSync(path.join(outDir, last), {recursive: true});
+ fs.writeFileSync(path.join(outDir, first), 'before first\n');
+
+ const {status, body} = await json([
+ 'swizzle',
+ 'Button',
+ '--output',
+ 'out',
+ '--overwrite',
+ ]);
+
+ expect(status).toBe(1);
+ expect(body.code).toBe('ERR_WRITE_FAILED');
+ expect(body.error).toContain(last);
+ expect(body.error).toContain('Nothing was written.');
+ expect(body.error).not.toContain(dir);
+ expect(fs.readFileSync(path.join(outDir, first), 'utf8')).toBe('before first\n');
+ expect(fs.statSync(path.join(outDir, last)).isDirectory()).toBe(true);
+ for (const file of middle) {
+ expect(fs.existsSync(path.join(outDir, file))).toBe(false);
+ }
+ });
+});