Skip to content

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

TypeScript

fix(cli): keep --json output to one envelope when a config or manifest prints (#6581)

Joeydd7d9e4b0e3c
diff --git a/.changeset/cli-spec-project-module-stdout.md b/.changeset/cli-spec-project-module-stdout.md
new file mode 100644
index 0000000000..d77c69a47d
--- /dev/null
+++ b/.changeset/cli-spec-project-module-stdout.md
@@ -0,0 +1,7 @@
+---
+'@astryxdesign/cli': patch
+---
+
+[fix] `--json` output is one envelope again when `astryx.config` or an integration manifest prints while it loads. Anything a project module writes to stdout during its load now goes to stderr.
+
+@josephfarina
diff --git a/packages/cli/foundation/fs/module-loader.mjs b/packages/cli/foundation/fs/module-loader.mjs
index 4ad95b2512..e0e045a1cc 100644
--- a/packages/cli/foundation/fs/module-loader.mjs
+++ b/packages/cli/foundation/fs/module-loader.mjs
@@ -7,7 +7,8 @@
* user-authored module (`.ts` via jiti, `.mjs`/`.js` via native dynamic
* import) and (b) find conventional files by basename in a fixed
* load-precedence order. These helpers centralize that so the two callers stay
- * in lockstep.
+ * in lockstep. A module's stdout writes go to stderr while it loads, so
+ * project code that prints cannot corrupt a `--json` envelope.
*
* `loadModuleWithParser` builds on these primitives to provide the single
* load/validation boundary shared by config, integration, codemod, and
@@ -16,6 +17,7 @@
*/
import * as path from 'node:path';
+import {AsyncLocalStorage} from 'node:async_hooks';
import {createRequire} from 'node:module';
import {pathToFileURL} from 'node:url';
import * as fs from 'node:fs';
@@ -56,6 +58,43 @@ function isCommonJsFile(file) {
}
}
+let loadsInFlight = 0;
+/** @type {typeof process.stdout.write | undefined} */
+let realStdoutWrite;
+/** Set in the async context of a module load, and only there. */
+const moduleLoad = new AsyncLocalStorage();
+
+/**
+ * Run a module load with the stdout writes made in its async context sent to
+ * stderr. Writes from any other context pass through, so the CLI's own output
+ * stays on stdout even while an abandoned load is still in flight. The gate
+ * is installed for the first overlapping load and removed after the last.
+ * @template T
+ * @param {() => Promise<T>} load
+ * @returns {Promise<T>}
+ */
+async function withStdoutOnStderr(load) {
+ if (loadsInFlight++ === 0) {
+ const write = process.stdout.write;
+ realStdoutWrite = write;
+ process.stdout.write = /** @type {any} */ (
+ function (/** @type {any} */ chunk, /** @type {any[]} */ ...rest) {
+ return moduleLoad.getStore()
+ ? process.stderr.write(chunk, ...rest)
+ : write.call(process.stdout, chunk, ...rest);
+ }
+ );
+ }
+ try {
+ return await moduleLoad.run(true, load);
+ } finally {
+ if (--loadsInFlight === 0 && realStdoutWrite) {
+ process.stdout.write = realStdoutWrite;
+ realStdoutWrite = undefined;
+ }
+ }
+}
+
/**
* Import a user-authored module. `.ts` is loaded via jiti; `.mjs`/`.js` use
* native dynamic import for ordinary cached reads. A fresh `.ts` read uses a
@@ -64,12 +103,22 @@ function isCommonJsFile(file) {
* nearest package.json `type` decides `.js`, matching Node's package scopes.
* Normal loads retain module caching. `fresh` is an explicit migration-only
* escape hatch for rereading files that a codemod changed during this process.
+ * Anything the module writes to stdout while it loads goes to stderr.
*
* @param {string} file absolute path
* @param {{fresh?: boolean}} [options]
* @returns {Promise<Record<string, unknown>>}
*/
export async function importUserModule(file, {fresh = false} = {}) {
+ return await withStdoutOnStderr(() => importModule(file, fresh));
+}
+
+/**
+ * @param {string} file absolute path
+ * @param {boolean} fresh
+ * @returns {Promise<Record<string, unknown>>}
+ */
+async function importModule(file, fresh) {
if (fresh && file.endsWith('.ts')) {
return await createJiti(import.meta.url, {moduleCache: false}).import(file);
}
diff --git a/packages/cli/foundation/fs/module-loader.stdout.test.mjs b/packages/cli/foundation/fs/module-loader.stdout.test.mjs
new file mode 100644
index 0000000000..ac52809253
--- /dev/null
+++ b/packages/cli/foundation/fs/module-loader.stdout.test.mjs
@@ -0,0 +1,332 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file A project module that prints while it loads must not reach stdout.
+ * Every `astryx.config.*` and integration manifest runs through
+ * `importUserModule`, so one stray `console.log` there used to corrupt every
+ * `--json` envelope. The loader cases run in a real Node process (vitest
+ * replaces `console`); the CLI cases spawn the real binary.
+ */
+
+import {afterEach, beforeEach, describe, expect, it} from 'vitest';
+import {spawnSync} from 'node:child_process';
+import * as fs from 'node:fs';
+import * as os from 'node:os';
+import * as path from 'node:path';
+import {fileURLToPath, pathToFileURL} from 'node:url';
+
+const HERE = path.dirname(fileURLToPath(import.meta.url));
+const LOADER_URL = pathToFileURL(path.join(HERE, 'module-loader.mjs')).href;
+const CLI = path.resolve(HERE, '..', '..', 'clients', 'cli', 'bin', 'astryx.mjs');
+
+const PRINTS =
+ "console.log('module log');\nprocess.stdout.write('module write\\n');\n";
+
+let tmpDir;
+
+beforeEach(() => {
+ tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'astryx-module-stdout-'));
+});
+
+afterEach(() => {
+ fs.rmSync(tmpDir, {recursive: true, force: true});
+});
+
+/** @param {string} rel @param {string} body @returns {string} */
+function write(rel, body) {
+ const file = path.join(tmpDir, rel);
+ fs.mkdirSync(path.dirname(file), {recursive: true});
+ fs.writeFileSync(file, body);
+ return file;
+}
+
+/**
+ * Run `body` as an ES module in a real Node process with `importUserModule`
+ * in scope.
+ * @param {string} body
+ */
+function runWithLoader(body) {
+ return spawnSync(
+ process.execPath,
+ [
+ '--input-type=module',
+ '-e',
+ `import {importUserModule} from ${JSON.stringify(LOADER_URL)};\n${body}`,
+ ],
+ {encoding: 'utf8', timeout: 60_000, stdio: ['ignore', 'pipe', 'pipe']},
+ );
+}
+
+describe('importUserModule keeps module output off stdout', () => {
+ it.each([
+ ['.mjs', 'mod.mjs', false, `${PRINTS}export default {answer: 42};\n`],
+ ['ESM .js', 'esm/mod.js', false, `${PRINTS}export default {answer: 42};\n`],
+ [
+ '.ts',
+ 'mod.ts',
+ false,
+ `${PRINTS}const answer: number = 42;\nexport default {answer};\n`,
+ ],
+ ['fresh .mjs', 'mod.mjs', true, `${PRINTS}export default {answer: 42};\n`],
+ [
+ 'fresh .ts',
+ 'mod.ts',
+ true,
+ `${PRINTS}const answer: number = 42;\nexport default {answer};\n`,
+ ],
+ [
+ 'fresh CommonJS .js',
+ 'cjs/mod.js',
+ true,
+ `${PRINTS}module.exports = {answer: 42};\n`,
+ ],
+ ])('sends a printing %s module to stderr', (_label, rel, fresh, source) => {
+ write('esm/package.json', JSON.stringify({type: 'module'}));
+ write('cjs/package.json', JSON.stringify({type: 'commonjs'}));
+ const file = write(rel, source);
+
+ const r = runWithLoader(
+ `const before = process.stdout.write;
+const mod = await importUserModule(${JSON.stringify(file)}, {fresh: ${fresh}});
+process.stdout.write(JSON.stringify({answer: mod.default?.answer, restored: process.stdout.write === before}));`,
+ );
+
+ expect(r.status, r.stderr).toBe(0);
+ expect(JSON.parse(r.stdout)).toEqual({answer: 42, restored: true});
+ expect(r.stderr).toContain('module log');
+ expect(r.stderr).toContain('module write');
+ });
+
+ it('keeps stdout redirected until the last overlapping load settles', () => {
+ const first = write(
+ 'first.mjs',
+ "await new Promise(resolve => setTimeout(resolve, 20));\nprocess.stdout.write('first write\\n');\nexport default 'first';\n",
+ );
+ const second = write(
+ 'second.mjs',
+ "await new Promise(resolve => setTimeout(resolve, 150));\nprocess.stdout.write('second write\\n');\nexport default 'second';\n",
+ );
+
+ const r = runWithLoader(
+ `const before = process.stdout.write;
+const mods = await Promise.all([
+ importUserModule(${JSON.stringify(first)}),
+ importUserModule(${JSON.stringify(second)}),
+]);
+process.stdout.write(JSON.stringify({loaded: mods.map(mod => mod.default), restored: process.stdout.write === before}));`,
+ );
+
+ expect(r.status, r.stderr).toBe(0);
+ expect(JSON.parse(r.stdout)).toEqual({
+ loaded: ['first', 'second'],
+ restored: true,
+ });
+ expect(r.stderr).toContain('first write');
+ expect(r.stderr).toContain('second write');
+ });
+
+ it('leaves the caller on stdout while an abandoned load is still in flight', () => {
+ const slow = write(
+ 'slow.mjs',
+ "await new Promise(resolve => setTimeout(resolve, 150));\nprocess.stdout.write('slow write\\n');\nexport default 'slow';\n",
+ );
+
+ const r = runWithLoader(
+ `const before = process.stdout.write;
+const slow = importUserModule(${JSON.stringify(slow)});
+const sibling = new Promise((_, reject) => setTimeout(() => reject(new Error('sibling failed')), 10));
+try {
+ await Promise.all([slow, sibling]);
+} catch (error) {
+ process.stdout.write('caught: ' + error.message + '\\n');
+}
+await slow;
+process.stdout.write('restored: ' + (process.stdout.write === before) + '\\n');`,
+ );
+
+ expect(r.status, r.stderr).toBe(0);
+ expect(r.stdout).toBe('caught: sibling failed\nrestored: true\n');
+ expect(r.stderr).toContain('slow write');
+ });
+
+ it('restores stdout when the module throws', () => {
+ const file = write(
+ 'boom.mjs',
+ "process.stdout.write('boom write\\n');\nthrow new Error('boom');\n",
+ );
+
+ const r = runWithLoader(
+ `const before = process.stdout.write;
+let message = null;
+try {
+ await importUserModule(${JSON.stringify(file)});
+} catch (error) {
+ message = error.message;
+}
+process.stdout.write(JSON.stringify({message, restored: process.stdout.write === before}));`,
+ );
+
+ expect(r.status, r.stderr).toBe(0);
+ expect(JSON.parse(r.stdout)).toEqual({message: 'boom', restored: true});
+ expect(r.stderr).toContain('boom write');
+ });
+});
+
+/** @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: ''},
+ });
+}
+
+/**
+ * Stdout must be exactly one envelope and the module's output must be on
+ * stderr.
+ * @param {ReturnType<typeof runCli>} r
+ * @param {string} printed
+ */
+function expectOneEnvelope(r, printed) {
+ expect(r.signal).toBeNull();
+ const envelope = JSON.parse(r.stdout);
+ expect(envelope.apiVersion).toBe(1);
+ expect(r.stdout).not.toContain(printed);
+ expect(r.stderr).toContain(printed);
+ return envelope;
+}
+
+/** A declared dependency that ships a printing manifest and one component. */
+function installNoisyIntegration() {
+ write(
+ 'package.json',
+ JSON.stringify({
+ name: 'consumer',
+ private: true,
+ type: 'module',
+ dependencies: {'@acme/noisy': '1.0.0'},
+ }),
+ );
+ write(
+ 'node_modules/@acme/noisy/package.json',
+ JSON.stringify({name: '@acme/noisy', version: '1.0.0'}),
+ );
+ write(
+ 'node_modules/@acme/noisy/astryx.integration.mjs',
+ "console.log('manifest log');\nexport default {components: './components'};\n",
+ );
+ write(
+ 'node_modules/@acme/noisy/components/Widget.doc.mjs',
+ "export const docs = {name: 'Widget', usage: {description: 'A widget'}};\n",
+ );
+ write(
+ 'node_modules/@acme/noisy/components/Widget.tsx',
+ 'export function Widget() { return null; }\n',
+ );
+}
+
+describe('--json stdout stays one envelope when project modules print', () => {
+ it.each([
+ [['--json', 'docs'], 'docs.list'],
+ [['--json', 'template', '--list'], 'template.list'],
+ [['--json', 'doctor'], 'doctor'],
+ ])('astryx.config.mjs: %j', (args, type) => {
+ write(
+ 'package.json',
+ JSON.stringify({name: 'consumer', private: true, type: 'module'}),
+ );
+ write(
+ 'astryx.config.mjs',
+ "console.log('config log');\nprocess.stdout.write('config write\\n');\nexport default {integrations: []};\n",
+ );
+
+ const r = runCli(args);
+
+ expect(expectOneEnvelope(r, 'config log').type).toBe(type);
+ expect(r.stderr).toContain('config write');
+ });
+
+ it('astryx.config.ts through jiti', () => {
+ write(
+ 'package.json',
+ JSON.stringify({name: 'consumer', private: true, type: 'module'}),
+ );
+ write(
+ 'astryx.config.ts',
+ "console.log('config log');\nconst config: {integrations: string[]} = {integrations: []};\nexport default config;\n",
+ );
+
+ const r = runCli(['--json', 'template', '--list']);
+
+ expect(r.status, r.stderr).toBe(0);
+ expect(expectOneEnvelope(r, 'config log').type).toBe('template.list');
+ });
+
+ it('CommonJS astryx.config.js reloaded fresh by upgrade', () => {
+ write('package.json', JSON.stringify({name: 'consumer', private: true}));
+ write(
+ 'node_modules/@astryxdesign/core/package.json',
+ JSON.stringify({name: '@astryxdesign/core', version: '0.6.3'}),
+ );
+ write(
+ 'astryx.config.js',
+ "console.log('config log');\nmodule.exports = {integrations: []};\n",
+ );
+
+ const r = runCli(['--json', 'upgrade', '--from', '0.5.0']);
+
+ expect(r.status, r.stderr).toBe(0);
+ expect(expectOneEnvelope(r, 'config log').type).toBe('upgrade.run');
+ });
+
+ it('an error envelope while sibling project loads are still in flight', () => {
+ // search rejects on a Core without sources before its parallel loads settle.
+ write(
+ 'package.json',
+ JSON.stringify({name: 'consumer', private: true, type: 'module'}),
+ );
+ write(
+ 'node_modules/@astryxdesign/core/package.json',
+ JSON.stringify({name: '@astryxdesign/core', version: '0.6.3'}),
+ );
+ write(
+ 'astryx.config.mjs',
+ "console.log('config log');\nexport default {integrations: []};\n",
+ );
+
+ const r = runCli(['--json', 'search', 'button']);
+
+ expect(r.status).toBe(1);
+ expect(typeof expectOneEnvelope(r, 'config log').code).toBe('string');
+ });
+
+ it('an autolinked integration manifest', () => {
+ installNoisyIntegration();
+
+ const r = runCli(['--json', 'docs']);
+
+ expect(r.status, r.stderr).toBe(0);
+ expect(expectOneEnvelope(r, 'manifest log').type).toBe('docs.list');
+ });
+
+ it.each([
+ [['--json', 'integration', 'add', 'doc', 'deploying'], 'integration.add'],
+ [['--json', 'doctor', 'integration', 'validate'], 'integration.validate'],
+ ])('the local package manifest: %j', (args, type) => {
+ write(
+ 'package.json',
+ JSON.stringify({name: 'acme-kit', version: '1.0.0', type: 'module'}),
+ );
+ write(
+ 'astryx.integration.mjs',
+ "console.log('manifest log');\nexport default {};\n",
+ );
+
+ const r = runCli(args);
+
+ expect(r.status, r.stderr).toBe(0);
+ expect(expectOneEnvelope(r, 'manifest log').type).toBe(type);
+ });
+});