An open source design system that's fully customizable and agent ready
TypeScript
feat(codemods): add drop-xds-meta-prefix codemod (XDSMetaAppShell → MetaAppShell) (#2957)
EJ Hammond52654d18dc99
diff --git a/packages/cli/src/codemods/transforms/v0.0.15/__tests__/drop-xds-meta-prefix.test.mjs b/packages/cli/src/codemods/transforms/v0.0.15/__tests__/drop-xds-meta-prefix.test.mjsnew file mode 100644index 0000000000..56f8e4b5ee--- /dev/null+++ b/packages/cli/src/codemods/transforms/v0.0.15/__tests__/drop-xds-meta-prefix.test.mjs@@ -0,0 +1,150 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++import {describe, it, expect} from 'vitest';++async function applyTransform(source) {+ const {default: transform} = await import('../drop-xds-meta-prefix.mjs');+ const jscodeshift = (await import('jscodeshift')).default;+ const j = jscodeshift.withParser('tsx');+ const api = {jscodeshift: j, stats: () => {}, report: () => {}};+ const file = {source, path: 'test.tsx'};+ const result = transform(file, api);+ return result ?? source;+}++describe('drop-xds-meta-prefix', () => {+ it('renames a basic named import (XDSMetaAppShell -> MetaAppShell)', async () => {+ const input = `import {XDSMetaAppShell} from '@xds/core/AppShell';`;+ const output = await applyTransform(input);+ expect(output).toContain(+ `import {MetaAppShell} from '@xds/core/AppShell';`,+ );+ expect(output).not.toContain('XDSMetaAppShell');+ });++ it('renames a hook (useXDSMetaCommandPalette -> useMetaCommandPalette)', async () => {+ const input = [+ `import {useXDSMetaCommandPalette} from '@xds/core/CommandPalette';`,+ `const cp = useXDSMetaCommandPalette();`,+ ].join('\n');+ const output = await applyTransform(input);+ expect(output).toContain(+ `import {useMetaCommandPalette} from '@xds/core/CommandPalette';`,+ );+ expect(output).toContain('const cp = useMetaCommandPalette();');+ expect(output).not.toContain('useXDSMetaCommandPalette');+ });++ it('renames a camel-case binding (xdsMetaIconRegistry -> metaIconRegistry)', async () => {+ const input = [+ `import {xdsMetaIconRegistry} from '@xds/core/Theme';`,+ `xdsMetaIconRegistry.register('foo');`,+ ].join('\n');+ const output = await applyTransform(input);+ expect(output).toContain(+ `import {metaIconRegistry} from '@xds/core/Theme';`,+ );+ expect(output).toContain(`metaIconRegistry.register('foo');`);+ expect(output).not.toContain('xdsMetaIconRegistry');+ });++ it('updates JSX usage (<XDSMetaAppShell> -> <MetaAppShell>)', async () => {+ const input = [+ `import {XDSMetaAppShell} from '@xds/core/AppShell';`,+ `export const App = () => <XDSMetaAppShell>hi</XDSMetaAppShell>;`,+ ].join('\n');+ const output = await applyTransform(input);+ expect(output).toContain('<MetaAppShell>hi</MetaAppShell>');+ expect(output).not.toContain('XDSMetaAppShell');+ });++ it('updates type usage in generic positions (ComponentProps<typeof XDSMetaAppShell>)', async () => {+ const input = [+ `import {XDSMetaAppShell} from '@xds/core/AppShell';`,+ `import type {ComponentProps} from 'react';`,+ `type Props = ComponentProps<typeof XDSMetaAppShell>;`,+ ].join('\n');+ const output = await applyTransform(input);+ expect(output).toContain('ComponentProps<typeof MetaAppShell>');+ expect(output).not.toContain('XDSMetaAppShell');+ });++ it('renames type references nested in generic type-argument positions', async () => {+ const input = [+ `import {XDSMetaTableColumn} from '@xds/core/Table';`,+ `const cols = useMemo<XDSMetaTableColumn<Issue>[]>(() => [], []);`,+ ].join('\n');+ const output = await applyTransform(input);+ expect(output).toContain(+ `import {MetaTableColumn} from '@xds/core/Table';`,+ );+ expect(output).toContain('useMemo<MetaTableColumn<Issue>[]>');+ // The unrelated generic argument `Issue` must be left alone.+ expect(output).toContain('<Issue>');+ expect(output).not.toContain('XDSMetaTableColumn');+ });++ it('renames multiple imports from the root barrel', async () => {+ const input = [+ `import {XDSMetaAppShell, XDSMetaBugNub} from '@xds/core';`,+ `export const App = () => <XDSMetaAppShell><XDSMetaBugNub /></XDSMetaAppShell>;`,+ ].join('\n');+ const output = await applyTransform(input);+ expect(output).toContain(+ `import {MetaAppShell, MetaBugNub} from '@xds/core';`,+ );+ expect(output).toContain('<MetaAppShell><MetaBugNub /></MetaAppShell>');+ expect(output).not.toContain('XDSMeta');+ });++ it('does NOT touch identifiers imported from a non-xds-meta source', async () => {+ const input = [+ `import {XDSMetaLookalike} from './local';`,+ `export const App = () => <XDSMetaLookalike />;`,+ ].join('\n');+ const output = await applyTransform(input);+ expect(output).toContain(`import {XDSMetaLookalike} from './local';`);+ expect(output).toContain('<XDSMetaLookalike />');+ });++ it('does NOT touch local symbols that are not imported from xds-meta', async () => {+ const input = [+ `import {XDSMetaAppShell} from '@xds/core/AppShell';`,+ `const XDSMetaFoo = 1;`,+ `export const App = () => <XDSMetaAppShell>{XDSMetaFoo}</XDSMetaAppShell>;`,+ ].join('\n');+ const output = await applyTransform(input);+ // Local symbol stays untouched.+ expect(output).toContain('const XDSMetaFoo = 1;');+ expect(output).toContain('{XDSMetaFoo}');+ // The imported binding is renamed.+ expect(output).toContain('<MetaAppShell>');+ expect(output).not.toContain('XDSMetaAppShell');+ });++ it('handles subpath imports and keeps the source path', async () => {+ const input = [+ `import {XDSMetaSideNav} from '@xds/core/SideNav';`,+ `export const App = () => <XDSMetaSideNav />;`,+ ].join('\n');+ const output = await applyTransform(input);+ expect(output).toContain(+ `import {MetaSideNav} from '@xds/core/SideNav';`,+ );+ expect(output).toContain('<MetaSideNav />');+ expect(output).not.toContain('XDSMetaSideNav');+ });++ it('returns undefined (no changes) when there are no @xds/core imports', async () => {+ const {default: transform} = await import('../drop-xds-meta-prefix.mjs');+ const jscodeshift = (await import('jscodeshift')).default;+ const j = jscodeshift.withParser('tsx');+ const api = {jscodeshift: j, stats: () => {}, report: () => {}};+ const file = {+ source: `import {useState} from 'react';\nconst x = 1;`,+ path: 'test.tsx',+ };+ const result = transform(file, api);+ expect(result).toBeUndefined();+ });+});diff --git a/packages/cli/src/codemods/transforms/v0.0.15/drop-xds-meta-prefix.mjs b/packages/cli/src/codemods/transforms/v0.0.15/drop-xds-meta-prefix.mjsnew file mode 100644index 0000000000..52c3c2f7b5--- /dev/null+++ b/packages/cli/src/codemods/transforms/v0.0.15/drop-xds-meta-prefix.mjs@@ -0,0 +1,270 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file Codemod: Drop the `XDSMeta` prefix from @xds/core imports+ *+ * Part of the @xds/core un-prefix migration. The package now ships+ * `Meta*` as the canonical prefix with `XDSMeta*` retained as compatibility+ * aliases; this codemod rewrites consumer code from the prefixed names to the+ * bare Meta-prefixed names:+ *+ * XDSMetaAppShell -> MetaAppShell+ * useXDSMetaCommandPalette -> useMetaCommandPalette+ * xdsMetaIconRegistry -> metaIconRegistry+ *+ * Safety: this codemod ONLY renames identifiers that are imported from+ * `@xds/core` (bare or subpath, e.g. `@xds/core/AppShell`). It tracks+ * the local binding introduced by each import and renames that binding plus its+ * references -- so a consumer's own unrelated `XDSMetaWhatever` symbol, or a+ * string that merely starts with "XDSMeta", is never touched.+ *+ * Handles:+ * 1. Named import specifiers: import {XDSMetaAppShell} from '@xds/core'+ * -> import {MetaAppShell} from '@xds/core' (and aliased imports)+ * 2. All references to the imported binding (JSX, type positions, values),+ * including type references in generic type-argument positions such as+ * `ComponentProps<typeof XDSMetaAppShell>`+ * 3. Re-exports from @xds/core:+ * export {XDSMetaAppShell} from '@xds/core/AppShell'+ *+ * Does NOT touch:+ * - import source paths (`@xds/core/AppShell` stays -- subpath dirs are+ * unchanged by the prefix migration)+ * - identifiers not bound to a @xds/core import+ */++export const meta = {+ title:+ 'Drop XDSMeta prefix from @xds/core imports (XDSMetaAppShell -> MetaAppShell)',+ description:+ 'Rewrites @xds/core imports and their usages from the prefixed names ' ++ '(XDSMetaAppShell, useXDSMetaCommandPalette) to the bare Meta-prefixed names ' ++ '(MetaAppShell, useMetaCommandPalette). Only renames bindings imported ' ++ 'from @xds/core, leaving unrelated identifiers untouched.',+};++const XDS_META_SOURCE = /^@xds\/xds-meta(\/.*)?$/;++/**+ * Compute the bare (Meta-prefixed) name for an XDSMeta-prefixed identifier.+ * Returns null if the name is not XDSMeta-prefixed in a renameable way.+ *+ * useXDSMeta<Cap> -> useMeta<Cap> (e.g. useXDSMetaCommandPalette)+ * XDSMeta<Cap> -> Meta<Cap> (e.g. XDSMetaAppShell)+ * xdsMeta<Cap> -> meta<Cap> (e.g. xdsMetaIconRegistry)+ */+function bareName(name) {+ // useXDSMeta<Cap> -> useMeta<Cap>+ if (name.startsWith('useXDSMeta') && name.length > 'useXDSMeta'.length) {+ const rest = name.slice('useXDSMeta'.length);+ if (+ rest[0] === rest[0].toUpperCase() &&+ rest[0] !== rest[0].toLowerCase()+ ) {+ return 'useMeta' + rest;+ }+ return null;+ }+ // XDSMeta<Cap> -> Meta<Cap>+ if (name.startsWith('XDSMeta') && name.length > 'XDSMeta'.length) {+ const rest = name.slice('XDSMeta'.length);+ if (+ rest[0] === rest[0].toUpperCase() &&+ rest[0] !== rest[0].toLowerCase()+ ) {+ return 'Meta' + rest;+ }+ return null;+ }+ // xdsMeta<Cap> -> meta<Cap>+ if (name.startsWith('xdsMeta') && name.length > 'xdsMeta'.length) {+ const rest = name.slice('xdsMeta'.length);+ if (+ rest[0] === rest[0].toUpperCase() &&+ rest[0] !== rest[0].toLowerCase()+ ) {+ return 'meta' + rest;+ }+ return null;+ }+ return null;+}++export default function transformer(file, api) {+ const j = api.jscodeshift;+ const root = j(file.source);+ let hasChanges = false;++ // Map of localName -> newLocalName for bindings we will rename. We only+ // rename when the LOCAL binding is the prefixed name (i.e. not aliased to+ // something custom). Aliased imports like `XDSMetaAppShell as Shell` keep+ // their local alias and only the imported name is rewritten.+ const localRenames = new Map();++ // 1. Rewrite import specifiers from @xds/core+ root.find(j.ImportDeclaration).forEach(path => {+ const source = path.node.source.value;+ if (typeof source !== 'string' || !XDS_META_SOURCE.test(source)) return;++ for (const spec of path.node.specifiers || []) {+ if (spec.type !== 'ImportSpecifier') continue; // skip default/namespace+ const importedName = spec.imported.name;+ const bare = bareName(importedName);+ if (!bare) continue;++ const localName = spec.local.name;+ const wasAliased = localName !== importedName;++ // Rewrite the imported name to the bare alias.+ spec.imported.name = bare;++ if (wasAliased) {+ // `import {XDSMetaAppShell as Shell}` -> `import {MetaAppShell as Shell}`.+ // Local binding unchanged, so no usage rewrites needed.+ hasChanges = true;+ } else {+ // `import {XDSMetaAppShell}` -> `import {MetaAppShell}`. The local+ // binding is the prefixed name; rename it and all its references.+ spec.local.name = bare;+ localRenames.set(importedName, bare);+ hasChanges = true;+ }+ }+ });++ // 2. Rewrite re-exports from @xds/core+ root.find(j.ExportNamedDeclaration).forEach(path => {+ if (!path.node.source) return;+ const source = path.node.source.value;+ if (typeof source !== 'string' || !XDS_META_SOURCE.test(source)) return;++ for (const spec of path.node.specifiers || []) {+ if (spec.type !== 'ExportSpecifier') continue;+ const localName = spec.local.name;+ const bare = bareName(localName);+ if (!bare) continue;+ spec.local.name = bare;+ // If the export was `export {XDSMetaAppShell}` (exported name == local),+ // also update the exported name; if it was+ // `export {XDSMetaAppShell as Foo}`, keep the public exported name `Foo`.+ if (spec.exported.name === localName) {+ spec.exported.name = bare;+ }+ hasChanges = true;+ }+ });++ if (localRenames.size === 0) {+ return hasChanges ? root.toSource() : undefined;+ }++ // 3. 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);+ if (!newName) return;+ // Skip object property keys like `{ XDSMetaAppShell: ... }` (not a+ // reference to the binding) and member expression properties like+ // `foo.XDSMetaAppShell`.+ const parent = path.parent.node;+ if (+ (parent.type === 'ObjectProperty' || parent.type === 'Property') &&+ parent.key === path.node &&+ !parent.computed+ ) {+ return;+ }+ if (+ parent.type === 'MemberExpression' &&+ parent.property === path.node &&+ !parent.computed+ ) {+ return;+ }+ // Don't double-rewrite the import specifier we already handled.+ if (parent.type === 'ImportSpecifier') return;+ path.node.name = newName;+ hasChanges = true;+ });++ // JSX element names: <XDSMetaAppShell> -> <MetaAppShell>+ root.find(j.JSXIdentifier).forEach(path => {+ const newName = localRenames.get(path.node.name);+ if (newName) {+ path.node.name = newName;+ hasChanges = true;+ }+ });++ // 4. 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 parser+ // -- e.g. the `XDSMetaAppShell` in `ComponentProps<typeof XDSMetaAppShell>`+ // or `XDSMetaTableColumn` in `useMemo<XDSMetaTableColumn<Issue>[]>(...)`.+ // ast-types' traversal doesn't descend through the+ // `TSTypeParameterInstantiation` / `TSArrayType` field path here, so those+ // type references slip past steps 1-3 and produce dangling prefixed names.+ //+ // To cover every type-reference position regardless of how the parser nests+ // it, walk the raw AST and rename any `TSTypeReference` whose `typeName` is a+ // renamed binding, plus any `Identifier` inside a `TSTypeQuery` (`typeof X`).+ // Renaming already-bare names is a no-op, so re-visiting a node the earlier+ // passes handled is harmless.+ const seenTypeNodes = new Set();+ const renameTypeReferences = node => {+ if (!node || typeof node !== 'object') return;+ if (Array.isArray(node)) {+ for (const child of node) renameTypeReferences(child);+ return;+ }+ if (seenTypeNodes.has(node)) return;+ seenTypeNodes.add(node);++ if (+ node.type === 'TSTypeReference' &&+ node.typeName &&+ node.typeName.type === 'Identifier'+ ) {+ const newName = localRenames.get(node.typeName.name);+ if (newName && node.typeName.name !== newName) {+ node.typeName.name = newName;+ hasChanges = true;+ }+ }++ // `typeof XDSMetaAppShell` inside a type position -> TSTypeQuery whose+ // exprName is an Identifier referencing the value binding.+ if (+ node.type === 'TSTypeQuery' &&+ node.exprName &&+ node.exprName.type === 'Identifier'+ ) {+ const newName = localRenames.get(node.exprName.name);+ if (newName && node.exprName.name !== newName) {+ node.exprName.name = newName;+ hasChanges = true;+ }+ }++ for (const key of Object.keys(node)) {+ // Skip position/metadata fields to avoid wasted traversal.+ if (+ key === 'loc' ||+ key === 'start' ||+ key === 'end' ||+ key === 'range' ||+ key === 'comments' ||+ key === 'leadingComments' ||+ key === 'trailingComments' ||+ key === 'tokens'+ ) {+ continue;+ }+ renameTypeReferences(node[key]);+ }+ };+ renameTypeReferences(root.get().node);++ return hasChanges ? root.toSource() : undefined;+}diff --git a/packages/cli/src/codemods/transforms/v0.0.15/index.mjs b/packages/cli/src/codemods/transforms/v0.0.15/index.mjsindex 96a69bfadb..b9ee1459b1 100644--- a/packages/cli/src/codemods/transforms/v0.0.15/index.mjs+++ b/packages/cli/src/codemods/transforms/v0.0.15/index.mjs@@ -38,6 +38,10 @@ import dropXdsPrefixImports, {meta as dropXdsPrefixImportsMeta,} from './drop-xds-prefix-imports.mjs';+import dropXdsMetaPrefix, {+ meta as dropXdsMetaPrefixMeta,+} from './drop-xds-meta-prefix.mjs';+export default [{name: 'rename-date-picker-to-input',@@ -84,4 +88,13 @@ export default [meta: dropXdsPrefixImportsMeta,optional: true,},+ {+ // @xds/core un-prefix migration. Optional + not tied to a version+ // bump: consumers run it explicitly during their migration, e.g.+ // xds upgrade --codemod drop-xds-meta-prefix --codemod-only --apply+ name: 'drop-xds-meta-prefix',+ transform: dropXdsMetaPrefix,+ meta: dropXdsMetaPrefixMeta,+ optional: true,+ },];