Repository navigation
fix(cli): resolve aliases through tsconfig paths and find the CSS entry #321
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change | ||||
|---|---|---|---|---|---|---|
|
|
@@ -62,6 +62,15 @@ Every write shows you what it would add and asks first. Pass `--yes` to accept e | |||||
|
|
||||||
| Change the aliases and imports are rewritten to match on the way in. | ||||||
|
|
||||||
| Aliases are import paths. The CLI writes them into the imports of every file it copies, and finds | ||||||
| the folder each one points to through `compilerOptions.paths` in your `tsconfig.json`. With | ||||||
| `"@/*": ["./src/*"]`, components go to `src/components/ui`. Without a matching entry, `@/` means the | ||||||
| project root. | ||||||
|
|
||||||
| `init` takes the CSS entry from the `cssEntryFile` your Metro config already passes to Uniwind, and | ||||||
| puts `theme.css` beside it. Without one, it looks for `global.css` in the project root, `src/` and | ||||||
| `app/`. | ||||||
|
|
||||||
| Aliases are directories inside the project: letters, numbers, dots, dashes and underscores, | ||||||
| separated by `/`, after an optional `@/`, `~/` or `./`. Anything else is refused. The alias is | ||||||
| written between the quotes of every import in every file copied in, so it has to be a path and | ||||||
|
|
@@ -178,6 +187,11 @@ import resolves, everything type-checks, and nothing is styled. | |||||
| } | ||||||
| ``` | ||||||
|
|
||||||
| **Components were written to the project root, not `src/`.** Older CLI versions read `@/` as the | ||||||
| project root whatever `tsconfig.json` said. Move `components/`, `lib/` and `hooks/` into `src/`, and | ||||||
| add `src/` to the start of each path in `panelui-lock.json` so `update` still recognises the files. | ||||||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Limit the Keys in Suggested doc fix
Committable suggestion
|
||||||
| Then run `npx panelui-cli@latest doctor` and fix any `@source` lines it reports. | ||||||
|
|
||||||
| **`Property 'className' does not exist`.** `className` is not a React Native prop — Uniwind adds | ||||||
| it. You need an ambient import somewhere in the project: | ||||||
|
|
||||||
|
|
||||||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -5,6 +5,7 @@ | |
| import fs from 'node:fs'; | ||
| import path from 'node:path'; | ||
| import { fail } from './ui.mjs'; | ||
| import { readTsconfigPaths, resolveAliasThroughPaths } from './tsconfig.mjs'; | ||
|
|
||
| export const CONFIG_FILE = 'panelui.json'; | ||
| export const DEFAULT_REGISTRY = 'https://panelui.dev/r'; | ||
|
|
@@ -95,12 +96,61 @@ export function validateAlias(alias) { | |
| } | ||
|
|
||
| /** | ||
| * Turn an alias into a real directory. `@/components/ui` → `components/ui`, | ||
| * following the `@/*` → `./*` mapping Expo's base tsconfig already sets up. | ||
| * Turn an alias into a real directory, relative to the project root. | ||
| * | ||
| * Given the project's root (`cwd`), the alias is resolved through | ||
| * `compilerOptions.paths` in its tsconfig, so `@/components/ui` is | ||
| * `src/components/ui` where `@/*` maps to `./src/*`. The copied files keep the | ||
| * alias in their imports; this is only where they are written. | ||
| * | ||
| * Without a root, or when no `paths` entry covers the alias, the prefix is read | ||
| * as the project root: `@/components/ui` → `components/ui`. | ||
| */ | ||
| export function aliasToDir(alias, cwd) { | ||
| const tidied = validateAlias(alias); | ||
| const fallback = tidied.replace(/^@\//, '').replace(/^~\//, '').replace(/^\.\//, ''); | ||
| if (cwd === undefined) return fallback; | ||
|
|
||
| const mapping = readTsconfigPaths(cwd); | ||
| const resolved = resolveAliasThroughPaths(tidied, mapping); | ||
| if (!resolved) return fallback; | ||
|
|
||
| const root = path.resolve(cwd); | ||
| const relative = path.relative(root, resolved.dir).split(path.sep).join('/'); | ||
| const where = `"${resolved.key}" in ${mapping.file}`; | ||
|
|
||
| /* | ||
| * The folder came from a project file, and it is about to be written into | ||
| * CSS (`@source '…'`) and used as a write destination, so it is held to the | ||
| * same characters an alias is. A mapping outside the app — a shared package | ||
| * in a monorepo — is refused rather than written into. | ||
| */ | ||
| if (relative === '..' || relative.startsWith('../') || path.isAbsolute(relative)) { | ||
| fail( | ||
| `Alias "${tidied}" resolves outside the project through ${where}.`, | ||
| 'Set an alias in panelui.json that resolves to a folder inside this app.' | ||
| ); | ||
| } | ||
| if (relative && !relative.split('/').every((segment) => ALIAS_SEGMENT.test(segment))) { | ||
| fail( | ||
| `Alias "${tidied}" resolves to "${relative}" through ${where}, which is not a plain directory path.`, | ||
| 'Use letters, numbers, dots, dashes and underscores, separated by /.' | ||
| ); | ||
| } | ||
|
|
||
| return validateRelativePath(relative, 'Alias path', { allowEmpty: true }); | ||
| } | ||
|
|
||
| /** | ||
| * The directory an alias's `@source` line scans: the alias's first segment, | ||
| * resolved. `@/components/ui` scans `components` (or `src/components`), so a | ||
| * later `add` that creates a sibling folder is covered without re-running init. | ||
| */ | ||
| export function aliasToDir(alias) { | ||
| export function aliasSourceRoot(alias, cwd) { | ||
| const tidied = validateAlias(alias); | ||
| return tidied.replace(/^@\//, '').replace(/^~\//, '').replace(/^\.\//, ''); | ||
| const prefix = tidied.match(/^(?:@\/|~\/|\.\/)?/)[0]; | ||
| const [first] = tidied.slice(prefix.length).split('/'); | ||
| return aliasToDir(first ? `${prefix}${first}` : tidied, cwd); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Resolve the full alias before choosing its CSS scan root. With
|
||
| } | ||
|
|
||
| /** Rejects paths that could escape a project on the current platform or Windows. */ | ||
|
|
@@ -197,11 +247,11 @@ export function validateProjectName(name) { | |
| } | ||
|
|
||
| /** Validate every configured path before it reaches a filesystem write boundary. */ | ||
| export function validateConfigPaths(config) { | ||
| export function validateConfigPaths(config, cwd) { | ||
| const aliases = { ...CANONICAL_ALIASES, ...(config.aliases ?? {}) }; | ||
| aliasToDir(aliases.components); | ||
| aliasToDir(aliases.lib); | ||
| aliasToDir(aliases.hooks); | ||
| aliasToDir(aliases.components, cwd); | ||
| aliasToDir(aliases.lib, cwd); | ||
| aliasToDir(aliases.hooks, cwd); | ||
| validateRelativePath(config.css ?? 'global.css', 'CSS path'); | ||
| validateRelativePath(config.theme ?? 'theme.css', 'Theme path'); | ||
| } | ||
|
|
@@ -227,7 +277,7 @@ export function targetPath(cwd, config, registryPath) { | |
| const alias = | ||
| group === 'ui' ? aliases.components : group === 'lib' ? aliases.lib : aliases.hooks; | ||
|
|
||
| return projectPath(cwd, path.join(aliasToDir(alias), ...rest), 'Registry file path'); | ||
| return projectPath(cwd, path.join(aliasToDir(alias, cwd), ...rest), 'Registry file path'); | ||
| } | ||
|
|
||
| /** | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -20,7 +20,13 @@ import { | |
| writeConfig, | ||
| } from './config.mjs'; | ||
| import { fetchItem } from './registry.mjs'; | ||
| import { installDependencies, patchCss, patchMetro, patchTypeScript } from './patch.mjs'; | ||
| import { | ||
| detectCssEntry, | ||
| installDependencies, | ||
| patchCss, | ||
| patchMetro, | ||
| patchTypeScript, | ||
| } from './patch.mjs'; | ||
| import { | ||
| TEMPLATES, | ||
| THEMES, | ||
|
|
@@ -89,6 +95,9 @@ export async function init(options) { | |
| } | ||
|
|
||
| const config = defaultConfig(options.registry ?? DEFAULT_REGISTRY); | ||
| // Update the CSS entry the project already has, wherever it lives, and keep | ||
| // the tokens beside it. | ||
| config.css = detectCssEntry(cwd); | ||
|
|
||
| if (!options.assumeYes && process.stdin.isTTY) { | ||
| config.aliases.components = await ask('Where should components go?', config.aliases.components); | ||
|
|
@@ -97,7 +106,8 @@ export async function init(options) { | |
| config.css = await ask('Which file is your CSS entry?', config.css); | ||
| } | ||
|
|
||
| validateConfigPaths(config); | ||
| config.theme = siblingOf(config.css, 'theme.css'); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Keep the CSS entry separate from the generated theme. If Metro uses Without If the CSS entry is already named
|
||
| validateConfigPaths(config, cwd); | ||
|
|
||
| step(`Write ${CONFIG_FILE}`); | ||
| if (!options.dryRun) { | ||
|
|
@@ -116,6 +126,7 @@ export async function init(options) { | |
| } else { | ||
| step(`Write ${config.theme} ${dim('(design tokens, all themes)')}`); | ||
| if (!options.dryRun) { | ||
| fs.mkdirSync(path.dirname(themePath), { recursive: true }); | ||
| fs.writeFileSync(themePath, theme.files[0].content); | ||
| success(`Wrote ${config.theme}`); | ||
| } | ||
|
|
@@ -128,7 +139,7 @@ export async function init(options) { | |
| const missing = BASE_DEPENDENCIES.filter((dep) => !(dep in project.deps)); | ||
| await installDependencies(cwd, missing, { ...options, isExpo: project.isExpo }); | ||
|
|
||
| printNextSteps(config); | ||
| printNextSteps(cwd, config); | ||
| } | ||
|
|
||
| /** | ||
|
|
@@ -230,8 +241,14 @@ function printCreated(projectName, template, theme, mode) { | |
| info(''); | ||
| } | ||
|
|
||
| function printNextSteps(config) { | ||
| const componentsDir = aliasToDir(config.aliases.components); | ||
| /** `theme.css` beside `src/global.css` is `src/theme.css`. */ | ||
| function siblingOf(file, name) { | ||
| const dir = path.posix.dirname(file.split(path.sep).join('/')); | ||
| return dir === '.' ? name : `${dir}/${name}`; | ||
| } | ||
|
|
||
| function printNextSteps(cwd, config) { | ||
| const componentsDir = aliasToDir(config.aliases.components, cwd); | ||
|
|
||
| info(''); | ||
| info(bold('Almost there. Two things left:')); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -7,7 +7,14 @@ | |
| import fs from 'node:fs'; | ||
| import path from 'node:path'; | ||
| import { spawnSync } from 'node:child_process'; | ||
| import { aliasToDir, projectPath, validateConfigPaths } from './config.mjs'; | ||
| import { | ||
| aliasSourceRoot, | ||
| aliasToDir, | ||
| projectPath, | ||
| validateConfigPaths, | ||
| validateRelativePath, | ||
| } from './config.mjs'; | ||
| import { readTsconfigPaths } from './tsconfig.mjs'; | ||
| import { confirm, dim, fail, printAddition, step, success, warn } from './ui.mjs'; | ||
|
|
||
| /** | ||
|
|
@@ -19,7 +26,7 @@ import { confirm, dim, fail, printAddition, step, success, warn } from './ui.mjs | |
| * miserable thing to debug. | ||
| */ | ||
| export async function patchCss(cwd, config, { assumeYes, dryRun }) { | ||
| validateConfigPaths(config); | ||
| validateConfigPaths(config, cwd); | ||
| const cssPath = projectPath(cwd, config.css ?? 'global.css', 'CSS path'); | ||
| const exists = fs.existsSync(cssPath); | ||
| const current = exists ? fs.readFileSync(cssPath, 'utf8') : ''; | ||
|
|
@@ -28,10 +35,10 @@ export async function patchCss(cwd, config, { assumeYes, dryRun }) { | |
| const sourceDirs = [ | ||
| ...new Set( | ||
| Object.values(config.aliases ?? {}) | ||
| .map(aliasToDir) | ||
| // Scan the top-level directory rather than the leaf, so a later | ||
| // `add` that creates a sibling folder is covered without re-running. | ||
| .map((dir) => dir.split(/[\\/]/)[0]) | ||
| // Scan the alias's top-level directory rather than the leaf, so a | ||
| // later `add` that creates a sibling folder is covered without | ||
| // re-running. | ||
| .map((alias) => aliasSourceRoot(alias, cwd)) | ||
| ), | ||
| ]; | ||
|
|
||
|
|
@@ -81,6 +88,60 @@ function relativeCssSpecifier(fromDir, targetPath) { | |
| return relative.startsWith('.') ? relative : `./${relative}`; | ||
| } | ||
|
|
||
| const METRO_FILES = ['metro.config.js', 'metro.config.cjs', 'metro.config.mjs', 'metro.config.ts']; | ||
| const CSS_CANDIDATES = ['global.css', 'src/global.css', 'app/global.css', 'src/app/global.css']; | ||
|
|
||
| /** A detected path, tidied, or null when it is not one this CLI may write to. */ | ||
| function safeRelative(value) { | ||
| const tidied = value.trim().replace(/^\.\//, ''); | ||
| try { | ||
| return validateRelativePath(tidied, 'CSS path'); | ||
| } catch { | ||
| return null; | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * Which file the project's CSS entry is, so `init` updates it instead of | ||
| * creating a second one beside it. | ||
| * | ||
| * In order: the `cssEntryFile` the Metro config already passes to Uniwind; an | ||
| * existing CSS file in a usual place that imports Uniwind; any existing CSS | ||
| * file in a usual place; and finally `global.css` in the folder `@/` resolves | ||
| * to, which is `src/` in an app laid out that way. | ||
| */ | ||
| export function detectCssEntry(cwd) { | ||
| for (const name of METRO_FILES) { | ||
| const file = path.join(cwd, name); | ||
| if (!fs.existsSync(file)) continue; | ||
| const match = codeOnlyKeepingStrings(fs.readFileSync(file, 'utf8')).match( | ||
| /\bcssEntryFile\s*:\s*(['"`])([^'"`\n]+)\1/ | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Reject interpolated template literals in
Skip template literals that contain interpolation and continue to the existing-file search. Do not evaluate the Metro configuration.
|
||
| ); | ||
| const found = match && safeRelative(match[2]); | ||
| if (found) return found; | ||
| } | ||
|
|
||
| const existing = CSS_CANDIDATES.filter((file) => fs.existsSync(path.join(cwd, file))); | ||
| const withUniwind = existing.find((file) => | ||
| /@import\s+['"]uniwind['"]/.test(fs.readFileSync(path.join(cwd, file), 'utf8')) | ||
| ); | ||
| if (withUniwind ?? existing[0]) return withUniwind ?? existing[0]; | ||
|
|
||
| try { | ||
| const root = aliasToDir('@/__panelui_probe__', cwd).replace(/\/?__panelui_probe__$/, ''); | ||
| return root ? `${root}/global.css` : 'global.css'; | ||
| } catch { | ||
| return 'global.css'; | ||
| } | ||
| } | ||
|
|
||
| /** Blank out comments but keep string literals, so a commented-out option is not read. */ | ||
| function codeOnlyKeepingStrings(source) { | ||
| return source.replace(/\/\*[\s\S]*?\*\/|(^|[^:'"`\\])\/\/[^\n]*/g, (match, lead) => | ||
| lead === undefined ? ' ' : `${lead} ` | ||
| ); | ||
| } | ||
|
|
||
| const METRO_TEMPLATE = `const { getDefaultConfig } = require('expo/metro-config'); | ||
| const { withUniwindConfig } = require('uniwind/metro'); | ||
|
|
||
|
|
@@ -247,20 +308,24 @@ export async function patchTypeScript(cwd, config, { assumeYes, dryRun }) { | |
| ['css.d.ts', "declare module '*.css';\n"], | ||
| ].filter(([file]) => !fs.existsSync(path.join(cwd, file))); | ||
|
|
||
| const raw = fs.readFileSync(tsconfigPath, 'utf8'); | ||
| // Deliberately not a full JSONC parser — tsconfig commonly has comments, and | ||
| // if this cannot read it cleanly it says so rather than mangling the file. | ||
| const aliasPrefix = (config.aliases?.components ?? '@/components/ui').split('/')[0]; | ||
| const wildcard = `${aliasPrefix}/*`; | ||
| // Read leniently (comments, trailing commas, `extends`) to learn whether the | ||
| // alias is already mapped — to `./src/*` as readily as to `./*`. | ||
| const mapped = Boolean(readTsconfigPaths(cwd)?.paths?.[wildcard]); | ||
|
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Check configured alias coverage before adding a root wildcard. Suppose an extended config maps This check then reports no mapping. The later assignment creates a local Check the configured child imports, not only this literal wildcard key. If an edit is necessary, preserve the effective inherited mappings and their path bases.
|
||
|
|
||
| // Writing is strict: a file with comments would lose them on the way back | ||
| // out, so one this cannot parse plainly is reported rather than mangled. | ||
| let tsconfig = null; | ||
| try { | ||
| tsconfig = JSON.parse(raw); | ||
| } catch { | ||
| warn('tsconfig.json has comments or trailing commas — not editing it.'); | ||
| if (!mapped) { | ||
| try { | ||
| tsconfig = JSON.parse(fs.readFileSync(tsconfigPath, 'utf8')); | ||
| } catch { | ||
| warn('tsconfig.json has comments or trailing commas — not editing it.'); | ||
| } | ||
| } | ||
|
|
||
| const aliasPrefix = (config.aliases?.components ?? '@/components/ui').split('/')[0]; | ||
| const wildcard = `${aliasPrefix}/*`; | ||
| const needsPaths = | ||
| tsconfig !== null && !tsconfig.compilerOptions?.paths?.[wildcard]; | ||
| const needsPaths = !mapped && tsconfig !== null; | ||
|
|
||
| if (!declarations.length && !needsPaths) { | ||
| success('TypeScript already set up'); | ||
|
|
||
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Move only CLI-generated files out of
components/,lib/andhooks/.Line 191 tells users to move the whole
components/,lib/andhooks/directories intosrc/. These directories can also contain the user's own files. An app file that imports one of those files by a relative path fails to resolve after the move. Tell users to move only the files listed inpanelui-lock.json. Tell them to update any relative import that points to a moved file.