An open source design system that's fully customizable and agent ready
TypeScript
refactor(cli): split swizzle into api/swizzle leaf shape (#4480)
Joey468768cfcc14
diff --git a/.changeset/cli-swizzle-leaves.md b/.changeset/cli-swizzle-leaves.mdnew file mode 100644index 0000000000..35208462a6--- /dev/null+++ b/.changeset/cli-swizzle-leaves.md@@ -0,0 +1,6 @@+---+'@astryxdesign/cli': patch+---++[refactor] CLI: swizzle reorganized into api/swizzle leaf shape — the flat command splits into `api/swizzle/list` (`swizzle.list`) and `api/swizzle/copy` (`swizzle.copy` receipt, incl. `rewriteImports`), with shared @astryxdesign/core discovery + component listing deduped in `api/swizzle/_adapter.mjs`, and `swizzle.mjs` reduced to a dispatcher + barrel that keeps its existing exports (`swizzle`, `rewriteImports`). Pure reorganization with no behavior change: human output and every `--json` envelope stay byte-identical, and the CLI command, the `./api` barrel, and the central `types/swizzle` declarations are untouched.+@josephfarinadiff --git a/packages/cli/api/swizzle/_adapter.mjs b/packages/cli/api/swizzle/_adapter.mjsnew file mode 100644index 0000000000..c37ae2edda--- /dev/null+++ b/packages/cli/api/swizzle/_adapter.mjs@@ -0,0 +1,35 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file swizzle adapter — the single fs + resolution seam the swizzle leaves+ * share.+ *+ * Both leaves need the consumer's @astryxdesign/core package dir and the list+ * of swizzlable components: `list` returns the names directly, `copy` uses them+ * for its "component not found" suggestions. Resolving core + listing lives+ * here once so neither leaf re-walks the filesystem. Throws AstryxError+ * (ERR_CORE_NOT_FOUND) when core can't be located.+ */++import {findCoreDir, listComponents} from '../../utils/paths.mjs';+import {ERROR_CODES} from '../../lib/error-codes.mjs';+import {AstryxError} from '../error.mjs';++/**+ * Locate @astryxdesign/core for `cwd` and list its swizzlable components.+ * @param {string} cwd+ * @returns {{coreDir: string, components: string[]}}+ */+export function resolveCore(cwd) {+ const coreDir = findCoreDir(cwd);+ if (!coreDir) {+ throw new AstryxError(+ 'Could not find @astryxdesign/core package. Make sure you are inside the design system monorepo or have @astryxdesign/core installed.',+ [],+ ERROR_CODES.ERR_CORE_NOT_FOUND,+ );+ }++ const components = listComponents(coreDir);+ return {coreDir, components};+}diff --git a/packages/cli/api/swizzle/copy/copy.mjs b/packages/cli/api/swizzle/copy/copy.mjsnew file mode 100644index 0000000000..43ad76ee7d--- /dev/null+++ b/packages/cli/api/swizzle/copy/copy.mjs@@ -0,0 +1,272 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file swizzle.copy leaf — copy a component's source into the consumer project+ * for customization, rewriting escaping relative imports to the OWNER package's+ * subpaths.+ *+ * Side-effecting: writes files and returns a `swizzle.copy` receipt describing+ * what it did. Shared core discovery + component listing come from+ * api/swizzle/_adapter.mjs; everything here (owner resolution, the copy, import+ * rewriting, StyleX detection, maintainer feedback) is copy-specific. Errors+ * throw AstryxError (stable code + suggestions). All human prose /+ * package-manager prefixing lives in the CLI renderer.+ */++import * as fs from 'node:fs';+import * as path from 'node:path';+import {resolveCore} from '../_adapter.mjs';+import {assertWithin, PathSafetyError} from '../../../utils/path-safety.mjs';+import {checkGhCli} from '../../../utils/github.mjs';+import {Project} from '../../../lib/project.mjs';+import {+ CORE_PACKAGE,+ findIntegrationComponentDoc,+ findIntegrationComponentSource,+} from '../../../lib/component-discovery.mjs';+import {ERROR_CODES} from '../../../lib/error-codes.mjs';+import {AstryxError} from '../../error.mjs';++/** Default issue tracker for maintainer feedback after swizzling. */+const DEFAULT_ISSUES_URL = 'https://github.com/facebook/astryx/issues/new';++/**+ * Rewrite relative imports that point outside the component directory to use+ * the OWNER package's subpaths. Imports within the copied directory (./x) are+ * left untouched.+ *+ * e.g. with ownerPackage '@astryxdesign/core':+ * '../theme/tokens.stylex' -> '@astryxdesign/core/theme'+ * '../utils/mergeProps' -> '@astryxdesign/core/utils'+ *+ * @param {string} content+ * @param {string} [ownerPackage]+ */+export function rewriteImports(content, ownerPackage = CORE_PACKAGE) {+ return content.replace(+ /(from\s+['"])(\.\.\/.+?)(['"])/g,+ (match, prefix, importPath, suffix) => {+ const parts = importPath.replace(/^\.\.\//, '').split('/');+ const topDir = parts[0];+ return `${prefix}${ownerPackage}/${topDir}${suffix}`;+ },+ );+}++/**+ * Build the maintainer feedback note for a swizzled component.+ * @param {string} component+ * @param {string|undefined} issuesUrl+ * @returns {{issuesUrl: string, ghCommand?: string} | null}+ */+function buildFeedback(component, issuesUrl) {+ if (!issuesUrl) return null;+ /** @type {{issuesUrl: string, ghCommand?: string}} */+ const feedback = {issuesUrl};+ const match = issuesUrl.match(+ /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/issues(?:\/new)?\/?$/,+ );+ if (match && checkGhCli()) {+ const [, owner, repo] = match;+ feedback.ghCommand = `gh issue create --repo ${owner}/${repo} --title "[${component}] Swizzle feedback"`;+ }+ return feedback;+}++/**+ * Load the configured integrations + core issues URL for `cwd`, swallowing any+ * config errors so swizzle never hard-fails on a malformed/absent config.+ * @param {string} cwd+ * @returns {Promise<{loadedIntegrations: import('../../../lib/integrations.mjs').LoadedIntegration[], issuesUrl: string|undefined, project: Project|null}>}+ */+async function loadConfigSafely(cwd) {+ try {+ const project = await Project.load(cwd);+ return {+ loadedIntegrations: project.loadedIntegrations,+ issuesUrl: project.config.issuesUrl,+ project,+ };+ } catch {+ return {loadedIntegrations: [], issuesUrl: undefined, project: null};+ }+}++/**+ * Build the set of OWNER packages that provide a component named `name` across+ * core + every loaded integration.+ * @param {string} coreDir+ * @param {Array<{name: string, components?: string, issuesUrl?: string}>} loadedIntegrations+ * @param {string} name+ * @param {string|undefined} coreIssuesUrl+ * @returns {Array<{package: string, sourceDir: string|null, ownerPackage: string, issuesUrl: string|undefined}>}+ */+function resolveOwners(coreDir, loadedIntegrations, name, coreIssuesUrl) {+ const owners = [];+ const coreComponentDir = path.join(coreDir, 'src', name);+ if (fs.existsSync(coreComponentDir)) {+ owners.push({+ package: CORE_PACKAGE,+ sourceDir: coreComponentDir,+ ownerPackage: CORE_PACKAGE,+ issuesUrl: coreIssuesUrl || DEFAULT_ISSUES_URL,+ });+ }+ for (const integration of loadedIntegrations) {+ const docPath = findIntegrationComponentDoc(integration, name);+ if (!docPath) continue;+ const sourcePath = findIntegrationComponentSource(integration, name);+ owners.push({+ package: integration.name,+ sourceDir: sourcePath ? path.dirname(sourcePath) : null,+ ownerPackage: integration.name,+ issuesUrl: integration.issuesUrl,+ });+ }+ return owners;+}++/** @param {string} file */+function isExcludedFromCopy(file) {+ return (+ file.includes('.test.') || file.includes('.doc.') || file === 'README.md'+ );+}++/**+ * Copy one component's source into the consumer project for customization,+ * rewriting escaping relative imports to the owner package's subpaths.+ *+ * @param {string} component bare or XDS-prefixed component name+ * @param {{cwd?: string, output?: string, package?: string, overwrite?: boolean}} [options]+ * @returns {Promise<import('../../../types/swizzle').SwizzleCopyResponse>}+ */+export async function swizzleCopy(component, options = {}) {+ const {+ cwd = process.cwd(),+ output = './components/astryx',+ package: pkg,+ overwrite = false,+ } = options;++ const {coreDir, components} = resolveCore(cwd);++ const dirName = component.replace(/^XDS/, '');++ const {loadedIntegrations, project} = await loadConfigSafely(cwd);+ const coreIssuesUrl = project+ ? project.issuesUrl({package: CORE_PACKAGE})+ : undefined;+ const allOwners = resolveOwners(coreDir, loadedIntegrations, dirName, coreIssuesUrl);++ if (allOwners.length === 0) {+ throw new AstryxError(+ `Component "${component}" not found.`,+ components.slice(0, 10).map(n => ({name: n})),+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,+ );+ }++ let owner;+ if (pkg) {+ owner = allOwners.find(o => o.package === pkg);+ if (!owner) {+ throw new AstryxError(+ `Component "${dirName}" is not provided by package "${pkg}".`,+ allOwners.map(o => ({name: o.package, reason: 'provides this component'})),+ ERROR_CODES.ERR_UNKNOWN_COMPONENT,+ );+ }+ } else if (allOwners.length > 1) {+ throw new AstryxError(+ `Component "${dirName}" is provided by multiple packages. Re-run with --package <pkg> to choose one.`,+ allOwners.map(o => ({name: o.package, reason: 'provides this component'})),+ ERROR_CODES.ERR_AMBIGUOUS_COMPONENT,+ );+ } else {+ owner = allOwners[0];+ }++ if (!owner.sourceDir || !fs.existsSync(owner.sourceDir)) {+ throw new AstryxError(+ `No source found for "${dirName}" in package "${owner.package}".`,+ [],+ ERROR_CODES.ERR_NO_SOURCE,+ );+ }++ const componentDir = owner.sourceDir;++ // Path-safety: --output must resolve inside cwd.+ let outputBase;+ try {+ outputBase = assertWithin(output, cwd, {label: 'output directory'});+ } catch (err) {+ if (err instanceof PathSafetyError) {+ throw new AstryxError(err.message, [], ERROR_CODES.ERR_PATH_TRAVERSAL);+ }+ throw err;+ }+ const outputDir = path.join(outputBase, dirName);++ // Pre-flight overwrite check before any mkdir/writeFile.+ const sourceFiles = fs.readdirSync(componentDir).filter(file => {+ if (isExcludedFromCopy(file)) return false;+ return fs.statSync(path.join(componentDir, file)).isFile();+ });+ const existingFiles = sourceFiles.filter(f =>+ fs.existsSync(path.join(outputDir, f)),+ );+ if (existingFiles.length > 0 && !overwrite) {+ const relOutputForMsg = path.relative(cwd, outputDir) || '.';+ throw new AstryxError(+ `Refusing to overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/. ` ++ `Re-run with --overwrite (or -f) to replace them.`,+ [],+ ERROR_CODES.ERR_FILE_EXISTS,+ );+ }++ fs.mkdirSync(outputDir, {recursive: true});++ const files = fs.readdirSync(componentDir);+ let copied = 0;+ let usesStyleX = false;+ for (const file of files) {+ if (isExcludedFromCopy(file)) continue;+ const srcPath = path.join(componentDir, file);+ if (!fs.statSync(srcPath).isFile()) continue;+ let content = fs.readFileSync(srcPath, 'utf-8');+ if (file.endsWith('.ts') || file.endsWith('.tsx')) {+ content = rewriteImports(content, owner.ownerPackage);+ }+ if (+ (file.endsWith('.ts') || file.endsWith('.tsx')) &&+ content.includes('@stylexjs/stylex')+ ) {+ usesStyleX = true;+ }+ fs.writeFileSync(path.join(outputDir, file), content);+ copied++;+ }++ const relOutput = path.relative(cwd, outputDir);+ const copiedFiles = files.filter(+ f =>+ !isExcludedFromCopy(f) &&+ fs.statSync(path.join(componentDir, f)).isFile(),+ );+ const feedback = buildFeedback(dirName, owner.issuesUrl);++ /** @type {import('../../../types/swizzle').SwizzleCopyResponse['data']} */+ const data = {+ component: dirName,+ package: owner.package,+ outputDir: relOutput,+ filesCopied: copied,+ files: copiedFiles.map(f => f),+ usesStyleX,+ };+ if (feedback) data.feedback = feedback;+ return {type: 'swizzle.copy', data};+}diff --git a/packages/cli/api/swizzle/list/list.mjs b/packages/cli/api/swizzle/list/list.mjsnew file mode 100644index 0000000000..e3d6716f48--- /dev/null+++ b/packages/cli/api/swizzle/list/list.mjs@@ -0,0 +1,21 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file swizzle.list leaf — the swizzlable component names.+ *+ * Projects the shared core resolution (api/swizzle/_adapter.mjs) into the+ * `swizzle.list` envelope. It does no filesystem work of its own beyond that+ * shared seam. All human prose / usage hints live in the CLI renderer.+ */++import {resolveCore} from '../_adapter.mjs';++/**+ * List swizzlable components discoverable from `cwd`'s @astryxdesign/core.+ * @param {string} [cwd]+ * @returns {import('../../../types/swizzle').SwizzleListResponse}+ */+export function swizzleList(cwd = process.cwd()) {+ const {components} = resolveCore(cwd);+ return {type: 'swizzle.list', data: components};+}diff --git a/packages/cli/api/swizzle/swizzle.mjs b/packages/cli/api/swizzle/swizzle.mjsindex 6299bebce4..fa572d8cba 100644--- a/packages/cli/api/swizzle/swizzle.mjs+++ b/packages/cli/api/swizzle/swizzle.mjs@@ -1,135 +1,24 @@// Copyright (c) Meta Platforms, Inc. and affiliates./**- * @file swizzle API — copy a component's source into the consumer project for- * customization, rewriting escaping relative imports to the OWNER package's- * subpaths.+ * @file swizzle API — dispatcher + barrel.*- * Side-effecting: `swizzle(name, ...)` writes files and returns a- * `swizzle.copy` receipt describing what it did; with no name (or `list`) it- * returns `swizzle.list`. Errors throw AstryxError (stable code + suggestions).- * All human prose / package-manager prefixing lives in the CLI renderer.- */--import * as fs from 'node:fs';-import * as path from 'node:path';-import {findCoreDir, listComponents} from '../../utils/paths.mjs';-import {assertWithin, PathSafetyError} from '../../utils/path-safety.mjs';-import {checkGhCli} from '../../utils/github.mjs';-import {Project} from '../../lib/project.mjs';-import {- CORE_PACKAGE,- findIntegrationComponentDoc,- findIntegrationComponentSource,-} from '../../lib/component-discovery.mjs';-import {ERROR_CODES} from '../../lib/error-codes.mjs';-import {AstryxError} from '../error.mjs';--/** Default issue tracker for maintainer feedback after swizzling. */-const DEFAULT_ISSUES_URL = 'https://github.com/facebook/astryx/issues/new';--/**- * Rewrite relative imports that point outside the component directory to use- * the OWNER package's subpaths. Imports within the copied directory (./x) are- * left untouched.- *- * e.g. with ownerPackage '@astryxdesign/core':- * '../theme/tokens.stylex' -> '@astryxdesign/core/theme'- * '../utils/mergeProps' -> '@astryxdesign/core/utils'+ * `swizzle(name, options)` routes to one of two leaves and returns that leaf's+ * envelope:+ * - no name (or `list: true`) -> api/swizzle/list -> `swizzle.list`+ * - a component name -> api/swizzle/copy -> `swizzle.copy` receipt*- * @param {string} content- * @param {string} [ownerPackage]+ * Errors throw AstryxError (stable code + suggestions). All human prose /+ * package-manager prefixing lives in the CLI renderer. Re-exports the copy+ * leaf's `rewriteImports` so existing importers keep this module as their entry+ * point (api/index.mjs, the CLI command, and the unit tests all import from+ * here).*/-export function rewriteImports(content, ownerPackage = CORE_PACKAGE) {- return content.replace(- /(from\s+['"])(\.\.\/.+?)(['"])/g,- (match, prefix, importPath, suffix) => {- const parts = importPath.replace(/^\.\.\//, '').split('/');- const topDir = parts[0];- return `${prefix}${ownerPackage}/${topDir}${suffix}`;- },- );-}-/**- * Build the maintainer feedback note for a swizzled component.- * @param {string} component- * @param {string|undefined} issuesUrl- * @returns {{issuesUrl: string, ghCommand?: string} | null}- */-function buildFeedback(component, issuesUrl) {- if (!issuesUrl) return null;- /** @type {{issuesUrl: string, ghCommand?: string}} */- const feedback = {issuesUrl};- const match = issuesUrl.match(- /^https:\/\/github\.com\/([^/]+)\/([^/]+)\/issues(?:\/new)?\/?$/,- );- if (match && checkGhCli()) {- const [, owner, repo] = match;- feedback.ghCommand = `gh issue create --repo ${owner}/${repo} --title "[${component}] Swizzle feedback"`;- }- return feedback;-}+import {swizzleList} from './list/list.mjs';+import {swizzleCopy, rewriteImports} from './copy/copy.mjs';-/**- * Load the configured integrations + core issues URL for `cwd`, swallowing any- * config errors so swizzle never hard-fails on a malformed/absent config.- * @param {string} cwd- * @returns {Promise<{loadedIntegrations: import('../../lib/integrations.mjs').LoadedIntegration[], issuesUrl: string|undefined, project: Project|null}>}- */-async function loadConfigSafely(cwd) {- try {- const project = await Project.load(cwd);- return {- loadedIntegrations: project.loadedIntegrations,- issuesUrl: project.config.issuesUrl,- project,- };- } catch {- return {loadedIntegrations: [], issuesUrl: undefined, project: null};- }-}--/**- * Build the set of OWNER packages that provide a component named `name` across- * core + every loaded integration.- * @param {string} coreDir- * @param {Array<{name: string, components?: string, issuesUrl?: string}>} loadedIntegrations- * @param {string} name- * @param {string|undefined} coreIssuesUrl- * @returns {Array<{package: string, sourceDir: string|null, ownerPackage: string, issuesUrl: string|undefined}>}- */-function resolveOwners(coreDir, loadedIntegrations, name, coreIssuesUrl) {- const owners = [];- const coreComponentDir = path.join(coreDir, 'src', name);- if (fs.existsSync(coreComponentDir)) {- owners.push({- package: CORE_PACKAGE,- sourceDir: coreComponentDir,- ownerPackage: CORE_PACKAGE,- issuesUrl: coreIssuesUrl || DEFAULT_ISSUES_URL,- });- }- for (const integration of loadedIntegrations) {- const docPath = findIntegrationComponentDoc(integration, name);- if (!docPath) continue;- const sourcePath = findIntegrationComponentSource(integration, name);- owners.push({- package: integration.name,- sourceDir: sourcePath ? path.dirname(sourcePath) : null,- ownerPackage: integration.name,- issuesUrl: integration.issuesUrl,- });- }- return owners;-}--/** @param {string} file */-function isExcludedFromCopy(file) {- return (- file.includes('.test.') || file.includes('.doc.') || file === 'README.md'- );-}+export {rewriteImports};/*** List swizzlable components, or copy one component's source for customization.@@ -139,145 +28,11 @@ function isExcludedFromCopy(file) {* @returns {Promise<import('../../types/swizzle').SwizzleListResponse | import('../../types/swizzle').SwizzleCopyResponse>}*/export async function swizzle(component, options = {}) {- const {- cwd = process.cwd(),- output = './components/astryx',- package: pkg,- list = false,- overwrite = false,- } = options;-- const coreDir = findCoreDir(cwd);- if (!coreDir) {- throw new AstryxError(- 'Could not find @astryxdesign/core package. Make sure you are inside the design system monorepo or have @astryxdesign/core installed.',- [],- ERROR_CODES.ERR_CORE_NOT_FOUND,- );- }-- const components = listComponents(coreDir);+ const {cwd = process.cwd(), list = false} = options;if (list || !component) {- return {type: 'swizzle.list', data: components};+ return swizzleList(cwd);}- const dirName = component.replace(/^XDS/, '');-- const {loadedIntegrations, project} = await loadConfigSafely(cwd);- const coreIssuesUrl = project- ? project.issuesUrl({package: CORE_PACKAGE})- : undefined;- const allOwners = resolveOwners(coreDir, loadedIntegrations, dirName, coreIssuesUrl);-- if (allOwners.length === 0) {- throw new AstryxError(- `Component "${component}" not found.`,- components.slice(0, 10).map(n => ({name: n})),- ERROR_CODES.ERR_UNKNOWN_COMPONENT,- );- }-- let owner;- if (pkg) {- owner = allOwners.find(o => o.package === pkg);- if (!owner) {- throw new AstryxError(- `Component "${dirName}" is not provided by package "${pkg}".`,- allOwners.map(o => ({name: o.package, reason: 'provides this component'})),- ERROR_CODES.ERR_UNKNOWN_COMPONENT,- );- }- } else if (allOwners.length > 1) {- throw new AstryxError(- `Component "${dirName}" is provided by multiple packages. Re-run with --package <pkg> to choose one.`,- allOwners.map(o => ({name: o.package, reason: 'provides this component'})),- ERROR_CODES.ERR_AMBIGUOUS_COMPONENT,- );- } else {- owner = allOwners[0];- }-- if (!owner.sourceDir || !fs.existsSync(owner.sourceDir)) {- throw new AstryxError(- `No source found for "${dirName}" in package "${owner.package}".`,- [],- ERROR_CODES.ERR_NO_SOURCE,- );- }-- const componentDir = owner.sourceDir;-- // Path-safety: --output must resolve inside cwd.- let outputBase;- try {- outputBase = assertWithin(output, cwd, {label: 'output directory'});- } catch (err) {- if (err instanceof PathSafetyError) {- throw new AstryxError(err.message, [], ERROR_CODES.ERR_PATH_TRAVERSAL);- }- throw err;- }- const outputDir = path.join(outputBase, dirName);-- // Pre-flight overwrite check before any mkdir/writeFile.- const sourceFiles = fs.readdirSync(componentDir).filter(file => {- if (isExcludedFromCopy(file)) return false;- return fs.statSync(path.join(componentDir, file)).isFile();- });- const existingFiles = sourceFiles.filter(f =>- fs.existsSync(path.join(outputDir, f)),- );- if (existingFiles.length > 0 && !overwrite) {- const relOutputForMsg = path.relative(cwd, outputDir) || '.';- throw new AstryxError(- `Refusing to overwrite ${existingFiles.length} existing file(s) in ${relOutputForMsg}/. ` +- `Re-run with --overwrite (or -f) to replace them.`,- [],- ERROR_CODES.ERR_FILE_EXISTS,- );- }-- fs.mkdirSync(outputDir, {recursive: true});-- const files = fs.readdirSync(componentDir);- let copied = 0;- let usesStyleX = false;- for (const file of files) {- if (isExcludedFromCopy(file)) continue;- const srcPath = path.join(componentDir, file);- if (!fs.statSync(srcPath).isFile()) continue;- let content = fs.readFileSync(srcPath, 'utf-8');- if (file.endsWith('.ts') || file.endsWith('.tsx')) {- content = rewriteImports(content, owner.ownerPackage);- }- if (- (file.endsWith('.ts') || file.endsWith('.tsx')) &&- content.includes('@stylexjs/stylex')- ) {- usesStyleX = true;- }- fs.writeFileSync(path.join(outputDir, file), content);- copied++;- }-- const relOutput = path.relative(cwd, outputDir);- const copiedFiles = files.filter(- f =>- !isExcludedFromCopy(f) &&- fs.statSync(path.join(componentDir, f)).isFile(),- );- const feedback = buildFeedback(dirName, owner.issuesUrl);-- /** @type {import('../../types/swizzle').SwizzleCopyResponse['data']} */- const data = {- component: dirName,- package: owner.package,- outputDir: relOutput,- filesCopied: copied,- files: copiedFiles.map(f => f),- usesStyleX,- };- if (feedback) data.feedback = feedback;- return {type: 'swizzle.copy', data};+ return swizzleCopy(component, options);}