An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): migrate xds module specifiers in upgrade (#3113)
EJ Hammondf54a06feaa4e
diff --git a/.changeset/shaggy-bears-migrate.md b/.changeset/shaggy-bears-migrate.mdnew file mode 100644index 0000000000..b54914da93--- /dev/null+++ b/.changeset/shaggy-bears-migrate.md@@ -0,0 +1,9 @@+---+'@astryxdesign/cli': patch+---++[fix] Add a v0.1.0 upgrade codemod that migrates legacy `@xds/*` module specifiers and config surfaces to the Astryx v0.1.0 names.+@ejhammond++[breaking] Remove legacy `astryx.versionFile` update-hint support from package.json.+@ejhammonddiff --git a/packages/cli/src/codemods/__tests__/registry.test.mjs b/packages/cli/src/codemods/__tests__/registry.test.mjsindex b0bfd1648f..a343efb523 100644--- a/packages/cli/src/codemods/__tests__/registry.test.mjs+++ b/packages/cli/src/codemods/__tests__/registry.test.mjs@@ -16,6 +16,7 @@ describe('registry', () => {'0.0.13','0.0.14','0.0.15',+ '0.1.0',]);});});diff --git a/packages/cli/src/codemods/registry.mjs b/packages/cli/src/codemods/registry.mjsindex a2af3a98c9..1a142dc0c0 100644--- a/packages/cli/src/codemods/registry.mjs+++ b/packages/cli/src/codemods/registry.mjs@@ -17,6 +17,7 @@ const registry = new Map([['0.0.13', () => import('./transforms/v0.0.13/index.mjs')],['0.0.14', () => import('./transforms/v0.0.14/index.mjs')],['0.0.15', () => import('./transforms/v0.0.15/index.mjs')],+ ['0.1.0', () => import('./transforms/v0.1.0/index.mjs')],]);// Re-export from the shared utility so registry callers and other consumersdiff --git a/packages/cli/src/codemods/runner.mjs b/packages/cli/src/codemods/runner.mjsindex 0454a6b365..caa6d06641 100644--- a/packages/cli/src/codemods/runner.mjs+++ b/packages/cli/src/codemods/runner.mjs@@ -11,7 +11,6 @@import * as fs from 'node:fs';import * as path from 'node:path';import * as p from '@clack/prompts';-import {getRunPrefix} from '../utils/package-manager.mjs';import {humanLog} from '../lib/json.mjs';// Known corruption patterns that indicate a broken transform.@@ -87,39 +86,6 @@ function findSourceFiles(dir) {return results.sort();}-/**- * Detect the project's formatter and run it on changed files.- * Tries prettier, then biome. Silently skips if none found.- *- * @param {string[]} files - Absolute paths to files that were modified- * @param {boolean} [silent] - Suppress human-facing output- */-async function formatChangedFiles(files, silent = false) {- if (files.length === 0) return;-- const {execSync} = await import('node:child_process');- const fileArgs = files.map(f => `"${f}"`).join(' ');- const prefix = getRunPrefix();-- const formatters = [- {name: 'prettier', cmd: `${prefix} prettier --write ${fileArgs}`},- {name: 'biome', cmd: `${prefix} biome format --write ${fileArgs}`},- ];-- for (const {name, cmd} of formatters) {- try {- execSync(cmd, {stdio: 'pipe', timeout: 30000});- if (!silent)- p.log.info(- `Formatted ${files.length} file${files.length === 1 ? '' : 's'} with ${name}`,- );- return;- } catch {- // Formatter not available or failed — try next- }- }-}-/*** Validate transform output before writing to disk.*@@ -162,6 +128,86 @@ export function validateOutput(result, source, j, {parse = true} = {}) {return {valid: true};}+function isConfigCodemod(transformEntry) {+ return transformEntry.meta?.codemodType === 'config';+}++const CONFIG_CODEMOD_PATHS = new Set([+ 'package.json',+ 'astryx.config.mjs',+ 'xds.config.mjs',+]);++function resolveConfigPath(relativePath) {+ if (!CONFIG_CODEMOD_PATHS.has(relativePath)) {+ throw new Error(`unsupported config codemod path: ${relativePath}`);+ }+ return path.resolve(process.cwd(), relativePath);+}++function readOptionalConfigFile(relativePath) {+ const fullPath = resolveConfigPath(relativePath);+ if (!fs.existsSync(fullPath)) return null;+ return {path: relativePath, source: fs.readFileSync(fullPath, 'utf-8')};+}++function getConfigCodemodContext() {+ return {+ packageJson: readOptionalConfigFile('package.json'),+ astryxConfig: readOptionalConfigFile('astryx.config.mjs'),+ xdsConfig: readOptionalConfigFile('xds.config.mjs'),+ };+}++async function runConfigCodemod(transformEntry, {apply, log}) {+ const {transform} = transformEntry;+ const api = {config: getConfigCodemodContext()};+ const result = await transform({path: process.cwd(), source: ''}, api);+ const errors = result?.errors ?? [];+ if (errors.length > 0) {+ for (const error of errors) {+ log.error(` ✗ ${error.file ?? 'config'} — ${error.error}`);+ }+ return {filesChanged: 0, errors};+ }++ const changes = result?.changes ?? [];+ if (changes.length === 0) return {filesChanged: 0, errors: []};++ for (const change of changes) {+ const fullPath = resolveConfigPath(change.path);+ if (change.delete) {+ if (apply) fs.rmSync(fullPath, {force: true});+ log[apply ? 'success' : 'warn'](+ ` ${apply ? '✓' : '~'} ${change.path} (delete${apply ? '' : ', dry run'})`,+ );+ continue;+ }++ if (apply) {+ fs.writeFileSync(fullPath, change.source, 'utf-8');+ }+ log[apply ? 'success' : 'warn'](+ ` ${apply ? '✓' : '~'} ${change.path}${apply ? '' : ' (would change)'}`,+ );+ }++ if (changes.length > 0) {+ const verb = apply ? 'Updated' : 'Would update';+ log.info(+ ` ${verb} ${changes.length} config file${changes.length === 1 ? '' : 's'}`,+ );+ }++ return {+ filesChanged: changes.length,+ writtenFiles: changes+ .filter(change => !change.delete && path.extname(change.path) !== '.json')+ .map(change => resolveConfigPath(change.path)),+ errors: [],+ };+}+/*** Run codemods against source files.*@@ -197,18 +243,12 @@ export async function runCodemods(if (files.length === 0) {log.warn('No source files found.');- return {- ok: true,- totalFilesChanged: 0,- totalTransformsApplied: 0,- errors: [],- writtenFiles: [],- skippedOptional: [],- };+ } else {+ log.info(+ `Found ${files.length} source file${files.length === 1 ? '' : 's'}`,+ );}- log.info(`Found ${files.length} source file${files.length === 1 ? '' : 's'}`);-// Dynamically import jscodeshiftconst jscodeshift = (await import('jscodeshift')).default;@@ -239,6 +279,24 @@ export async function runCodemods(log.info(` ${meta.title}`);+ if (isConfigCodemod(transformEntry)) {+ const result = await runConfigCodemod(transformEntry, {apply, log});+ if (result.errors.length > 0) {+ for (const error of result.errors) {+ errors.push({+ file: error.file ?? 'config',+ codemod: name,+ error: error.error,+ });+ }+ } else if (result.filesChanged > 0) {+ totalFilesChanged += result.filesChanged;+ totalTransformsApplied += result.filesChanged;+ writtenFiles.push(...(result.writtenFiles ?? []));+ }+ continue;+ }+let filesChanged = 0;for (const filePath of files) {@@ -323,12 +381,6 @@ export async function runCodemods(}}- // Post-codemod formatting: run the project's formatter on changed files- // so codemods don't introduce style drift (jscodeshift may change quotes, etc.)- if (apply && writtenFiles.length > 0) {- await formatChangedFiles(writtenFiles, silent);- }-if (totalValidationBlocked > 0) {log.warn(`${totalValidationBlocked} file${totalValidationBlocked === 1 ? ' was' : 's were'} blocked by validation — no changes written to ${totalValidationBlocked === 1 ? 'that file' : 'those files'}.`,@@ -366,7 +418,9 @@ export async function runCodemods(if (meta.description) {log.info(` ${meta.description}`);}- log.info(` Run: astryx upgrade --codemod ${name} --path <dir> --apply`);+ log.info(+ ` Run: astryx upgrade --codemod ${name} --path <dir> --apply`,+ );}}diff --git a/packages/cli/src/codemods/transforms/v0.1.0/__tests__/migrate-xds-config-surfaces.test.mjs b/packages/cli/src/codemods/transforms/v0.1.0/__tests__/migrate-xds-config-surfaces.test.mjsnew file mode 100644index 0000000000..3639309281--- /dev/null+++ b/packages/cli/src/codemods/transforms/v0.1.0/__tests__/migrate-xds-config-surfaces.test.mjs@@ -0,0 +1,116 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect} from 'vitest';++async function applyConfigCodemod(files) {+ const {default: transform} =+ await import('../migrate-xds-config-surfaces.mjs');+ const config = {+ packageJson: files['package.json']+ ? {path: 'package.json', source: files['package.json']}+ : null,+ astryxConfig: files['astryx.config.mjs']+ ? {path: 'astryx.config.mjs', source: files['astryx.config.mjs']}+ : null,+ xdsConfig: files['xds.config.mjs']+ ? {path: 'xds.config.mjs', source: files['xds.config.mjs']}+ : null,+ };+ return transform({path: process.cwd(), source: ''}, {config});+}++describe('migrate-xds-config-surfaces', () => {+ it('extracts package.json xds config into astryx.config.mjs and removes the package key in place', async () => {+ const input = `{+ "dependencies": {"@xds/core":"^0.0.15"},+ "xds" : {"theme":"neutral","docs":"./src"}+}+`;++ const result = await applyConfigCodemod({'package.json': input});+ expect(result.errors ?? []).toEqual([]);+ expect(result.changes).toEqual([+ {+ path: 'package.json',+ source: `{+ "dependencies": {"@xds/core":"^0.0.15"}+}+`,+ },+ {+ path: 'astryx.config.mjs',+ source: `export default {+ "theme": "neutral",+ "docs": "./src"+};+`,+ },+ ]);+ });++ it('extracts package.json astryx config into astryx.config.mjs too', async () => {+ const result = await applyConfigCodemod({+ 'package.json': `{"astryx":{"theme":"neutral"}}\n`,+ });+ expect(result.changes).toEqual([+ {path: 'package.json', source: `{}\n`},+ {+ path: 'astryx.config.mjs',+ source: `export default {+ "theme": "neutral"+};+`,+ },+ ]);+ });++ it('bails when package.json contains both xds and astryx config keys', async () => {+ const result = await applyConfigCodemod({+ 'package.json': `{"xds":{"theme":"default"},"astryx":{"theme":"neutral"}}\n`,+ });+ expect(result.errors?.[0]?.error).toMatch(/both xds and astryx/);+ });++ it('does not rewrite dependency keys in package.json', async () => {+ const input = `{"dependencies":{"@xds/core":"^0.0.15"}}\n`;+ const result = await applyConfigCodemod({'package.json': input});+ expect(result.changes).toEqual([]);+ });++ it('bails when package config and astryx.config.mjs both exist', async () => {+ const result = await applyConfigCodemod({+ 'package.json': `{"xds":{"theme":"neutral"}}\n`,+ 'astryx.config.mjs': `export default {};\n`,+ });+ expect(result.errors?.[0]?.error).toMatch(/migrate the config manually/);+ });++ it('bails when package config and xds.config.mjs both exist', async () => {+ const result = await applyConfigCodemod({+ 'package.json': `{"xds":{"theme":"neutral"}}\n`,+ 'xds.config.mjs': `export default {};\n`,+ });+ expect(result.errors?.[0]?.error).toMatch(/migrate the config manually/);+ });++ it('renames xds.config.mjs to astryx.config.mjs when no package config exists', async () => {+ const result = await applyConfigCodemod({+ 'xds.config.mjs': "export default { theme: 'neutral' };\n",+ });+ expect(result.changes).toEqual([+ {+ path: 'astryx.config.mjs',+ source: "export default { theme: 'neutral' };\n",+ },+ {path: 'xds.config.mjs', delete: true},+ ]);+ });++ it('bails when xds.config.mjs and astryx.config.mjs both exist', async () => {+ const result = await applyConfigCodemod({+ 'xds.config.mjs': `export default {};\n`,+ 'astryx.config.mjs': `export default {};\n`,+ });+ expect(result.errors?.[0]?.error).toMatch(/migrate the config manually/);+ });+});diff --git a/packages/cli/src/codemods/transforms/v0.1.0/__tests__/migrate-xds-module-specifiers.test.mjs b/packages/cli/src/codemods/transforms/v0.1.0/__tests__/migrate-xds-module-specifiers.test.mjsnew file mode 100644index 0000000000..ead095f731--- /dev/null+++ b/packages/cli/src/codemods/transforms/v0.1.0/__tests__/migrate-xds-module-specifiers.test.mjs@@ -0,0 +1,51 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect} from 'vitest';++async function applyTransform(source, filePath = 'test.tsx') {+ const {default: transform} =+ await import('../migrate-xds-module-specifiers.mjs');+ const jscodeshift = (await import('jscodeshift')).default;+ const j = jscodeshift.withParser('tsx');+ const api = {jscodeshift: j, stats: () => {}, report: () => {}};+ const file = {source, path: filePath};+ const result = transform(file, api);+ return result ?? source;+}++describe('migrate-xds-module-specifiers', () => {+ it('renames import and export source paths including subpaths', async () => {+ const input = [+ "import {Button} from '@xds/core/Button';",+ "import '@xds/theme-default/theme.css';",+ "export {LabThing} from '@xds/lab/Thing';",+ "export * from '@xds/core/theme';",+ ].join('\n');++ const output = await applyTransform(input);+ expect(output).toContain('@astryxdesign/core/Button');+ expect(output).toContain('@astryxdesign/theme-neutral/theme.css');+ expect(output).toContain('@astryxdesign/lab/Thing');+ expect(output).toContain('@astryxdesign/core/theme');+ expect(output).not.toContain('@xds/');+ });++ it('renames dynamic import and require string literals', async () => {+ const output = await applyTransform(+ [+ "const mod = await import('@xds/core/theme');",+ "const core = require('@xds/core');",+ ].join('\n'),+ 'test.ts',+ );+ expect(output).toContain('@astryxdesign/core/theme');+ expect(output).toContain('@astryxdesign/core');+ expect(output).not.toContain('@xds/');+ });++ it('does not rewrite ordinary string literals', async () => {+ const input = "const packageName = '@xds/core';";+ const output = await applyTransform(input, 'test.ts');+ expect(output).toBe(input);+ });+});diff --git a/packages/cli/src/codemods/transforms/v0.1.0/index.mjs b/packages/cli/src/codemods/transforms/v0.1.0/index.mjsnew file mode 100644index 0000000000..d944b49dc4--- /dev/null+++ b/packages/cli/src/codemods/transforms/v0.1.0/index.mjs@@ -0,0 +1,28 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file v0.1.0 transform manifest+ *+ * Lists all codemods for the v0.1.0 release in the order they should run.+ */++import migrateXdsConfigSurfaces, {+ meta as migrateXdsConfigSurfacesMeta,+} from './migrate-xds-config-surfaces.mjs';++import migrateXdsModuleSpecifiers, {+ meta as migrateXdsModuleSpecifiersMeta,+} from './migrate-xds-module-specifiers.mjs';++export default [+ {+ name: 'migrate-xds-config-surfaces',+ transform: migrateXdsConfigSurfaces,+ meta: migrateXdsConfigSurfacesMeta,+ },+ {+ name: 'migrate-xds-module-specifiers',+ transform: migrateXdsModuleSpecifiers,+ meta: migrateXdsModuleSpecifiersMeta,+ },+];diff --git a/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-config-surfaces.mjs b/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-config-surfaces.mjsnew file mode 100644index 0000000000..d83410cae7--- /dev/null+++ b/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-config-surfaces.mjs@@ -0,0 +1,230 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Codemod: migrate XDS config surfaces to Astryx v0.1.0+ *+ * The v0.1.0 CLI reads astryx.config.mjs. This config codemod migrates+ * legacy xds.config.mjs and package.json's top-level `xds` config without+ * changing dependency names or versions.+ */++export const meta = {+ title: 'Migrate xds config surfaces to astryx',+ description:+ 'Moves legacy package.json xds config into astryx.config.mjs, or renames ' ++ 'xds.config.mjs when no package.json config exists. Bails out if both exist.',+ pr: '#3092',+ codemodType: 'config',+};++function findTopLevelKey(source, targetKey) {+ let depth = 0;+ let inString = false;+ let escaped = false;+ let stringStart = -1;++ for (let i = 0; i < source.length; i++) {+ const ch = source[i];++ if (inString) {+ if (escaped) {+ escaped = false;+ continue;+ }+ if (ch === '\\') {+ escaped = true;+ continue;+ }+ if (ch !== '"') continue;++ inString = false;+ const rawKey = source.slice(stringStart + 1, i);+ if (depth !== 1 || rawKey !== targetKey) continue;++ let j = i + 1;+ while (/\s/.test(source[j] ?? '')) j++;+ if (source[j] !== ':') continue;++ const valueStart = j + 1;+ const value = readJsonValue(source, valueStart);+ if (!value) return null;+ return {keyStart: stringStart, keyEnd: i + 1, colon: j, ...value};+ }++ if (ch === '"') {+ inString = true;+ stringStart = i;+ continue;+ }+ if (ch === '{' || ch === '[') depth++;+ else if (ch === '}' || ch === ']') depth--;+ }+ return null;+}++function readJsonValue(source, start) {+ let i = start;+ while (/\s/.test(source[i] ?? '')) i++;+ const valueStart = i;+ let inString = false;+ let escaped = false;+ let depth = 0;++ for (; i < source.length; i++) {+ const ch = source[i];+ if (inString) {+ if (escaped) {+ escaped = false;+ continue;+ }+ if (ch === '\\') {+ escaped = true;+ continue;+ }+ if (ch === '"') inString = false;+ continue;+ }+ if (ch === '"') {+ inString = true;+ continue;+ }+ if (ch === '{' || ch === '[') {+ depth++;+ continue;+ }+ if (ch === '}' || ch === ']') {+ if (depth === 0) break;+ depth--;+ continue;+ }+ if (depth === 0 && ch === ',') break;+ }++ const valueEnd = i;+ const rawValue = source.slice(valueStart, valueEnd).trim();+ try {+ JSON.parse(rawValue);+ } catch {+ return null;+ }+ return {valueStart, valueEnd, rawValue, terminator: source[i]};+}++function removeTopLevelProperty(source, property) {+ let removeStart = property.keyStart;+ let removeEnd = property.valueEnd;++ if (source[removeEnd] === ',') {+ removeEnd++;+ if (source[removeEnd] === '\n') removeEnd++;+ return source.slice(0, removeStart) + source.slice(removeEnd);+ }++ let i = removeStart - 1;+ while (/\s/.test(source[i] ?? '')) i--;+ if (source[i] === ',') {+ const whitespaceBetweenCommaAndKey = source.slice(i + 1, removeStart);+ const preservedWhitespace = whitespaceBetweenCommaAndKey.includes('\n')+ ? '\n'+ : '';+ return source.slice(0, i) + preservedWhitespace + source.slice(removeEnd);+ }++ return source.slice(0, removeStart) + source.slice(removeEnd);+}++function formatConfigSource(rawConfig) {+ const parsed = JSON.parse(rawConfig);+ return `export default ${JSON.stringify(parsed, null, 2)};\n`;+}++function migratePackageJsonConfig(config) {+ if (!config.packageJson) return {changes: []};++ const packageJson = config.packageJson.source;+ const xdsConfig = findTopLevelKey(packageJson, 'xds');+ const astryxConfig = findTopLevelKey(packageJson, 'astryx');+ if (!xdsConfig && !astryxConfig) return {changes: []};++ if (config.astryxConfig) {+ return {+ errors: [+ {+ file: 'package.json',+ error:+ 'package.json contains xds/astryx config and astryx.config.mjs already exists; migrate the config manually.',+ },+ ],+ };+ }++ if (xdsConfig && astryxConfig) {+ return {+ errors: [+ {+ file: 'package.json',+ error:+ 'package.json contains both xds and astryx config keys; migrate the config manually.',+ },+ ],+ };+ }++ const configProperty = astryxConfig ?? xdsConfig;+ const packageJsonWithoutConfig = removeTopLevelProperty(+ packageJson,+ configProperty,+ );+ return {+ changes: [+ {path: 'package.json', source: packageJsonWithoutConfig},+ {+ path: 'astryx.config.mjs',+ source: formatConfigSource(configProperty.rawValue),+ },+ ],+ };+}++function migrateXdsConfigFile(config) {+ if (!config.xdsConfig) return {changes: []};+ if (config.astryxConfig) {+ return {+ errors: [+ {+ file: 'xds.config.mjs',+ error:+ 'xds.config.mjs and astryx.config.mjs both exist; migrate the config manually.',+ },+ ],+ };+ }+ return {+ changes: [+ {path: 'astryx.config.mjs', source: config.xdsConfig.source},+ {path: 'xds.config.mjs', delete: true},+ ],+ };+}++export default function transformer(_file, api) {+ const config = api.config ?? {};+ const packageResult = migratePackageJsonConfig(config);+ if (packageResult.errors?.length) return packageResult;+ if (packageResult.changes?.length) {+ if (config.xdsConfig) {+ return {+ errors: [+ {+ file: 'package.json',+ error:+ 'package.json contains xds/astryx config and xds.config.mjs exists; migrate the config manually.',+ },+ ],+ };+ }+ return packageResult;+ }++ return migrateXdsConfigFile(config);+}diff --git a/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-module-specifiers.mjs b/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-module-specifiers.mjsnew file mode 100644index 0000000000..d96c295b96--- /dev/null+++ b/packages/cli/src/codemods/transforms/v0.1.0/migrate-xds-module-specifiers.mjs@@ -0,0 +1,84 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Codemod: migrate module specifiers from @xds/* to @astryxdesign/*+ *+ * The v0.1.0 release moved the public package scope from @xds to+ * @astryxdesign. Consumers update dependencies first, install, then run+ * `astryx upgrade`; this transform only updates JS/TS module specifiers in+ * source code.+ */++export const meta = {+ title: 'Migrate module specifiers from @xds/* to @astryxdesign/*',+ description:+ 'Updates JS/TS import, export, dynamic import, and require module ' ++ 'specifiers from @xds/* to the @astryxdesign/* packages used by Astryx v0.1.0.',+ pr: '#3092',+ fileExtensions: ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs'],+};++const PACKAGE_RENAMES = new Map([+ ['@xds/build', '@astryxdesign/build'],+ ['@xds/cli', '@astryxdesign/cli'],+ ['@xds/core', '@astryxdesign/core'],+ ['@xds/lab', '@astryxdesign/lab'],+ ['@xds/theme-butter', '@astryxdesign/theme-butter'],+ ['@xds/theme-chocolate', '@astryxdesign/theme-chocolate'],+ ['@xds/theme-daily', '@astryxdesign/theme-neutral'],+ ['@xds/theme-default', '@astryxdesign/theme-neutral'],+ ['@xds/theme-gothic', '@astryxdesign/theme-gothic'],+ ['@xds/theme-matcha', '@astryxdesign/theme-matcha'],+ ['@xds/theme-neutral', '@astryxdesign/theme-neutral'],+ ['@xds/theme-stone', '@astryxdesign/theme-stone'],+ ['@xds/theme-y2k', '@astryxdesign/theme-y2k'],+]);++function renamePackageSpecifier(value) {+ if (typeof value !== 'string') return value;+ for (const [from, to] of PACKAGE_RENAMES) {+ if (value === from) return to;+ if (value.startsWith(from + '/')) return to + value.slice(from.length);+ }+ return value;+}++function rewriteLiteral(node) {+ if (!node || typeof node.value !== 'string') return false;+ const next = renamePackageSpecifier(node.value);+ if (next === node.value) return false;+ node.value = next;+ return true;+}++export default function transformer(file, api) {+ const j = api.jscodeshift;+ const root = j(file.source);+ let hasChanges = false;++ root.find(j.ImportDeclaration).forEach(path => {+ hasChanges = rewriteLiteral(path.node.source) || hasChanges;+ });++ root.find(j.ExportNamedDeclaration).forEach(path => {+ hasChanges = rewriteLiteral(path.node.source) || hasChanges;+ });++ root.find(j.ExportAllDeclaration).forEach(path => {+ hasChanges = rewriteLiteral(path.node.source) || hasChanges;+ });++ root.find(j.CallExpression).forEach(path => {+ const isDynamicImport = path.node.callee.type === 'Import';+ const isRequire =+ path.node.callee.type === 'Identifier' &&+ path.node.callee.name === 'require';+ if (!isDynamicImport && !isRequire) return;+ const [arg] = path.node.arguments;+ if (arg?.type === 'StringLiteral' || arg?.type === 'Literal') {+ hasChanges = rewriteLiteral(arg) || hasChanges;+ }+ });++ return hasChanges ? root.toSource() : undefined;+}diff --git a/packages/cli/src/commands/upgrade.mjs b/packages/cli/src/commands/upgrade.mjsindex 6faa88b920..94190fa0da 100644--- a/packages/cli/src/commands/upgrade.mjs+++ b/packages/cli/src/commands/upgrade.mjs@@ -31,15 +31,13 @@ import {execFile} from 'node:child_process';import {promisify} from 'node:util';import * as p from '@clack/prompts';import {ensureJscodeshift} from '../codemods/ensure-jscodeshift.mjs';-import {- getTransformsBetween,- latestVersion,-} from '../codemods/registry.mjs';+import {getTransformsBetween, latestVersion} from '../codemods/registry.mjs';import {runCodemods} from '../codemods/runner.mjs';import {installAgentDocs, discoverAgentDocs} from './agent-docs.mjs';import {getRunPrefix} from '../utils/package-manager.mjs';import {isValidSemver, semverGte, semverGt} from '../utils/semver.mjs';import {jsonOut, jsonError} from '../lib/json.mjs';+import {loadConfig} from '../lib/config.mjs';import {ERROR_CODES} from '../lib/error-codes.mjs';const execFileAsync = promisify(execFile);@@ -66,7 +64,6 @@ function detectInstalledTargetVersion() {return null;}-function isPathSpec(spec) {return (spec.startsWith('.') ||@@ -147,7 +144,9 @@ function normalizeIntegrationTransforms(integration, from, to) {`Integration ${integration.name ?? integration.__spec} has a codemod without a name.`,);if (!entry.transform)- throw new Error(`Integration codemod ${entry.name} is missing transform.`);+ throw new Error(+ `Integration codemod ${entry.name} is missing transform.`,+ );const directTransform =typeof entry.transform === 'function' ? entry.transform : null;if (!directTransform)@@ -157,7 +156,9 @@ function normalizeIntegrationTransforms(integration, from, to) {transforms.push({name: entry.name,meta: {- title: entry.title ?? `${integration.name ?? integration.__spec}: ${entry.name}`,+ title:+ entry.title ??+ `${integration.name ?? integration.__spec}: ${entry.name}`,description: entry.description ?? '',pr: entry.pr,fileExtensions: entry.fileExtensions,@@ -179,9 +180,7 @@ async function runPostCodemodHooks(integrations, context, silent) {);if (hooks.length === 0) return;- const log = silent- ? {info() {}, warn() {}, success() {}, error() {}}- : p.log;+ const log = silent ? {info() {}, warn() {}, success() {}, error() {}} : p.log;const run = async (command, args, options = {}) => {await execFileAsync(command, args, {@@ -209,7 +208,9 @@ async function runPostCodemodHooks(integrations, context, silent) {});}} else {- log.warn(`Integration hook ${label} has no run() or command() function; skipping.`);+ log.warn(+ `Integration hook ${label} has no run() or command() function; skipping.`,+ );continue;}log.success(`Post-codemod hook ${label} completed.`);@@ -226,9 +227,16 @@ export function registerUpgrade(program) {program.command('upgrade').description('Run codemods to migrate between versions')- .option('--from <version>', 'Previous version before the dependency upgrade')+ .option(+ '--from <version>',+ 'Previous version before the dependency upgrade',+ ).option('--apply', 'Write changes to disk (default: dry-run)', false)- .option('--force', 'Run codemods even if --from is newer than the installed version', false)+ .option(+ '--force',+ 'Run codemods even if --from is newer than the installed version',+ false,+ ).option('--codemod <name>', 'Run a specific transform only').option('--integration <package-or-file>',@@ -237,15 +245,21 @@ export function registerUpgrade(program) {[],).option('--path <dir>', 'Source directory to scan', './src')- .option('--install-deps', 'Auto-install jscodeshift without prompting', false)+ .option(+ '--install-deps',+ 'Auto-install jscodeshift without prompting',+ false,+ ).option('--list', 'List available codemods', false)- .action(async (options) => {+ .action(async options => {const json = program.opts().json || false;if (!json) p.intro('Upgrade');if (!options.list && !options.from) {- const msg = 'Missing required --from. Install the target version first, then run `astryx upgrade --from <old-version>`.';- if (json) return jsonError(msg, undefined, ERROR_CODES.ERR_INVALID_ARGUMENT);+ const msg =+ 'Missing required --from. Install the target version first, then run `astryx upgrade --from <old-version>`.';+ if (json)+ return jsonError(msg, undefined, ERROR_CODES.ERR_INVALID_ARGUMENT);p.log.error(msg);p.outro('Aborted');process.exitCode = 1;@@ -255,7 +269,8 @@ export function registerUpgrade(program) {// Validate --from upfront so callers don't silently accept typos.if (!options.list && !isValidSemver(options.from)) {const msg = `Invalid --from value: "${options.from}". Expected a semver string like 0.0.5.`;- if (json) return jsonError(msg, undefined, ERROR_CODES.ERR_INVALID_VERSION);+ if (json)+ return jsonError(msg, undefined, ERROR_CODES.ERR_INVALID_VERSION);p.log.error(msg);p.outro('Aborted');process.exitCode = 1;@@ -270,13 +285,30 @@ export function registerUpgrade(program) {const manifests = await getTransformsBetween('0.0.0', latestVersion);for (const {version, transforms} of manifests) {for (const {name, meta, optional} of transforms) {- codemods.push({name, title: meta.title, version, pr: meta.pr, optional: !!optional});+ codemods.push({+ name,+ title: meta.title,+ version,+ pr: meta.pr,+ optional: !!optional,+ });}}- if (json) return jsonOut('upgrade.list', codemods.map(({name, title, version, optional}) => ({name, title, version, optional})));+ if (json)+ return jsonOut(+ 'upgrade.list',+ codemods.map(({name, title, version, optional}) => ({+ name,+ title,+ version,+ optional,+ })),+ );p.log.step('Available codemods:');for (const {name, title, pr, optional} of codemods) {- p.log.info(` ${name} — ${title}${optional ? ' (optional)' : ''} (${pr})`);+ p.log.info(+ ` ${name} — ${title}${optional ? ' (optional)' : ''} (${pr})`,+ );}p.outro('Done');return;@@ -285,8 +317,10 @@ export function registerUpgrade(program) {const currentVersion = options.from;const installed = detectInstalledTargetVersion();if (!installed) {- const msg = 'Could not find installed @astryxdesign/core (or legacy @xds/core). Install the target version first, then rerun `astryx upgrade --from <old-version>`.';- if (json) return jsonError(msg, undefined, ERROR_CODES.ERR_VERSION_DETECT);+ const msg =+ 'Could not find installed @astryxdesign/core (or legacy @xds/core). Install the target version first, then rerun `astryx upgrade --from <old-version>`.';+ if (json)+ return jsonError(msg, undefined, ERROR_CODES.ERR_VERSION_DETECT);p.log.error(msg);p.outro('Aborted');process.exitCode = 1;@@ -296,14 +330,26 @@ export function registerUpgrade(program) {if (!json) {p.log.info(`From version: ${currentVersion}`);- p.log.info(`Installed target: ${targetVersion} (${installed.packageName})`);+ p.log.info(+ `Installed target: ${targetVersion} (${installed.packageName})`,+ );}let integrations;try {- integrations = await loadIntegrations(options.integration ?? []);+ const config = await loadConfig(process.cwd());+ const integrationSpecs = uniqueFiles([+ ...(config.integrations ?? []),+ ...(options.integration ?? []),+ ]);+ integrations = await loadIntegrations(integrationSpecs);} catch (err) {- if (json) return jsonError(err.message, undefined, ERROR_CODES.ERR_INVALID_ARGUMENT);+ if (json)+ return jsonError(+ err.message,+ undefined,+ ERROR_CODES.ERR_INVALID_ARGUMENT,+ );p.log.error(err.message);p.outro('Aborted');process.exitCode = 1;@@ -333,7 +379,11 @@ export function registerUpgrade(program) {const versionManifests = [...(await getTransformsBetween(currentVersion, targetVersion)),...integrations.flatMap(integration =>- normalizeIntegrationTransforms(integration, currentVersion, targetVersion),+ normalizeIntegrationTransforms(+ integration,+ currentVersion,+ targetVersion,+ ),),];@@ -366,7 +416,8 @@ export function registerUpgrade(program) {if (totalTransforms === 0 && totalOptional === 0) {const msg = `Codemod "${options.codemod}" not found. Use --list to see available codemods.`;- if (json) return jsonError(msg, undefined, ERROR_CODES.ERR_UNKNOWN_CODEMOD);+ if (json)+ return jsonError(msg, undefined, ERROR_CODES.ERR_UNKNOWN_CODEMOD);p.log.error(msg);p.outro('Aborted');process.exitCode = 1;@@ -383,12 +434,26 @@ export function registerUpgrade(program) {}}- const receipt = {from: currentVersion, to: targetVersion, codemods: totalTransforms, integrations: integrations.map(i => i.name ?? i.__spec), agentDocsRefreshed: false};+ const receipt = {+ from: currentVersion,+ to: targetVersion,+ codemods: totalTransforms,+ integrations: integrations.map(i => i.name ?? i.__spec),+ agentDocsRefreshed: false,+ };// Ensure jscodeshift is available- const ready = await ensureJscodeshift({installDeps: options.installDeps, silent: json});+ const ready = await ensureJscodeshift({+ installDeps: options.installDeps,+ silent: json,+ });if (!ready) {- if (json) return jsonError('jscodeshift is required but could not be installed.', undefined, ERROR_CODES.ERR_DEP_MISSING);+ if (json)+ return jsonError(+ 'jscodeshift is required but could not be installed.',+ undefined,+ ERROR_CODES.ERR_DEP_MISSING,+ );p.outro('Aborted');process.exitCode = 1;return;@@ -404,7 +469,9 @@ export function registerUpgrade(program) {if (options.apply && integrations.length > 0) {const codemodDir = path.resolve(options.path);- const absoluteChangedFiles = uniqueFiles(codemodResult?.writtenFiles ?? []);+ const absoluteChangedFiles = uniqueFiles(+ codemodResult?.writtenFiles ?? [],+ );const changedFiles = absoluteChangedFiles.map(file =>path.relative(process.cwd(), file),);@@ -435,7 +502,8 @@ export function registerUpgrade(program) {// Don't inject into files that never had Astryx content.const written = installAgentDocs(process.cwd(), {onlyReplace: true});receipt.agentDocsRefreshed = written.length > 0;- if (!json && written.length > 0) p.log.success(`Agent docs updated: ${written.join(', ')}`);+ if (!json && written.length > 0)+ p.log.success(`Agent docs updated: ${written.join(', ')}`);} catch {if (!json) {p.log.warn(@@ -445,12 +513,23 @@ export function registerUpgrade(program) {}}- if (json) {- if (codemodResult && typeof codemodResult === 'object') {- receipt.filesChanged = codemodResult.totalFilesChanged ?? 0;- receipt.transformsApplied = codemodResult.totalTransformsApplied ?? 0;- receipt.errors = codemodResult.errors ?? [];+ if (codemodResult && typeof codemodResult === 'object') {+ receipt.filesChanged = codemodResult.totalFilesChanged ?? 0;+ receipt.transformsApplied = codemodResult.totalTransformsApplied ?? 0;+ receipt.errors = codemodResult.errors ?? [];+ }++ if (receipt.errors?.length > 0) {+ const msg = `Upgrade completed with ${receipt.errors.length} codemod error${receipt.errors.length === 1 ? '' : 's'}.`;+ if (json) {+ return jsonError(msg, {receipt}, ERROR_CODES.ERR_CODEMOD_FAILED);}+ p.outro('Upgrade failed');+ process.exitCode = 1;+ return;+ }++ if (json) {return jsonOut('upgrade.run', receipt);}p.outro(options.apply ? 'Upgrade complete' : 'Dry run complete');diff --git a/packages/cli/src/lib/config.mjs b/packages/cli/src/lib/config.mjsindex aee88d5a76..51dedb8c0d 100644--- a/packages/cli/src/lib/config.mjs+++ b/packages/cli/src/lib/config.mjs@@ -13,6 +13,7 @@ import {pathToFileURL} from 'node:url';const DEFAULTS = {packages: [],+ integrations: [],};/**@@ -46,6 +47,7 @@ export async function loadConfig(startDir = process.cwd()) {...DEFAULTS,...config,packages: normalizePackages(config.packages, path.dirname(configPath)),+ integrations: normalizeIntegrations(config.integrations),};} catch {return {...DEFAULTS};@@ -72,3 +74,13 @@ function normalizePackages(packages, configDir) {}return result;}++/**+ * Normalize integration specs to a string array. Integrations are package names+ * or manifest paths consumed by `astryx upgrade --integration`.+ */+function normalizeIntegrations(integrations) {+ if (!integrations) return [];+ const arr = Array.isArray(integrations) ? integrations : [integrations];+ return arr.filter(value => typeof value === 'string' && value !== '');+}diff --git a/packages/cli/src/lib/config.test.mjs b/packages/cli/src/lib/config.test.mjsnew file mode 100644index 0000000000..93ec503c46--- /dev/null+++ b/packages/cli/src/lib/config.test.mjs@@ -0,0 +1,42 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {afterEach, beforeEach, describe, expect, it} from 'vitest';+import * as fs from 'node:fs';+import * as path from 'node:path';+import {loadConfig} from './config.mjs';++let tmpDir;++beforeEach(() => {+ tmpDir = fs.mkdtempSync(path.join(process.cwd(), '.astryx-config-test-'));+});++afterEach(() => {+ fs.rmSync(tmpDir, {recursive: true, force: true});+});++describe('loadConfig', () => {+ it('normalizes integrations from astryx.config.mjs', async () => {+ const dir = path.join(tmpDir, 'one');+ fs.mkdirSync(dir);+ fs.writeFileSync(+ path.join(dir, 'astryx.config.mjs'),+ `export default { integrations: '@nest/xds-meta' };\n`,+ );+ await expect(loadConfig(dir)).resolves.toMatchObject({+ integrations: ['@nest/xds-meta'],+ });+ });++ it('normalizes integration arrays and filters non-strings', async () => {+ const dir = path.join(tmpDir, 'two');+ fs.mkdirSync(dir);+ fs.writeFileSync(+ path.join(dir, 'astryx.config.mjs'),+ `export default { integrations: ['@nest/xds-meta', '', 42] };\n`,+ );+ await expect(loadConfig(dir)).resolves.toMatchObject({+ integrations: ['@nest/xds-meta'],+ });+ });+});diff --git a/packages/cli/src/lib/error-codes.mjs b/packages/cli/src/lib/error-codes.mjsindex 1c49498735..48404f3d5a 100644--- a/packages/cli/src/lib/error-codes.mjs+++ b/packages/cli/src/lib/error-codes.mjs@@ -56,6 +56,7 @@* | 'ERR_UNKNOWN_AGENT'* | 'ERR_UNKNOWN_FEATURE'* | 'ERR_UNKNOWN_CODEMOD'+ | 'ERR_CODEMOD_FAILED'* | 'ERR_NOT_FOUND'* | 'ERR_NO_DOC'* | 'ERR_NO_SHOWCASE'@@ -129,6 +130,8 @@ export const ERROR_CODES = Object.freeze({ERR_UNKNOWN_FEATURE: 'ERR_UNKNOWN_FEATURE',/** A `--codemod` value did not match any registered codemod (upgrade). */ERR_UNKNOWN_CODEMOD: 'ERR_UNKNOWN_CODEMOD',+ /** One or more codemods failed during an upgrade run. */+ ERR_CODEMOD_FAILED: 'ERR_CODEMOD_FAILED',/** A generic discover/lookup query matched nothing in any package. */ERR_NOT_FOUND: 'ERR_NOT_FOUND',diff --git a/packages/cli/src/types/error-codes.d.ts b/packages/cli/src/types/error-codes.d.tsindex e6b0344999..e2ea48b50b 100644--- a/packages/cli/src/types/error-codes.d.ts+++ b/packages/cli/src/types/error-codes.d.ts@@ -29,6 +29,7 @@ export type ErrorCode =| 'ERR_UNKNOWN_AGENT'| 'ERR_UNKNOWN_FEATURE'| 'ERR_UNKNOWN_CODEMOD'+ | 'ERR_CODEMOD_FAILED'| 'ERR_NOT_FOUND'| 'ERR_NO_DOC'| 'ERR_NO_SHOWCASE'diff --git a/packages/cli/src/utils/update-check.mjs b/packages/cli/src/utils/update-check.mjsindex dff0efbb63..803ed46fe3 100644--- a/packages/cli/src/utils/update-check.mjs+++ b/packages/cli/src/utils/update-check.mjs@@ -4,9 +4,8 @@* @file Check for newer @astryxdesign/core versions via local signals.** Resolution order:- * 1. $ASTRYX_LATEST_VERSION env var (set by previous CLI invocation)- * 2. xds.versionFile in consumer's package.json (e.g. ../../libs/xds-common/LATEST_VERSION)- * 3. If neither: no hint (no network calls from this module)+ * 1. $ASTRYX_LATEST_VERSION env var+ * 2. If unset: no hint (no network calls from this module)** When a newer version is detected, returns a hint string for CLI output.* Also sets $ASTRYX_LATEST_VERSION for subsequent commands in the same shell.@@ -23,34 +22,13 @@ import {semverGt} from './semver.mjs';* @param {string} [cwd] - Project directory (default: process.cwd())* @returns {string|null} Latest version string, or null if unknown*/-export function getLatestVersion(cwd = process.cwd()) {+export function getLatestVersion() {// 1. Check env var (fastest — set by previous CLI run)const envVersion = process.env.ASTRYX_LATEST_VERSION;if (envVersion && /^\d+\.\d+\.\d+/.test(envVersion)) {return envVersion;}- // 2. Check versionFile from package.json config- try {- const pkgPath = path.resolve(cwd, 'package.json');- if (fs.existsSync(pkgPath)) {- const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));- const versionFile = pkg.astryx?.versionFile;-- if (versionFile) {- const filePath = path.resolve(cwd, versionFile);- if (fs.existsSync(filePath)) {- const version = fs.readFileSync(filePath, 'utf-8').trim();- if (/^\d+\.\d+\.\d+/.test(version)) {- return version;- }- }- }- }- } catch {- // Silently fail — version check should never break the CLI- }-return null;}@@ -97,7 +75,7 @@ export function checkForUpdate(cwd = process.cwd()) {// Use semver-aware comparison so '0.0.20' is correctly treated as greater// than '0.0.5' (lexicographic compare gets that backwards).if (semverGt(latest, installed)) {- return `FYI: A newer version of @astryxdesign/core (${latest}) is available. You can upgrade with: astryx upgrade --apply --to ${latest}`;+ return `FYI: A newer version of @astryxdesign/core (${latest}) is available. Install the new package version, then run: astryx upgrade --from <old-version> --apply`;}return null;diff --git a/packages/cli/src/utils/update-check.test.mjs b/packages/cli/src/utils/update-check.test.mjsindex f177eebdf9..cd0f4f7a95 100644--- a/packages/cli/src/utils/update-check.test.mjs+++ b/packages/cli/src/utils/update-check.test.mjs@@ -41,17 +41,6 @@ describe('getLatestVersion', () => {expect(getLatestVersion(tmpDir)).toBeNull();});- it('reads from versionFile in package.json', () => {- const versionFilePath = path.join(tmpDir, 'LATEST_VERSION');- fs.writeFileSync(versionFilePath, '0.0.9\n');- fs.writeFileSync(- path.join(tmpDir, 'package.json'),- JSON.stringify({astryx: {versionFile: './LATEST_VERSION'}}),- );-- expect(getLatestVersion(tmpDir)).toBe('0.0.9');- });-it('returns null when no signals exist', () => {fs.writeFileSync(path.join(tmpDir, 'package.json'),@@ -59,26 +48,6 @@ describe('getLatestVersion', () => {);expect(getLatestVersion(tmpDir)).toBeNull();});-- it('returns null when versionFile path does not exist', () => {- fs.writeFileSync(- path.join(tmpDir, 'package.json'),- JSON.stringify({astryx: {versionFile: './missing/LATEST_VERSION'}}),- );- expect(getLatestVersion(tmpDir)).toBeNull();- });-- it('env var takes priority over versionFile', () => {- process.env.ASTRYX_LATEST_VERSION = '1.0.0';- const versionFilePath = path.join(tmpDir, 'LATEST_VERSION');- fs.writeFileSync(versionFilePath, '0.0.9\n');- fs.writeFileSync(- path.join(tmpDir, 'package.json'),- JSON.stringify({astryx: {versionFile: './LATEST_VERSION'}}),- );-- expect(getLatestVersion(tmpDir)).toBe('1.0.0');- });});describe('getInstalledVersion', () => {@@ -117,7 +86,7 @@ describe('checkForUpdate', () => {const hint = checkForUpdate(tmpDir);expect(hint).toContain('0.0.8');- expect(hint).toContain('astryx upgrade --apply --to 0.0.8');+ expect(hint).toContain('astryx upgrade --from <old-version> --apply');expect(hint).toContain('FYI');});@@ -140,37 +109,6 @@ describe('checkForUpdate', () => {expect(checkForUpdate(tmpDir)).toBeNull();});- it('sets env var for subsequent calls', () => {- const versionFilePath = path.join(tmpDir, 'LATEST_VERSION');- fs.writeFileSync(versionFilePath, '0.0.8\n');- fs.writeFileSync(- path.join(tmpDir, 'package.json'),- JSON.stringify({- dependencies: {'@astryxdesign/core': '^0.0.7'},- astryx: {versionFile: './LATEST_VERSION'},- }),- );-- checkForUpdate(tmpDir);- expect(process.env.ASTRYX_LATEST_VERSION).toBe('0.0.8');- });-- it('reads from versionFile and produces hint', () => {- const versionFilePath = path.join(tmpDir, 'LATEST_VERSION');- fs.writeFileSync(versionFilePath, '0.0.9\n');- fs.writeFileSync(- path.join(tmpDir, 'package.json'),- JSON.stringify({- dependencies: {'@astryxdesign/core': '^0.0.7'},- astryx: {versionFile: './LATEST_VERSION'},- }),- );-- const hint = checkForUpdate(tmpDir);- expect(hint).toContain('0.0.9');- expect(hint).toContain('FYI');- });-it('uses semver (not lexicographic) comparison for double-digit patches', () => {// Regression: with string compare, '0.0.20' > '0.0.5' is false because// '2' < '5' lexicographically. Users on 0.0.5 would never be told that