An open source design system that's fully customizable and agent ready
TypeScript
fix(cli): cover @xds/core mock calls in v0.1.0 upgrade codemods (#4069)
EJ Hammond82f90d1ddde1
diff --git a/.changeset/codemod-mock-call-specifiers.md b/.changeset/codemod-mock-call-specifiers.mdnew file mode 100644index 0000000000..12f77316fb--- /dev/null+++ b/.changeset/codemod-mock-call-specifiers.md@@ -0,0 +1,10 @@+---+'@astryxdesign/cli': patch+---++[fix] Extend the v0.1.0 upgrade codemods to cover test files that mock `@xds/core` modules, which were previously left half-migrated and broke after upgrade:++- **migrate-xds-module-specifiers**: rewrite the mocked-module path in `vi.mock`/`vi.doMock`/`jest.mock`/`jest.doMock` (and bare `mock`) calls, plus `import(...)` specifiers used in TS type positions (`typeof import('@xds/core/Text')`), so the mock still intercepts the renamed `@astryxdesign/*` import.+- **drop-xds-prefix-imports**: un-prefix partial-mock override keys inside an `@xds/core` mock factory (e.g. `useXDSTruncation` → `useTruncation`) so the override matches the renamed export instead of silently overriding nothing. Scoped to recognized `@xds/core` mock factories only; unrelated object keys are untouched.++@ejhammonddiff --git a/packages/cli/src/codemods/transforms/v0.1.0/__tests__/drop-xds-prefix-imports.test.mjs b/packages/cli/src/codemods/transforms/v0.1.0/__tests__/drop-xds-prefix-imports.test.mjsindex a0a6464680..828bef1bc6 100644--- a/packages/cli/src/codemods/transforms/v0.1.0/__tests__/drop-xds-prefix-imports.test.mjs+++ b/packages/cli/src/codemods/transforms/v0.1.0/__tests__/drop-xds-prefix-imports.test.mjs@@ -166,15 +166,50 @@ describe('drop-xds-prefix-imports', () => {expect(output).toContain('export const other = Card;');});- it('un-prefixes normally when there is NO local collision', async () => {+ it('un-prefixes override keys inside an @xds/core mock factory', async () => {const input = [- `import {XDSCodeBlock} from '@xds/core/CodeBlock';`,- `export const App = () => <XDSCodeBlock code="x" />;`,+ `vi.mock('@xds/core/Text', async orig => ({`,+ ` ...(await orig<typeof import('@xds/core/Text')>()),`,+ ` useXDSTruncation: () => ({ref: vi.fn(), isTruncated: true, fullText: ''}),`,+ `}));`,].join('\n');const output = await applyTransform(input);- expect(output).toContain('{CodeBlock}');- expect(output).toContain('@xds/core/CodeBlock');- expect(output).toContain('<CodeBlock code="x" />');- expect(output).not.toContain('AstryxCodeBlock');+ expect(output).toContain('useTruncation:');+ expect(output).not.toContain('useXDSTruncation');+ // This codemod does not touch the module-path string (that is the+ // module-specifiers codemod's job); the @xds/core/Text path stays here.+ expect(output).toContain(`vi.mock('@xds/core/Text'`);+ });++ it('un-prefixes component override keys inside a bare @xds/core jest.mock factory', async () => {+ const input = [+ `jest.mock('@xds/core', () => ({`,+ ` XDSButton: () => null,`,+ ` useXDSToast: () => ({}),`,+ `}));`,+ ].join('\n');+ const output = await applyTransform(input);+ expect(output).toContain('Button:');+ expect(output).toContain('useToast:');+ expect(output).not.toContain('XDSButton');+ expect(output).not.toContain('useXDSToast');+ });++ it('does NOT touch mock factory keys for a non-@xds package', async () => {+ const input = [+ `vi.mock('some-other-pkg', () => ({`,+ ` useXDSFoo: () => 1,`,+ `}));`,+ ].join('\n');+ const output = await applyTransform(input);+ expect(output).toBe(input);+ });++ it('does NOT touch useXDS keys in an unrelated object literal (not a mock factory)', async () => {+ const input = [`const config = {`, ` useXDSWhatever: true,`, `};`].join(+ '\n',+ );+ const output = await applyTransform(input);+ expect(output).toBe(input);});});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.mjsindex d3232bc033..93e026f446 100644--- 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.mjs@@ -89,4 +89,47 @@ describe('migrate-xds-module-specifiers', () => {expect(output).not.toContain('defaultTheme');expect(output).not.toContain('neutralTheme as');});++ it('rewrites the mocked module path in vi.mock (including the inline import() type arg)', async () => {+ const input = [+ "vi.mock('@xds/core/Text', async orig => ({",+ " ...(await orig<typeof import('@xds/core/Text')>()),",+ '}));',+ ].join('\n');+ const output = await applyTransform(input);+ expect(output).toMatch(/vi\.mock\(['"]@astryxdesign\/core\/Text['"]/);+ // The inline dynamic import() type argument is rewritten too.+ expect(output).toMatch(/import\(['"]@astryxdesign\/core\/Text['"]\)/);+ expect(output).not.toContain('@xds/');+ });++ it('rewrites the mocked module path in jest.mock (bare @xds/core)', async () => {+ const output = await applyTransform(+ "jest.mock('@xds/core', () => ({}));",+ 'test.ts',+ );+ expect(output).toMatch(/jest\.mock\(['"]@astryxdesign\/core['"]/);+ expect(output).not.toContain('@xds/');+ });++ it('rewrites vi.doMock / jest.doMock and a bare mock() call', async () => {+ const output = await applyTransform(+ [+ "vi.doMock('@xds/lab/Thing', () => ({}));",+ "jest.doMock('@xds/core/Text', () => ({}));",+ "mock('@xds/core', () => ({}));",+ ].join('\n'),+ 'test.ts',+ );+ expect(output).toMatch(/vi\.doMock\(['"]@astryxdesign\/lab\/Thing['"]/);+ expect(output).toMatch(/jest\.doMock\(['"]@astryxdesign\/core\/Text['"]/);+ expect(output).toMatch(/[^.]mock\(['"]@astryxdesign\/core['"]/);+ expect(output).not.toContain('@xds/');+ });++ it('does NOT rewrite the mock path for a non-@xds package', async () => {+ const input = "vi.mock('some-other-pkg', () => ({useXDSFoo: () => 1}));";+ const output = await applyTransform(input);+ expect(output).toBe(input);+ });});diff --git a/packages/cli/src/codemods/transforms/v0.1.0/drop-xds-prefix-imports.mjs b/packages/cli/src/codemods/transforms/v0.1.0/drop-xds-prefix-imports.mjsindex 2144374c43..d08513e9d7 100644--- a/packages/cli/src/codemods/transforms/v0.1.0/drop-xds-prefix-imports.mjs+++ b/packages/cli/src/codemods/transforms/v0.1.0/drop-xds-prefix-imports.mjs@@ -35,11 +35,19 @@* including type references in generic type-argument positions such as* `useMemo<XDSTableColumn<Issue>[]>(...)`* 3. Re-exports from @xds/core: export {XDSButton} from '@xds/core/Button'+ * 4. Object-property keys inside a test-framework mock factory for an+ * `@xds/core` module: the partial-mock override in+ * `vi.mock('@xds/core/Text', async orig => ({...await orig(),+ * useXDSTruncation: () => ...}))` must be un-prefixed to `useTruncation`,+ * otherwise the key targets a name the renamed module no longer exports and+ * the mock silently overrides nothing.** Does NOT touch:* - import source paths (`@xds/core/Button` stays -- subpath dirs are unchanged* by the prefix migration)* - identifiers not bound to an @xds/core import+ * - object-property keys outside an `@xds/core` mock factory (an unrelated+ * `{useXDSFoo: ...}` literal, or a mock of some other package, is untouched)* - the `XDSBaseProps`-style names only when they are NOT imported from core*/@@ -48,7 +56,8 @@ export const meta = {description:'Rewrites @xds/core imports and their usages from the prefixed names ' +'(XDSButton, useXDSTheme, XDSIconRegistry, XDSButtonProps) to their bare ' +- 'names (Button, useTheme, IconRegistry, ButtonProps). Only renames ' ++ 'names (Button, useTheme, IconRegistry, ButtonProps), including override ' ++ 'keys in a vi.mock/jest.mock factory for an @xds/core module. Only renames ' +'bindings imported from @xds/core, leaving unrelated identifiers untouched.',pr: '#2880',};@@ -74,6 +83,81 @@ function bareName(name) {return null;}+// A test-framework mock of an `@xds/core` module (`vi.mock('@xds/core/Text',+// factory)`). We only rewrite override keys inside such a factory, so scope the+// detection tightly: callee must be `vi.mock`/`vi.doMock`/`jest.mock`/+// `jest.doMock` (or a bare `mock`) AND the first argument must be a string+// literal that resolves to `@xds/core` (bare or subpath).+const MOCK_METHOD_NAMES = new Set(['mock', 'doMock']);+const MOCK_OBJECT_NAMES = new Set(['vi', 'jest']);++function isMockCallee(callee) {+ if (+ callee.type === 'MemberExpression' &&+ !callee.computed &&+ callee.object.type === 'Identifier' &&+ MOCK_OBJECT_NAMES.has(callee.object.name) &&+ callee.property.type === 'Identifier' &&+ MOCK_METHOD_NAMES.has(callee.property.name)+ ) {+ return true;+ }+ return callee.type === 'Identifier' && callee.name === 'mock';+}++function isXdsCoreMockCall(node) {+ if (node.type !== 'CallExpression' || !isMockCallee(node.callee))+ return false;+ const [arg] = node.arguments;+ const value =+ arg && (arg.type === 'StringLiteral' || arg.type === 'Literal')+ ? arg.value+ : null;+ return typeof value === 'string' && XDS_CORE_SOURCE.test(value);+}++// Rename XDS-prefixed object-property KEYS (not values, not nested objects)+// within the given AST subtree. Used only on a recognized @xds/core mock+// factory, so the scope guard lives at the call site.+function renameMockFactoryKeys(node, seen, onChange) {+ if (!node || typeof node !== 'object') return;+ if (Array.isArray(node)) {+ for (const child of node) renameMockFactoryKeys(child, seen, onChange);+ return;+ }+ if (seen.has(node)) return;+ seen.add(node);++ if (+ (node.type === 'ObjectProperty' || node.type === 'Property') &&+ !node.computed &&+ node.key &&+ node.key.type === 'Identifier'+ ) {+ const bare = bareName(node.key.name);+ if (bare && bare !== node.key.name) {+ node.key.name = bare;+ onChange();+ }+ }++ for (const key of Object.keys(node)) {+ if (+ key === 'loc' ||+ key === 'start' ||+ key === 'end' ||+ key === 'range' ||+ key === 'comments' ||+ key === 'leadingComments' ||+ key === 'trailingComments' ||+ key === 'tokens'+ ) {+ continue;+ }+ renameMockFactoryKeys(node[key], seen, onChange);+ }+}+export default function transformer(file, api) {const j = api.jscodeshift;const root = j(file.source);@@ -190,11 +274,26 @@ export default function transformer(file, api) {}});+ // 3. Un-prefix override keys inside @xds/core mock factories. Independent of+ // the import bindings above: the override key is a factory object property,+ // not a reference to an imported binding, so it must match the renamed export+ // name of the mocked module regardless of what the file imports.+ const seenMockNodes = new Set();+ root.find(j.CallExpression).forEach(path => {+ if (!isXdsCoreMockCall(path.node)) return;+ // Only walk the factory argument(s), never the module-path string.+ for (const arg of path.node.arguments.slice(1)) {+ renameMockFactoryKeys(arg, seenMockNodes, () => {+ hasChanges = true;+ });+ }+ });+if (localRenames.size === 0) {return hasChanges ? root.toSource() : undefined;}- // 3. Rename references to renamed local bindings+ // 4. Rename references to renamed local bindings// Identifiers (type refs, value refs, etc.)root.find(j.Identifier).forEach(path => {const newName = localRenames.get(path.node.name);@@ -231,7 +330,7 @@ export default function transformer(file, api) {}});- // 4. Rename TS type references in generic type-argument positions.+ // 5. Rename TS type references in generic type-argument positions.//// `j.find(j.Identifier)` (and `j.find(j.TSTypeReference)`) do NOT visit// identifiers nested inside generic type arguments with the tsx/babel parserdiff --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.mjsindex 2cc4ee8f0d..fe7332f02e 100644--- 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.mjs@@ -12,8 +12,9 @@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.',+ 'Updates JS/TS import, export, dynamic import, require, TS import-type, ' ++ 'and test-framework mock (vi.mock / jest.mock) module specifiers from ' ++ '@xds/* to the @astryxdesign/* packages used by Astryx v0.1.0.',pr: '#3092',fileExtensions: ['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs'],};@@ -73,6 +74,30 @@ function isCollapsedThemeSource(value) {return false;}+// Test-framework mock calls take the mocked module path as their first+// argument (`vi.mock('@xds/core/Text', factory)`). That path is a plain string+// literal -- not an ImportDeclaration source -- so it slips past the import/+// export handlers and, left unrewritten, the mock would target the stale+// `@xds/*` path and stop intercepting the renamed `@astryxdesign/*` import.+// Recognized callees: `vi.mock`, `vi.doMock`, `jest.mock`, `jest.doMock`, and+// a bare `mock(...)` (destructured from the test runner).+const MOCK_METHOD_NAMES = new Set(['mock', 'doMock']);+const MOCK_OBJECT_NAMES = new Set(['vi', 'jest']);++function isMockCall(callee) {+ if (+ callee.type === 'MemberExpression' &&+ !callee.computed &&+ callee.object.type === 'Identifier' &&+ MOCK_OBJECT_NAMES.has(callee.object.name) &&+ callee.property.type === 'Identifier' &&+ MOCK_METHOD_NAMES.has(callee.property.name)+ ) {+ return true;+ }+ return callee.type === 'Identifier' && callee.name === 'mock';+}+function remapThemeExportNames(importPath, j) {let changed = false;importPath.node.specifiers = (importPath.node.specifiers || []).map(spec => {@@ -118,12 +143,53 @@ export default function transformer(file, api) {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;+ if (isDynamicImport || isRequire || isMockCall(path.node.callee)) {+ const [arg] = path.node.arguments;+ if (arg?.type === 'StringLiteral' || arg?.type === 'Literal') {+ hasChanges = rewriteLiteral(arg) || hasChanges;+ }}});+ // TS `import(...)` TYPE specifiers -- e.g. the `import('@xds/core/Text')` in+ // `typeof import('@xds/core/Text')` -- parse to a `TSImportType` node, not a+ // dynamic-import CallExpression, so the handler above never reaches them.+ // ast-types' traversal also doesn't descend into a `TSImportType` nested in a+ // generic type-argument position (e.g. `orig<typeof import('@xds/core/Text')>()`),+ // so `j.find(j.TSImportType)` misses it. Walk the raw AST to cover every+ // position. Re-visiting a node the loop above handled is harmless: the+ // literal is already rewritten, so the second pass is a no-op.+ const seenTypeImportNodes = new Set();+ const rewriteTSImportTypes = node => {+ if (!node || typeof node !== 'object') return;+ if (Array.isArray(node)) {+ for (const child of node) rewriteTSImportTypes(child);+ return;+ }+ if (seenTypeImportNodes.has(node)) return;+ seenTypeImportNodes.add(node);++ if (node.type === 'TSImportType' && node.argument) {+ hasChanges = rewriteLiteral(node.argument) || hasChanges;+ }++ for (const key of Object.keys(node)) {+ if (+ key === 'loc' ||+ key === 'start' ||+ key === 'end' ||+ key === 'range' ||+ key === 'comments' ||+ key === 'leadingComments' ||+ key === 'trailingComments' ||+ key === 'tokens'+ ) {+ continue;+ }+ rewriteTSImportTypes(node[key]);+ }+ };+ rewriteTSImportTypes(root.get().node);+return hasChanges ? root.toSource() : undefined;}