Registry transformers and codemod utilities
Overview
The registry transformation layer rewrites registry item source before files are compared or written into a project. Its public orchestrator is packages/…/index.ts: transform(opts, transformers) strips a leading byte-order mark, runs a sequence of text transformers over opts.raw, and then either returns getTextFromFirstToken(code) or, when opts.transformJsx is true, returns transformJsx(code, opts). The default chain in index.ts is transformImport, transformRsc, transformCssVars, transformTwPrefixes, transformRtl, transformIcons, and transformCleanup; install/update callers can pass their own chain.
The main install/update invocation is packages/…/update-files.ts. updateFiles() skips this layer for .env, registry:file, and registry:item content, but otherwise calls transform() with registry content, config, fetched base color, remote flag, JSX output flag, and supported font markers. Its install chain is deliberately broader than the default: transformImport, transformRsc, transformCssVars, transformTwPrefixes, transformIcons, transformMenu, transformAsChild, transformRtl, conditional transformNext, transformFont, then transformCleanup. After transformation, update-files.ts uses rewriteResolvedImportsInContent() and packages/…/import-declarations.ts to rewrite planned local alias imports against the target project.
Most transformers are string-in/string-out functions over original source positions. packages/…/parse.ts supplies Babel-backed parsing shaped to mimic the old ts-morph/TypeScript behavior: parseModule() uses TypeScript and JSX plugins, error recovery, skipped-comma masking, and optional JSX parsing; parseTransformInput() returns undefined for inputs Babel still cannot parse so transformers can leave files untouched; parseMaskingLines() masks non-code lines so JSX in MDX-like files can still be found. The same file provides source-order traversal (getDescendants()), text slicing (getText()), and refinding edited nodes by start position (findNodeAt()). packages/…/source-text.ts preserves the old runner boundary by removing a BOM and returning text from TypeScript's first token, which drops leading trivia, shebangs, and leading conflict-marker trivia.
Source edits are centralized in packages/…/edits.ts. applyEdits() applies non-overlapping original-position edits from the end of the file; applyManipulation() additionally rejects edits that increase syntax errors, matching ts-morph's manipulation checks except for intentionally skipped object-literal commas. Helpers such as replaceWithText() and getTextEdit() let transformers compose edits without reparsing entire files after every change. Formatting fidelity comes from packages/…/indentation.ts, which rebuilds enough of TypeScript's syntax tree from Babel nodes to reproduce ts-morph indentation for multi-line replacements, object/array insertions, JSX attributes, and list entries.
The codemod package is a compatibility layer for common ts-morph operations:
- packages/…/string-literals.ts tracks string/directive literals and no-substitution templates, reads values like TypeScript, handles JSX attribute entity behavior, and accumulates
setLiteralValue()-style edits. - packages/…/jsx-attributes.ts finds JSX attributes in source order, removes attributes with surrounding trivia, and replaces attribute initializers with indentation-aware text.
- packages/…/comma-lists.ts, array-literals.ts, and object-literals.ts implement comma-separated insertion/removal, comment-node-aware object member operations, array holes, JSDoc starts, and post-edit structural verification.
- packages/…/statements.ts models source-file statements plus standalone comment nodes, removes statements with ts-morph spacing rules, and inserts import declarations after leading block comments and existing imports.
- packages/…/named-imports.ts reads, adds, and removes named imports while preserving empty/default/side-effect import shapes.
- packages/…/rename.ts renames function and variable bindings through Babel scope analysis while disabling Babel's collision checks to tolerate TypeScript-style redeclarations.
- packages/…/trivia.ts, comment-nodes.ts, and variables.ts provide lower-level scanning for whitespace, comments, JSDoc, statement/object comment nodes, and variable initializer replacement.
Individual registry transformers are narrowly scoped:
- packages/…/transform-import.ts rewrites registry and local alias import specifiers according to
config.aliases,isRemote, and package-import forms such as#registryand#/.... It visits TypeScript's import string literal surface: top-level import/export declarations, import-equals, dynamicimport(),import type, and ambient module specifiers when TypeScript would collect them. It special-casescnfrom@/lib/utilsso utility imports land onconfig.aliases.utils. - packages/…/transform-rsc.ts removes a top-level
"use client"directive whenconfig.rscis false, using statement/comment-aware removal. It intentionally carries a module-level global regex state documented by its tests. - packages/…/transform-css-vars.ts inlines theme colors when
config.tailwind.cssVariablesis false andbaseColor.inlineColorsis present. It maps color-related Tailwind class strings across all string literals, adds dark variants, preserves alpha modifiers, and treats bareborderasborder border-border. - packages/…/transform-tw-prefix.ts applies Tailwind prefixes to strings found in
cva()variants,className,classNames, andcn()calls. It branches ongetProjectTailwindVersionFromConfig(): v3 prefixes the utility segment (hover:tw-bg...), while v4 prependsprefix:unless already present.applyPrefixesCss()performs the matching@applyrewrite for CSS text. - packages/…/transform-icons.ts replaces self-closing
<IconPlaceholder ... />elements with configured icon-library usage fromiconLibraries, removes placeholder/library-specific props, updates imports, and supports MDX-like files by masking non-code lines when placeholders are present. It preserves ts-morph edge behavior for expression-provided icon names, forgotten nodes, and semicolon style. - packages/…/transform-menu.ts resolves
cn-menu-targetandcn-menu-translucentmarkers fromconfig.menuColor, either replacing targets withdark, removing markers, or inlining a hardcoded translucent class bundle viatwMerge(). - packages/…/transform-aschild.ts runs only for
base-*styles and converts leaf<Parent asChild><Child ...>...</Child></Parent>structures into render props. It iterates from inner elements outward, removes orphanasChildattributes, and addsnativeButton={false}forButtonrender props targeting non-button elements. - packages/…/transform-rtl.ts runs when
config.rtlis true and also exposestransformDirection()for build-time RTL conversion. It rewrites physical Tailwind classes to logical classes, addsrtl:variants for translate/space/divide/cursor cases, replacescn-rtl-flip, rewrites logical side animation variants, and changes selected menuside="left/right"props and defaults toinline-start/inline-end. - packages/…/transform-next.ts performs the Next.js 16 middleware migration. It renames top-level
middlewarefunction/variable declarations toproxyand edits named export specifiers such asexport { handler as middleware }, leaving unparsable files untouched. - packages/…/transform-font.ts handles
cn-font-heading. It checks support fromconfig.resolvedPaths.tailwindCssby looking for--font-heading:and mergessupportedFontMarkers; supported markers becomefont-heading, unsupported markers are removed. It edits JSX class attributes first, removes empty attributes, then reparses and rewritescva()andmergeProps()strings. - packages/…/transform-cleanup.ts removes generic
cn-*marker classes from JSX class attributes,cva()calls, andmergeProps()calls, while preservingcn-font-headingsotransformFontcan process it later. It exposescleanupMarkers()for standalone build usage. - packages/…/transform-jsx.ts is the final JavaScript-output pass when config.tsx is false. It parses TSX with Recast and broad Babel syntax plugins, runs
@babel/plugin-transform-typescript, and prints JavaScript while preserving formatting as much as Recast allows.
Tests and snapshots are part of the behavioral contract. packages/…/index.test.ts pins the orchestrator's text-boundary behavior, default transformer list, nested filenames, non-TS inputs, MDX icon behavior, and the distinction between normal output and transformJsx output. packages/…/transform-corpus.test.ts is the broad golden corpus: fixtures from real registry payloads are run through individual transformers, install chains, default chains, and JSX output, and snapshots record line diffs from input. The per-transformer tests and packages/…/*.test.ts files document edge cases in ts-morph compatibility, formatting, parse recovery, and marker-specific behavior.
Coupling
- If the install chain in packages/…/update-files.ts changes, also update packages/…/transform-corpus.test.ts: its
installChain()duplicates the caller order so snapshots exercise exactly what install/update writes. - If packages/…/transform-cleanup.ts changes the preserved marker set, verify packages/…/transform-font.ts and the install order in packages/…/update-files.ts;
cn-font-headingmust survive cleanup untiltransformFontruns. - If class-string discovery changes in packages/…/transform-tw-prefix.ts, verify packages/…/transform-rtl.ts; RTL imports
getClassNameStrings()andgetArgumentStrings()so prefix and RTL transforms intentionally visit the samecva,className,classNames, andcn()surfaces. - If parsing behavior changes in packages/…/parse.ts, rerun the transformer and codemod suites. Transformers rely on
parseTransformInput()returningundefinedrather than throwing for unsupported source, and transform-icons.ts relies onparseMaskingLines()for MDX-style placeholder replacement. - If edit validation changes in packages/…/edits.ts, verify helpers that call
applyManipulation()(jsx-attributes.ts, named-imports.ts, statements.ts, array-literals.ts, object-literals.ts, variables.ts, and rename.ts); they depend on syntax-error comparisons to emulate ts-morph rejecting unsafe manipulations. - If alias normalization in packages/…/transform-import.ts changes, verify
rewriteResolvedImportsInContent()in packages/…/update-files.ts; install first rewrites registry aliases, then the updater may rewrite imports among planned local files.
Risks
- packages/…/transform-rsc.ts keeps
directiveRegexwith the globalgflag. The file comments and transform-rsc.test.ts/transform-corpus.test.ts document that regex state can make every other matching call miss a"use client"; if tests stop resetting that state, files can retain directives unexpectedly. - packages/…/transform-icons.ts performs JSX edits and import edits against original positions, and has explicit
SyntaxErrorInsertedError/ForgottenNodeErrorbranches for icon names from expressions and nested self-closing elements. A change that applies edits in a different order can either generate unparsable JSX or miss import cleanup. - packages/…/transform-jsx.ts parses every
transformJsxinput as TSX. packages/…/index.test.ts pins that CSS and JSON reject on the JSX path; enabling this path for non-code files in packages/…/update-files.ts would turn a transform skip into an install-time exception. - packages/…/indentation.ts is a large hand-rolled TypeScript smart-indenter shim over Babel AST nodes. Insertions in object-literals.ts, array-literals.ts, jsx-attributes.ts, and edits.ts depend on it for exact whitespace; small AST-kind mapping changes can create broad snapshot churn even when semantic edits are correct.