An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): keep upgrade --json output to one envelope when a hook prints (#6536)
Joeyb6e3f95e5f77
diff --git a/.changeset/cli-spec-upgrade-hook-stdout.md b/.changeset/cli-spec-upgrade-hook-stdout.mdnew file mode 100644index 0000000000..8cbafc36c0--- /dev/null+++ b/.changeset/cli-spec-upgrade-hook-stdout.md@@ -0,0 +1,7 @@+---+'@astryxdesign/cli': patch+---++[fix] `astryx upgrade --json` now prints exactly one JSON envelope when a post-codemod hook prints output. Anything a hook's `buildCommand` writes goes to stderr, so stdout carries only the result.++@josephfarinadiff --git a/packages/cli/api/upgrade/_adapter.mjs b/packages/cli/api/upgrade/_adapter.mjsindex 6ca0cf6a87..b6c386f869 100644--- a/packages/cli/api/upgrade/_adapter.mjs+++ b/packages/cli/api/upgrade/_adapter.mjs@@ -104,6 +104,27 @@ export function uniqueFiles(files) {];}+/**+ * Run app code with its stdout writes sent to stderr. Stdout carries only the+ * command's own output, so a hook that prints cannot corrupt `--json`.+ * @template T+ * @param {() => T | Promise<T>} fn+ * @returns {Promise<T>}+ */+async function withStdoutOnStderr(fn) {+ const realWrite = process.stdout.write;+ process.stdout.write = /** @type {any} */ (+ function (/** @type {any} */ chunk, /** @type {any[]} */ ...rest) {+ return process.stderr.write(chunk, ...rest);+ }+ );+ try {+ return await fn();+ } finally {+ process.stdout.write = realWrite;+ }+}+/*** Run the app config's post-codemod hooks (config.hooks.postCodemod).* Dry-run PREVIEWS (buildCommand still called, so a throw fails); apply executes.@@ -123,7 +144,9 @@ export async function runPostCodemodHooks(hooks, context) {);}- const cmd = await hook.buildCommand({packageDir, files});+ const cmd = await withStdoutOnStderr(() =>+ hook.buildCommand({packageDir, files}),+ );if (!cmd) {logger.log(`Post-codemod hook ${label} produced no command; skipping.`);continue;diff --git a/packages/cli/clients/cli/commands/upgrade.doc.mjs b/packages/cli/clients/cli/commands/upgrade.doc.mjsindex de60d7a4fb..49c0a9958f 100644--- a/packages/cli/clients/cli/commands/upgrade.doc.mjs+++ b/packages/cli/clients/cli/commands/upgrade.doc.mjs@@ -19,6 +19,7 @@ export const doc = {'running the registered codemods, and refreshes the fully rendered managed ' +'agent-docs block when Core or configured integration guidance changes. ' +'Dry-run by default. --apply writes codemod and receipt changes, runs hooks, then refreshes agent docs. ' ++ 'Anything a post-codemod hook prints goes to stderr, so stdout carries only the result. ' +'ShadCN-copied compositions are checked automatically during a normal upgrade, or alone with --registry.',fn: 'upgrade',options: [diff --git a/packages/cli/clients/cli/commands/upgrade.hook-output.test.mjs b/packages/cli/clients/cli/commands/upgrade.hook-output.test.mjsnew file mode 100644index 0000000000..dca08937e1--- /dev/null+++ b/packages/cli/clients/cli/commands/upgrade.hook-output.test.mjs@@ -0,0 +1,88 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Subprocess test: a post-codemod hook that prints must not corrupt the+ * `upgrade --json` envelope. Stdout carries exactly one envelope; the hook's+ * output goes to stderr.+ */++import {describe, it, expect, beforeEach, afterEach} from 'vitest';+import {spawnSync} from 'node:child_process';+import * as fs from 'node:fs';+import * as path from 'node:path';+import * as os from 'node:os';+import {fileURLToPath} from 'node:url';++const __dirname = path.dirname(fileURLToPath(import.meta.url));+const CLI = path.resolve(__dirname, '..', 'bin', 'astryx.mjs');++let tmpDir;++/** @param {string} rel @param {string} body */+function write(rel, body) {+ const file = path.join(tmpDir, rel);+ fs.mkdirSync(path.dirname(file), {recursive: true});+ fs.writeFileSync(file, body);+}++/** @param {string[]} args */+function runCli(args) {+ return spawnSync(process.execPath, [CLI, ...args], {+ cwd: tmpDir,+ encoding: 'utf8',+ timeout: 60_000,+ stdio: ['ignore', 'pipe', 'pipe'],+ env: {...process.env, FORCE_COLOR: '0', CI: ''},+ });+}++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-upgrade-hook-output-'));+ write('package.json', JSON.stringify({name: 'consumer', private: true}));+ write(+ 'node_modules/@astryxdesign/core/package.json',+ JSON.stringify({name: '@astryxdesign/core', version: '0.6.0'}),+ );+ write(+ 'src/panel.tsx',+ "import {useResizable} from '@astryxdesign/core';\n" ++ 'export const usePanel = () => useResizable({defaultSize: 250, minSizePx: 200});\n',+ );+ write(+ 'astryx.config.mjs',+ 'export default {hooks: {postCodemod: [{name: "noisy", buildCommand: ({files}) => {\n' ++ ' console.log("hook saw " + files.join(","));\n' ++ ' process.stdout.write("hook raw write\\n");\n' ++ ' return null;\n' ++ '}}]}};\n',+ );+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('upgrade post-codemod hook output', () => {+ it('keeps --json stdout to one envelope and sends hook output to stderr', () => {+ const r = runCli([+ '--json',+ 'upgrade',+ '--from',+ '0.5.0',+ '--codemod',+ 'rename-resizable-pixel-bounds',+ '--apply',+ ]);++ expect(r.signal).toBeNull();+ expect(r.status).toBe(0);+ const envelope = JSON.parse(r.stdout);+ expect(envelope.type).toBe('upgrade.run');+ expect(envelope.data.filesChanged).toBe(1);+ expect(r.stderr).toContain('hook saw src/panel.tsx');+ expect(r.stderr).toContain('hook raw write');+ expect(fs.readFileSync(path.join(tmpDir, 'src/panel.tsx'), 'utf8')).toContain(+ 'minSize: 200',+ );+ });+});