mirror of
https://github.com/shadcn-ui/ui.git
synced 2026-06-15 11:51:34 +00:00
Compare commits
13 Commits
shadcn@2.8
...
shadcn/reg
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
319f7f9419 | ||
|
|
e6bc16461a | ||
|
|
f85ca066dc | ||
|
|
54e66d4450 | ||
|
|
6c341c16ae | ||
|
|
06d03d64f4 | ||
|
|
6407a3b330 | ||
|
|
96b15f6090 | ||
|
|
2fe9cf6d26 | ||
|
|
728cb4cfa5 | ||
|
|
db93787712 | ||
|
|
1cdd6c1645 | ||
|
|
4983c6e1f4 |
3
apps/v4/.gitignore
vendored
3
apps/v4/.gitignore
vendored
@@ -46,3 +46,6 @@ next-env.d.ts
|
||||
.contentlayer
|
||||
.content-collections
|
||||
.source
|
||||
|
||||
# Generated data
|
||||
.data/
|
||||
|
||||
150
apps/v4/app/api/search/community/route.ts
Normal file
150
apps/v4/app/api/search/community/route.ts
Normal file
@@ -0,0 +1,150 @@
|
||||
import { promises as fs } from "fs"
|
||||
import path from "path"
|
||||
import type { Orama } from "@orama/orama"
|
||||
import { create, load, search } from "@orama/orama"
|
||||
import { registryItemSchema } from "shadcn/registry"
|
||||
import { z } from "zod"
|
||||
|
||||
type RegistryItem = z.infer<typeof registryItemSchema>
|
||||
|
||||
const searchSchema = {
|
||||
name: "string",
|
||||
description: "string",
|
||||
type: "string",
|
||||
author: "string",
|
||||
url: "string",
|
||||
registryName: "string",
|
||||
} as const
|
||||
|
||||
let searchDb: Orama<typeof searchSchema> | null = null
|
||||
|
||||
async function getSearchDb() {
|
||||
if (searchDb) return searchDb
|
||||
|
||||
try {
|
||||
const indexPath = path.join(
|
||||
process.cwd(),
|
||||
".data",
|
||||
"external-registries-index.json"
|
||||
)
|
||||
const indexData = await fs.readFile(indexPath, "utf-8")
|
||||
const savedDb = JSON.parse(indexData)
|
||||
|
||||
searchDb = await create({
|
||||
schema: searchSchema,
|
||||
})
|
||||
|
||||
await load(searchDb, savedDb)
|
||||
return searchDb
|
||||
} catch (error) {
|
||||
console.error("Failed to load search index:", error)
|
||||
return null
|
||||
}
|
||||
}
|
||||
|
||||
export async function GET(request: Request) {
|
||||
try {
|
||||
const { searchParams } = new URL(request.url)
|
||||
const query = searchParams.get("q") || ""
|
||||
const limit = parseInt(searchParams.get("limit") || "20")
|
||||
const offset = parseInt(searchParams.get("offset") || "0")
|
||||
|
||||
if (!query) {
|
||||
// Return all items if no query
|
||||
const registryPath = path.join(
|
||||
process.cwd(),
|
||||
".data",
|
||||
"external-registries.json"
|
||||
)
|
||||
|
||||
try {
|
||||
const data = await fs.readFile(registryPath, "utf-8")
|
||||
const registry = JSON.parse(data)
|
||||
|
||||
const items = registry.items.slice(offset, offset + limit)
|
||||
return Response.json(
|
||||
{
|
||||
items,
|
||||
total: registry.items.length,
|
||||
hasMore: offset + limit < registry.items.length,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
"Cache-Control":
|
||||
"public, s-maxage=3600, stale-while-revalidate=86400",
|
||||
},
|
||||
}
|
||||
)
|
||||
} catch {
|
||||
return Response.json({
|
||||
items: [],
|
||||
total: 0,
|
||||
hasMore: false,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Search using Orama
|
||||
const db = await getSearchDb()
|
||||
if (!db) {
|
||||
// No search index - return empty results
|
||||
return Response.json({
|
||||
items: [],
|
||||
total: 0,
|
||||
hasMore: false,
|
||||
})
|
||||
}
|
||||
|
||||
const results = await search(db, {
|
||||
term: query,
|
||||
limit,
|
||||
offset,
|
||||
})
|
||||
|
||||
console.log(`Search query: "${query}", found ${results.count} results`)
|
||||
|
||||
// Load the full registry to get complete item data
|
||||
const registryPath = path.join(
|
||||
process.cwd(),
|
||||
".data",
|
||||
"external-registries.json"
|
||||
)
|
||||
|
||||
try {
|
||||
const data = await fs.readFile(registryPath, "utf-8")
|
||||
const registry = JSON.parse(data)
|
||||
|
||||
// Map search results to full items
|
||||
const items = results.hits
|
||||
.map((hit) => {
|
||||
return registry.items.find(
|
||||
(item: RegistryItem) => item.name === hit.document.name
|
||||
)
|
||||
})
|
||||
.filter(Boolean)
|
||||
|
||||
return Response.json(
|
||||
{
|
||||
items,
|
||||
total: results.count,
|
||||
hasMore: offset + limit < results.count,
|
||||
},
|
||||
{
|
||||
headers: {
|
||||
"Cache-Control":
|
||||
"public, s-maxage=3600, stale-while-revalidate=86400",
|
||||
},
|
||||
}
|
||||
)
|
||||
} catch {
|
||||
return Response.json({
|
||||
items: [],
|
||||
total: 0,
|
||||
hasMore: false,
|
||||
})
|
||||
}
|
||||
} catch (error) {
|
||||
console.error("Search API error:", error)
|
||||
return Response.json({ error: "Internal server error" }, { status: 500 })
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { Metadata } from "next"
|
||||
import { NuqsAdapter } from "nuqs/adapters/next/app"
|
||||
|
||||
import { META_THEME_COLORS, siteConfig } from "@/lib/config"
|
||||
import { fontVariables } from "@/lib/fonts"
|
||||
@@ -88,16 +89,18 @@ export default function RootLayout({
|
||||
fontVariables
|
||||
)}
|
||||
>
|
||||
<ThemeProvider>
|
||||
<LayoutProvider>
|
||||
<ActiveThemeProvider>
|
||||
{children}
|
||||
<TailwindIndicator />
|
||||
<Toaster position="top-center" />
|
||||
<Analytics />
|
||||
</ActiveThemeProvider>
|
||||
</LayoutProvider>
|
||||
</ThemeProvider>
|
||||
<NuqsAdapter>
|
||||
<ThemeProvider>
|
||||
<LayoutProvider>
|
||||
<ActiveThemeProvider>
|
||||
{children}
|
||||
<TailwindIndicator />
|
||||
<Toaster position="top-center" />
|
||||
<Analytics />
|
||||
</ActiveThemeProvider>
|
||||
</LayoutProvider>
|
||||
</ThemeProvider>
|
||||
</NuqsAdapter>
|
||||
</body>
|
||||
</html>
|
||||
)
|
||||
|
||||
@@ -36,11 +36,13 @@ export function CommandMenu({
|
||||
tree,
|
||||
colors,
|
||||
blocks,
|
||||
navItems,
|
||||
...props
|
||||
}: DialogProps & {
|
||||
tree: typeof source.pageTree
|
||||
colors: ColorPalette[]
|
||||
blocks?: { name: string; description: string; categories: string[] }[]
|
||||
navItems?: { href: string; label: string }[]
|
||||
}) {
|
||||
const router = useRouter()
|
||||
const isMac = useIsMac()
|
||||
@@ -162,12 +164,45 @@ export function CommandMenu({
|
||||
<DialogTitle>Search documentation...</DialogTitle>
|
||||
<DialogDescription>Search for a command to run...</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Command className="**:data-[slot=command-input-wrapper]:bg-input/50 **:data-[slot=command-input-wrapper]:border-input rounded-none bg-transparent **:data-[slot=command-input]:!h-9 **:data-[slot=command-input]:py-0 **:data-[slot=command-input-wrapper]:mb-0 **:data-[slot=command-input-wrapper]:!h-9 **:data-[slot=command-input-wrapper]:rounded-md **:data-[slot=command-input-wrapper]:border">
|
||||
<Command
|
||||
className="**:data-[slot=command-input-wrapper]:bg-input/50 **:data-[slot=command-input-wrapper]:border-input rounded-none bg-transparent **:data-[slot=command-input]:!h-9 **:data-[slot=command-input]:py-0 **:data-[slot=command-input-wrapper]:mb-0 **:data-[slot=command-input-wrapper]:!h-9 **:data-[slot=command-input-wrapper]:rounded-md **:data-[slot=command-input-wrapper]:border"
|
||||
filter={(value, search, keywords) => {
|
||||
const extendValue = value + " " + (keywords?.join(" ") || "")
|
||||
if (extendValue.toLowerCase().includes(search.toLowerCase())) {
|
||||
return 1
|
||||
}
|
||||
return 0
|
||||
}}
|
||||
>
|
||||
<CommandInput placeholder="Search documentation..." />
|
||||
<CommandList className="no-scrollbar min-h-80 scroll-pt-2 scroll-pb-1.5">
|
||||
<CommandEmpty className="text-muted-foreground py-12 text-center text-sm">
|
||||
No results found.
|
||||
</CommandEmpty>
|
||||
{navItems && navItems.length > 0 && (
|
||||
<CommandGroup
|
||||
heading="Pages"
|
||||
className="!p-0 [&_[cmdk-group-heading]]:scroll-mt-16 [&_[cmdk-group-heading]]:!p-3 [&_[cmdk-group-heading]]:!pb-1"
|
||||
>
|
||||
{navItems.map((item) => (
|
||||
<CommandMenuItem
|
||||
key={item.href}
|
||||
value={`Navigation ${item.label}`}
|
||||
keywords={["nav", "navigation", item.label.toLowerCase()]}
|
||||
onHighlight={() => {
|
||||
setSelectedType("page")
|
||||
setCopyPayload("")
|
||||
}}
|
||||
onSelect={() => {
|
||||
runCommand(() => router.push(item.href))
|
||||
}}
|
||||
>
|
||||
<IconArrowRight />
|
||||
{item.label}
|
||||
</CommandMenuItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
)}
|
||||
{tree.children.map((group) => (
|
||||
<CommandGroup
|
||||
key={group.$id}
|
||||
|
||||
236
apps/v4/components/components-community.tsx
Normal file
236
apps/v4/components/components-community.tsx
Normal file
@@ -0,0 +1,236 @@
|
||||
"use client"
|
||||
|
||||
import * as React from "react"
|
||||
import { ArrowUpRightIcon, Loader2Icon, SearchIcon } from "lucide-react"
|
||||
import { useQueryState } from "nuqs"
|
||||
import { registryItemSchema } from "shadcn/registry"
|
||||
import { z } from "zod"
|
||||
|
||||
import { cn } from "@/lib/utils"
|
||||
import { Button } from "@/registry/new-york-v4/ui/button"
|
||||
import { Input } from "@/registry/new-york-v4/ui/input"
|
||||
import { Skeleton } from "@/registry/new-york-v4/ui/skeleton"
|
||||
|
||||
export function ComponentsCommunitySearch({
|
||||
className,
|
||||
}: React.ComponentProps<"div">) {
|
||||
return (
|
||||
<div className={cn("grid gap-4", className)}>
|
||||
<ComponentsCommunitySearchForm />
|
||||
<ComponentsCommunitySearchResults />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
interface SearchResponse {
|
||||
items: z.infer<typeof registryItemSchema>[]
|
||||
total: number
|
||||
hasMore: boolean
|
||||
}
|
||||
|
||||
function ComponentsCommunitySearchForm() {
|
||||
const [search, setSearch] = useQueryState("q", {
|
||||
defaultValue: "",
|
||||
throttleMs: 150,
|
||||
})
|
||||
const [isSearching, setIsSearching] = React.useState(false)
|
||||
const inputRef = React.useRef<HTMLInputElement>(null)
|
||||
|
||||
React.useEffect(() => {
|
||||
const handleKeyDown = (e: KeyboardEvent) => {
|
||||
if (e.key === "/" && !e.ctrlKey && !e.metaKey) {
|
||||
const activeElement = document.activeElement
|
||||
const isInputFocused =
|
||||
activeElement instanceof HTMLInputElement ||
|
||||
activeElement instanceof HTMLTextAreaElement
|
||||
if (!isInputFocused) {
|
||||
e.preventDefault()
|
||||
inputRef.current?.focus()
|
||||
}
|
||||
}
|
||||
}
|
||||
document.addEventListener("keydown", handleKeyDown)
|
||||
return () => document.removeEventListener("keydown", handleKeyDown)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div className="relative">
|
||||
<SearchIcon className="text-muted-foreground absolute top-1/2 left-3 size-4 -translate-y-1/2" />
|
||||
<Input
|
||||
ref={inputRef}
|
||||
placeholder="Search components..."
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value)
|
||||
setIsSearching(true)
|
||||
setTimeout(() => setIsSearching(false), 300)
|
||||
}}
|
||||
className="pr-9 pl-9 shadow-none"
|
||||
/>
|
||||
{isSearching && (
|
||||
<Loader2Icon className="text-muted-foreground absolute top-1/2 right-3 size-4 -translate-y-1/2 animate-spin" />
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ComponentsCommunityResults({
|
||||
items,
|
||||
}: {
|
||||
items: z.infer<typeof registryItemSchema>[]
|
||||
}) {
|
||||
if (items.length === 0) {
|
||||
return (
|
||||
<div className="p-6 text-center text-sm">
|
||||
<p className="text-muted-foreground text-balance">
|
||||
No components found for this search. Try a different search term.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="grid gap-1">
|
||||
{items.map((item, index) => (
|
||||
<a
|
||||
key={`${item.type}-${item.name}-${index}`}
|
||||
href={`${item.meta?.url ?? ""}?utm_source=shadcn-ui&utm_medium=referral&utm_campaign=components-community`}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="group hover:bg-muted focus-visible:border-ring focus-visible:ring-ring/50 flex h-16 flex-col gap-1 rounded-md p-3 transition-colors outline-none focus-visible:ring-[3px]"
|
||||
title={`${item.name} - ${item.description}`}
|
||||
>
|
||||
<div className="flex items-center gap-1 leading-none font-medium underline-offset-4">
|
||||
{item.name}{" "}
|
||||
{item.meta?.registryName && (
|
||||
<div className="text-muted-foreground ml-auto flex items-center gap-1 text-xs opacity-0 transition-opacity group-hover:opacity-100 group-focus-visible:opacity-100">
|
||||
{item.meta.registryName}
|
||||
<ArrowUpRightIcon className="size-3" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{item.description && (
|
||||
<div className="text-muted-foreground line-clamp-1 max-w-[80%] text-sm">
|
||||
{item.description}
|
||||
</div>
|
||||
)}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ComponentsCommunitySkeleton() {
|
||||
return (
|
||||
<div className="grid gap-1">
|
||||
{Array.from({ length: 20 }).map((_, i) => (
|
||||
<div key={i} className="flex h-16 flex-col gap-1 rounded-md p-3">
|
||||
<Skeleton className="h-4 w-32 rounded-md" />
|
||||
<Skeleton className="h-4 w-full max-w-[90%] rounded-md" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function ComponentsCommunitySearchResults() {
|
||||
const [search] = useQueryState("q", { defaultValue: "" })
|
||||
const [items, setItems] = React.useState<
|
||||
z.infer<typeof registryItemSchema>[]
|
||||
>([])
|
||||
const [loading, setLoading] = React.useState(true)
|
||||
const [hasMore, setHasMore] = React.useState(false)
|
||||
const [offset, setOffset] = React.useState(0)
|
||||
const abortControllerRef = React.useRef<AbortController | null>(null)
|
||||
const searchCacheRef = React.useRef<Map<string, SearchResponse>>(new Map())
|
||||
|
||||
const performSearch = React.useCallback(
|
||||
async (query: string, currentOffset = 0) => {
|
||||
const cacheKey = `${query}:${currentOffset}`
|
||||
const cached = searchCacheRef.current.get(cacheKey)
|
||||
if (cached && currentOffset === 0) {
|
||||
setItems(cached.items)
|
||||
setHasMore(cached.hasMore)
|
||||
setOffset(0)
|
||||
return
|
||||
}
|
||||
|
||||
if (abortControllerRef.current) {
|
||||
abortControllerRef.current.abort()
|
||||
}
|
||||
|
||||
const controller = new AbortController()
|
||||
abortControllerRef.current = controller
|
||||
|
||||
setLoading(true)
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams({
|
||||
q: query,
|
||||
limit: "20",
|
||||
offset: currentOffset.toString(),
|
||||
})
|
||||
|
||||
const response = await fetch(`/api/search/community?${params}`, {
|
||||
signal: controller.signal,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error("Search failed")
|
||||
}
|
||||
|
||||
const data: SearchResponse = await response.json()
|
||||
|
||||
searchCacheRef.current.set(cacheKey, data)
|
||||
|
||||
if (currentOffset === 0) {
|
||||
setItems(data.items)
|
||||
} else {
|
||||
setItems((prev) => [...prev, ...data.items])
|
||||
}
|
||||
|
||||
setHasMore(data.hasMore)
|
||||
setOffset(currentOffset)
|
||||
} catch (error) {
|
||||
if (error instanceof Error && error.name !== "AbortError") {
|
||||
console.error("Search error:", error)
|
||||
}
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
},
|
||||
[]
|
||||
)
|
||||
|
||||
React.useEffect(() => {
|
||||
performSearch(search, 0)
|
||||
}, [search, performSearch])
|
||||
|
||||
const loadMore = React.useCallback(() => {
|
||||
if (!loading && hasMore) {
|
||||
performSearch(search, offset + 20)
|
||||
}
|
||||
}, [search, offset, loading, hasMore, performSearch])
|
||||
|
||||
if (loading && items.length === 0) {
|
||||
return <ComponentsCommunitySkeleton />
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<ComponentsCommunityResults items={items} />
|
||||
{hasMore && (
|
||||
<div className="flex justify-center pt-4">
|
||||
<Button
|
||||
onClick={loadMore}
|
||||
disabled={loading}
|
||||
variant="secondary"
|
||||
size="sm"
|
||||
>
|
||||
{loading ? "Loading..." : "Load more"}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -41,7 +41,11 @@ export function SiteHeader() {
|
||||
<MainNav items={siteConfig.navItems} className="hidden lg:flex" />
|
||||
<div className="ml-auto flex items-center gap-2 md:flex-1 md:justify-end">
|
||||
<div className="hidden w-full flex-1 md:flex md:w-auto md:flex-none">
|
||||
<CommandMenu tree={pageTree} colors={colors} />
|
||||
<CommandMenu
|
||||
tree={pageTree}
|
||||
colors={colors}
|
||||
navItems={siteConfig.navItems}
|
||||
/>
|
||||
</div>
|
||||
<Separator
|
||||
orientation="vertical"
|
||||
|
||||
@@ -4,6 +4,33 @@ description: Latest updates and announcements.
|
||||
toc: false
|
||||
---
|
||||
|
||||
## July 2025 - Universal Registry Items
|
||||
|
||||
We've added support for universal registry items. This allows you to create registry items that can be distributed to any project i.e. no framework, no components.json, no tailwind, no react required.
|
||||
|
||||
This new registry item type unlocks a lot of new workflows. You can now distribute code, config, rules, docs, anything to any code project.
|
||||
|
||||
See the [docs](/docs/registry/examples) for more details and examples.
|
||||
|
||||
## July 2025 - Local File Support
|
||||
|
||||
The shadcn CLI now supports local files. Initialize projects and add components, themes, hooks, utils and more from local JSON files.
|
||||
|
||||
```bash
|
||||
# Initialize a project from a local file
|
||||
npx shadcn init ./template.json
|
||||
|
||||
# Add a component from a local file
|
||||
npx shadcn add ./block.json
|
||||
```
|
||||
|
||||
This feature enables powerful new workflows:
|
||||
|
||||
- **Zero setup** - No remote registries required
|
||||
- **Faster development** - Test registry items locally before publishing
|
||||
- **Enhanced workflow for agents and MCP** - Generate and run registry items locally
|
||||
- **Private components** - Keep proprietary components local and private.
|
||||
|
||||
## June 2025 - `radix-ui`
|
||||
|
||||
We've added a new command to migrate to the new `radix-ui` package. This command will replace all `@radix-ui/react-*` imports with `radix-ui`.
|
||||
|
||||
@@ -4,9 +4,15 @@ description: Beautiful charts. Built using Recharts. Copy and paste into your ap
|
||||
component: true
|
||||
---
|
||||
|
||||
<Callout>
|
||||
|
||||
**Note:** We're working on upgrading to Recharts v3. In the meantime, if you'd like to start testing v3, see the code in the comment [here](https://github.com/shadcn-ui/ui/issues/7669#issuecomment-2998299159). We'll have an official release soon.
|
||||
|
||||
</Callout>
|
||||
|
||||
<ComponentPreview
|
||||
name="chart-bar-interactive"
|
||||
className="theme-blue -mt-4 [&_.preview]:p-0 [&_.preview]:lg:min-h-[404px] [&_.preview>div]:w-full [&_.preview>div]:border-none [&_.preview>div]:shadow-none"
|
||||
className="theme-blue [&_.preview]:h-auto [&_.preview]:p-0 [&_.preview]:lg:min-h-[404px] [&_.preview>div]:w-full [&_.preview>div]:border-none [&_.preview>div]:shadow-none"
|
||||
hideCode
|
||||
/>
|
||||
|
||||
|
||||
12
apps/v4/content/docs/components/community.mdx
Normal file
12
apps/v4/content/docs/components/community.mdx
Normal file
@@ -0,0 +1,12 @@
|
||||
---
|
||||
title: Community
|
||||
description: Discover components from the community.
|
||||
---
|
||||
|
||||
import { ComponentsCommunitySearch } from "@/components/components-community"
|
||||
|
||||
The following components are created and maintained by the community. They are compatible with shadcn/ui primitives and works with the CLI.
|
||||
|
||||
You will be taken to the external component page for preview, documentation and installation instructions.
|
||||
|
||||
<ComponentsCommunitySearch className="mt-6" />
|
||||
@@ -3,4 +3,9 @@ title: Components
|
||||
description: Here you can find all the components available in the library. We are working on adding more components.
|
||||
---
|
||||
|
||||
<Callout className="mb-6">
|
||||
Looking for more components? Check out the [Components
|
||||
Community](/docs/components/community) page.
|
||||
</Callout>
|
||||
|
||||
<ComponentsList />
|
||||
|
||||
4
apps/v4/content/docs/components/meta.json
Normal file
4
apps/v4/content/docs/components/meta.json
Normal file
@@ -0,0 +1,4 @@
|
||||
{
|
||||
"title": "Components",
|
||||
"pages": ["!community", "..."]
|
||||
}
|
||||
@@ -368,3 +368,70 @@ Note: you need to define both `@keyframes` in css and `theme` in cssVars to use
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Universal Items
|
||||
|
||||
As of `2.9.0`, you can create universal items that can be installed without framework detection or components.json.
|
||||
|
||||
To make an item universal i.e framework agnostic, all the files in the item must have an explicit target.
|
||||
|
||||
Here's an example of a registry item that installs custom Cursor rules for _python_:
|
||||
|
||||
```json title=".cursor/rules/custom-python.mdc" showLineNumbers {9}
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
||||
"name": "python-rules",
|
||||
"type": "registry:item",
|
||||
"files": [
|
||||
{
|
||||
"path": "/path/to/your/registry/default/custom-python.mdc",
|
||||
"type": "registry:file",
|
||||
"target": "~/.cursor/rules/custom-python.mdc",
|
||||
"content": "..."
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Here's another example for installation custom ESLint config:
|
||||
|
||||
```json title=".eslintrc.json" showLineNumbers {9}
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
||||
"name": "my-eslint-config",
|
||||
"type": "registry:item",
|
||||
"files": [
|
||||
{
|
||||
"path": "/path/to/your/registry/default/custom-eslint.json",
|
||||
"type": "registry:file",
|
||||
"target": "~/.eslintrc.json",
|
||||
"content": "..."
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
You can also have a universal item that installs multiple files:
|
||||
|
||||
```json title="my-custom-starter-template.json" showLineNumbers {9}
|
||||
{
|
||||
"$schema": "https://ui.shadcn.com/schema/registry-item.json",
|
||||
"name": "my-custom-start-template",
|
||||
"type": "registry:item",
|
||||
dependencies: ["better-auth"]
|
||||
"files": [
|
||||
{
|
||||
"path": "/path/to/file-01.json",
|
||||
"type": "registry:file",
|
||||
"target": "~/file-01.json",
|
||||
"content": "..."
|
||||
},
|
||||
{
|
||||
"path": "/path/to/file-02.vue",
|
||||
"type": "registry:file",
|
||||
"target": "~/pages/file-02.vue",
|
||||
"content": "..."
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
@@ -1,15 +1,14 @@
|
||||
---
|
||||
title: Registry
|
||||
description: Run your own component registry.
|
||||
description: Run your own code registry.
|
||||
---
|
||||
|
||||
<Callout>
|
||||
**Note:** This feature is currently experimental. Help us improve it by
|
||||
testing it out and sending feedback. If you have any questions, please [reach
|
||||
out to us](https://github.com/shadcn-ui/ui/discussions).
|
||||
</Callout>
|
||||
You can use the `shadcn` CLI to run your own code registry. Running your own registry allows you to distribute your custom components, hooks, pages, config, rules and other files to any project.
|
||||
|
||||
You can use the `shadcn` CLI to run your own component registry. Running your own registry allows you to distribute your custom components, hooks, pages, and other files to any React project.
|
||||
<Callout>
|
||||
**Note:** The registry works with any project type and any framework, and is
|
||||
not limited to React.
|
||||
</Callout>
|
||||
|
||||
<figure className="flex flex-col gap-4">
|
||||
<Image
|
||||
@@ -27,12 +26,10 @@ You can use the `shadcn` CLI to run your own component registry. Running your ow
|
||||
className="mt-6 hidden w-full overflow-hidden rounded-lg border shadow-sm dark:block"
|
||||
/>
|
||||
<figcaption className="text-center text-sm text-gray-500">
|
||||
Distribute code to any React project.
|
||||
A distribution system for code
|
||||
</figcaption>
|
||||
</figure>
|
||||
|
||||
Registry items are automatically compatible with the `shadcn` CLI and `Open in v0`.
|
||||
|
||||
## Requirements
|
||||
|
||||
You are free to design and host your custom registry as you see fit. The only requirement is that your registry items must be valid JSON files that conform to the [registry-item schema specification](/docs/registry/registry-item-json).
|
||||
|
||||
@@ -107,6 +107,7 @@ The following types are supported:
|
||||
| `registry:file` | Use for miscellaneous files. |
|
||||
| `registry:style` | Use for registry styles. eg. `new-york` |
|
||||
| `registry:theme` | Use for themes. |
|
||||
| `registry:item` | Use for universal registry items. |
|
||||
|
||||
### author
|
||||
|
||||
|
||||
@@ -33,6 +33,10 @@ export const siteConfig = {
|
||||
href: "/colors",
|
||||
label: "Colors",
|
||||
},
|
||||
{
|
||||
href: "/docs/components/community",
|
||||
label: "Community",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -68,6 +68,11 @@ const nextConfig = {
|
||||
destination: "/view/:name",
|
||||
permanent: true,
|
||||
},
|
||||
{
|
||||
source: "/community",
|
||||
destination: "/docs/components/community",
|
||||
permanent: false,
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "next dev --turbopack --port 4000",
|
||||
"build": "pnpm --filter=shadcn build && next build",
|
||||
"build": "pnpm --filter=shadcn build && pnpm build:external && next build",
|
||||
"start": "next start --port 4000",
|
||||
"lint": "next lint",
|
||||
"lint:fix": "next lint --fix",
|
||||
@@ -14,6 +14,7 @@
|
||||
"format:check": "prettier --check \"**/*.{ts,tsx,mdx}\" --cache",
|
||||
"registry:build": "tsx --tsconfig ./tsconfig.scripts.json ./scripts/build-registry.mts && prettier --log-level silent --write \"registry/**/*.{ts,tsx,json,mdx}\" --cache",
|
||||
"registry:capture": "tsx --tsconfig ./tsconfig.scripts.json ./scripts/capture-registry.mts",
|
||||
"build:external": "tsx --tsconfig ./tsconfig.scripts.json ./scripts/build-external-registry.mts",
|
||||
"postinstall": "fumadocs-mdx"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -23,6 +24,7 @@
|
||||
"@dnd-kit/utilities": "^3.2.2",
|
||||
"@faker-js/faker": "^8.2.0",
|
||||
"@hookform/resolvers": "^3.10.0",
|
||||
"@orama/orama": "^3.1.11",
|
||||
"@radix-ui/react-accessible-icon": "^1.1.1",
|
||||
"@radix-ui/react-accordion": "^1.2.2",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.5",
|
||||
@@ -77,6 +79,7 @@
|
||||
"motion": "^12.12.1",
|
||||
"next": "15.3.1",
|
||||
"next-themes": "0.4.6",
|
||||
"nuqs": "^2.4.3",
|
||||
"postcss": "^8.5.1",
|
||||
"react": "19.1.0",
|
||||
"react-day-picker": "^9.7.0",
|
||||
@@ -86,7 +89,7 @@
|
||||
"recharts": "2.15.1",
|
||||
"rehype-pretty-code": "^0.14.1",
|
||||
"rimraf": "^6.0.1",
|
||||
"shadcn": "2.8.0",
|
||||
"shadcn": "2.9.0",
|
||||
"shiki": "^1.10.1",
|
||||
"sonner": "^2.0.0",
|
||||
"tailwind-merge": "^3.0.1",
|
||||
|
||||
@@ -180,7 +180,7 @@
|
||||
"name": "chart",
|
||||
"type": "registry:ui",
|
||||
"dependencies": [
|
||||
"recharts",
|
||||
"recharts@2.15.4",
|
||||
"lucide-react"
|
||||
],
|
||||
"registryDependencies": [
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -4,7 +4,7 @@
|
||||
"type": "registry:ui",
|
||||
"author": "shadcn (https://ui.shadcn.com)",
|
||||
"dependencies": [
|
||||
"recharts",
|
||||
"recharts@2.15.4",
|
||||
"lucide-react"
|
||||
],
|
||||
"registryDependencies": [
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -3,7 +3,7 @@
|
||||
"name": "chart",
|
||||
"type": "registry:ui",
|
||||
"dependencies": [
|
||||
"recharts",
|
||||
"recharts@2.15.4",
|
||||
"lucide-react"
|
||||
],
|
||||
"registryDependencies": [
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -4,7 +4,7 @@
|
||||
"type": "registry:ui",
|
||||
"author": "shadcn (https://ui.shadcn.com)",
|
||||
"dependencies": [
|
||||
"recharts",
|
||||
"recharts@2.15.4",
|
||||
"lucide-react"
|
||||
],
|
||||
"registryDependencies": [
|
||||
|
||||
@@ -17,7 +17,8 @@
|
||||
"registry:theme",
|
||||
"registry:page",
|
||||
"registry:file",
|
||||
"registry:style"
|
||||
"registry:style",
|
||||
"registry:item"
|
||||
],
|
||||
"description": "The type of the item. This is used to determine the type and target path of the item when resolved for a project."
|
||||
},
|
||||
@@ -79,7 +80,8 @@
|
||||
"registry:theme",
|
||||
"registry:page",
|
||||
"registry:file",
|
||||
"registry:style"
|
||||
"registry:style",
|
||||
"registry:item"
|
||||
],
|
||||
"description": "The type of the file. This is used to determine the type of the file when resolved for a project."
|
||||
},
|
||||
|
||||
@@ -169,7 +169,7 @@
|
||||
"name": "chart",
|
||||
"type": "registry:ui",
|
||||
"dependencies": [
|
||||
"recharts",
|
||||
"recharts@2.15.4",
|
||||
"lucide-react"
|
||||
],
|
||||
"registryDependencies": [
|
||||
|
||||
@@ -73,7 +73,10 @@ function Calendar({
|
||||
"relative has-focus:border-ring border border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] rounded-md",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn("absolute inset-0 opacity-0", defaultClassNames.dropdown),
|
||||
dropdown: cn(
|
||||
"absolute bg-popover inset-0 opacity-0",
|
||||
defaultClassNames.dropdown
|
||||
),
|
||||
caption_label: cn(
|
||||
"select-none font-medium",
|
||||
captionLayout === "label"
|
||||
|
||||
5
apps/v4/registry/registry-external.json
Normal file
5
apps/v4/registry/registry-external.json
Normal file
@@ -0,0 +1,5 @@
|
||||
[
|
||||
"https://api.npoint.io/db04a255782ab866fcd3",
|
||||
"https://api.npoint.io/8183a39e7dad9bb86e78",
|
||||
"https://api.npoint.io/e69a11a4d660bb12c0de"
|
||||
]
|
||||
@@ -155,7 +155,7 @@ export const ui: Registry["items"] = [
|
||||
},
|
||||
],
|
||||
registryDependencies: ["card"],
|
||||
dependencies: ["recharts", "lucide-react"],
|
||||
dependencies: ["recharts@2.15.4", "lucide-react"],
|
||||
},
|
||||
{
|
||||
name: "checkbox",
|
||||
|
||||
171
apps/v4/scripts/build-external-registry.mts
Normal file
171
apps/v4/scripts/build-external-registry.mts
Normal file
@@ -0,0 +1,171 @@
|
||||
import { promises as fs } from "fs"
|
||||
import path from "path"
|
||||
import { create, insertMultiple, save } from "@orama/orama"
|
||||
import { z } from "zod"
|
||||
|
||||
// Schema for registries.json - just an array of URLs
|
||||
const RegistriesConfigSchema = z.array(z.string().url())
|
||||
|
||||
// Schema for registry items (matching the public schema)
|
||||
const RegistryItemSchema = z.object({
|
||||
name: z.string(),
|
||||
type: z.enum([
|
||||
"registry:lib",
|
||||
"registry:block",
|
||||
"registry:component",
|
||||
"registry:ui",
|
||||
"registry:hook",
|
||||
"registry:theme",
|
||||
"registry:page",
|
||||
"registry:file",
|
||||
"registry:style",
|
||||
"registry:item",
|
||||
]),
|
||||
description: z.string().optional(),
|
||||
author: z.string().optional(),
|
||||
dependencies: z.array(z.string()).optional(),
|
||||
devDependencies: z.array(z.string()).optional(),
|
||||
registryDependencies: z.array(z.string()).optional(),
|
||||
files: z.array(z.any()).optional(),
|
||||
categories: z.array(z.string()).optional(),
|
||||
meta: z.record(z.any()).optional(),
|
||||
})
|
||||
|
||||
const RegistrySchema = z.object({
|
||||
name: z.string(),
|
||||
homepage: z.string(),
|
||||
items: z.array(RegistryItemSchema),
|
||||
})
|
||||
|
||||
type Registry = z.infer<typeof RegistrySchema>
|
||||
type RegistryItem = z.infer<typeof RegistryItemSchema>
|
||||
|
||||
interface ProcessedRegistry {
|
||||
url: string
|
||||
data: Registry
|
||||
items: RegistryItem[]
|
||||
fetchedAt: string
|
||||
error?: string
|
||||
}
|
||||
|
||||
async function fetchRegistry(url: string): Promise<ProcessedRegistry> {
|
||||
console.log(`📥 Fetching registry from ${url}`)
|
||||
|
||||
try {
|
||||
const response = await fetch(url)
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const validated = RegistrySchema.parse(data)
|
||||
|
||||
// Items are already in the correct format
|
||||
const items = validated.items
|
||||
|
||||
console.log(`✅ Successfully fetched ${validated.items.length} items from ${validated.name}`)
|
||||
|
||||
return {
|
||||
url,
|
||||
data: validated,
|
||||
items: items,
|
||||
fetchedAt: new Date().toISOString(),
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`❌ Failed to fetch ${url}:`, error)
|
||||
return {
|
||||
url,
|
||||
data: { name: "Unknown", homepage: url, items: [] },
|
||||
items: [],
|
||||
fetchedAt: new Date().toISOString(),
|
||||
error: error instanceof Error ? error.message : "Unknown error",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function buildExternalRegistry() {
|
||||
console.log("🔨 Building external registry index...")
|
||||
|
||||
// Read registries config
|
||||
const configPath = path.join(process.cwd(), "registry", "registry-external.json")
|
||||
const configContent = await fs.readFile(configPath, "utf-8")
|
||||
const config = RegistriesConfigSchema.parse(JSON.parse(configContent))
|
||||
|
||||
// Output will go to content directory
|
||||
|
||||
// Fetch all registries
|
||||
const results = await Promise.all(
|
||||
config.map(url => fetchRegistry(url))
|
||||
)
|
||||
|
||||
// Combine all items from all registries, adding registry name to each item
|
||||
const allItems = results.flatMap(r =>
|
||||
r.items.map(item => ({
|
||||
...item,
|
||||
meta: {
|
||||
...item.meta,
|
||||
registryName: r.data.name,
|
||||
registryHomepage: r.data.homepage,
|
||||
}
|
||||
}))
|
||||
)
|
||||
|
||||
// Create a registry following the standard schema
|
||||
const registry = {
|
||||
name: "External Registries",
|
||||
homepage: "https://ui.shadcn.com/docs/components",
|
||||
items: allItems,
|
||||
}
|
||||
|
||||
// Create data directory
|
||||
const dataDir = path.join(process.cwd(), ".data")
|
||||
await fs.mkdir(dataDir, { recursive: true })
|
||||
|
||||
// Write registry to data directory
|
||||
const outputPath = path.join(dataDir, "external-registries.json")
|
||||
await fs.writeFile(outputPath, JSON.stringify(registry, null, 2))
|
||||
|
||||
// Create search index
|
||||
console.log("🔍 Building search index...")
|
||||
const searchDb = await create({
|
||||
schema: {
|
||||
name: 'string',
|
||||
description: 'string',
|
||||
type: 'string',
|
||||
author: 'string',
|
||||
url: 'string',
|
||||
registryName: 'string',
|
||||
},
|
||||
components: {
|
||||
tokenizer: {
|
||||
stemming: false, // Disable stemming for faster indexing
|
||||
stopWords: false, // Disable stop words for component names
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
// Prepare items for indexing
|
||||
const searchItems = allItems.map(item => ({
|
||||
name: item.name,
|
||||
description: item.description || '',
|
||||
type: item.type,
|
||||
author: item.author || '',
|
||||
url: item.meta?.url || '',
|
||||
registryName: item.meta?.registryName || '',
|
||||
}))
|
||||
|
||||
await insertMultiple(searchDb, searchItems)
|
||||
|
||||
// Save search index
|
||||
const indexPath = path.join(dataDir, "external-registries-index.json")
|
||||
const index = await save(searchDb)
|
||||
await fs.writeFile(indexPath, JSON.stringify(index))
|
||||
|
||||
console.log(`✨ External registry built successfully!`)
|
||||
console.log(`📊 Total registries: ${results.length}`)
|
||||
console.log(`📦 Total items: ${allItems.length}`)
|
||||
console.log(`📍 Registry saved to: ${outputPath}`)
|
||||
console.log(`🔍 Search index saved to: ${indexPath}`)
|
||||
}
|
||||
|
||||
buildExternalRegistry().catch(console.error)
|
||||
@@ -88,7 +88,7 @@
|
||||
"react-resizable-panels": "^2.0.22",
|
||||
"react-wrap-balancer": "^0.4.1",
|
||||
"recharts": "2.12.7",
|
||||
"shadcn": "2.8.0",
|
||||
"shadcn": "2.9.0",
|
||||
"sharp": "^0.32.6",
|
||||
"sonner": "^1.2.3",
|
||||
"swr": "2.2.6-beta.3",
|
||||
|
||||
@@ -180,7 +180,7 @@
|
||||
"name": "chart",
|
||||
"type": "registry:ui",
|
||||
"dependencies": [
|
||||
"recharts",
|
||||
"recharts@2.15.4",
|
||||
"lucide-react"
|
||||
],
|
||||
"registryDependencies": [
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -4,7 +4,7 @@
|
||||
"type": "registry:ui",
|
||||
"author": "shadcn (https://ui.shadcn.com)",
|
||||
"dependencies": [
|
||||
"recharts",
|
||||
"recharts@2.15.4",
|
||||
"lucide-react"
|
||||
],
|
||||
"registryDependencies": [
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -3,7 +3,7 @@
|
||||
"name": "chart",
|
||||
"type": "registry:ui",
|
||||
"dependencies": [
|
||||
"recharts",
|
||||
"recharts@2.15.4",
|
||||
"lucide-react"
|
||||
],
|
||||
"registryDependencies": [
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -4,7 +4,7 @@
|
||||
"type": "registry:ui",
|
||||
"author": "shadcn (https://ui.shadcn.com)",
|
||||
"dependencies": [
|
||||
"recharts",
|
||||
"recharts@2.15.4",
|
||||
"lucide-react"
|
||||
],
|
||||
"registryDependencies": [
|
||||
|
||||
@@ -73,7 +73,10 @@ function Calendar({
|
||||
"has-focus:border-ring border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] relative rounded-md border",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn("absolute inset-0 opacity-0", defaultClassNames.dropdown),
|
||||
dropdown: cn(
|
||||
"bg-popover absolute inset-0 opacity-0",
|
||||
defaultClassNames.dropdown
|
||||
),
|
||||
caption_label: cn(
|
||||
"select-none font-medium",
|
||||
captionLayout === "label"
|
||||
|
||||
@@ -73,7 +73,10 @@ function Calendar({
|
||||
"has-focus:border-ring border-input shadow-xs has-focus:ring-ring/50 has-focus:ring-[3px] relative rounded-md border",
|
||||
defaultClassNames.dropdown_root
|
||||
),
|
||||
dropdown: cn("absolute inset-0 opacity-0", defaultClassNames.dropdown),
|
||||
dropdown: cn(
|
||||
"bg-popover absolute inset-0 opacity-0",
|
||||
defaultClassNames.dropdown
|
||||
),
|
||||
caption_label: cn(
|
||||
"select-none font-medium",
|
||||
captionLayout === "label"
|
||||
|
||||
@@ -155,7 +155,7 @@ export const ui: Registry["items"] = [
|
||||
},
|
||||
],
|
||||
registryDependencies: ["card"],
|
||||
dependencies: ["recharts", "lucide-react"],
|
||||
dependencies: ["recharts@2.15.4", "lucide-react"],
|
||||
},
|
||||
{
|
||||
name: "checkbox",
|
||||
|
||||
@@ -35,6 +35,7 @@
|
||||
"www:build": "pnpm --filter=www build",
|
||||
"v4:dev": "pnpm --filter=v4 dev",
|
||||
"v4:build": "pnpm --filter=v4 build",
|
||||
"build:external": "pnpm --filter=v4 build:external",
|
||||
"lint": "turbo run lint",
|
||||
"lint:fix": "turbo run lint:fix",
|
||||
"preview": "turbo run preview",
|
||||
|
||||
@@ -1,5 +1,17 @@
|
||||
# @shadcn/ui
|
||||
|
||||
## 2.9.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- [#7782](https://github.com/shadcn-ui/ui/pull/7782) [`06d03d64f437b543bf5fa07ccbc559f285538ffd`](https://github.com/shadcn-ui/ui/commit/06d03d64f437b543bf5fa07ccbc559f285538ffd) Thanks [@shadcn](https://github.com/shadcn)! - add universal registry items support
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- [#7795](https://github.com/shadcn-ui/ui/pull/7795) [`6c341c16aeaf5ade177a4a1ba4fb9afcd33d5fee`](https://github.com/shadcn-ui/ui/commit/6c341c16aeaf5ade177a4a1ba4fb9afcd33d5fee) Thanks [@shadcn](https://github.com/shadcn)! - fix safe target handling
|
||||
|
||||
- [#7757](https://github.com/shadcn-ui/ui/pull/7757) [`db93787712fe51346bf87dbae8b4cf4e38ed8c27`](https://github.com/shadcn-ui/ui/commit/db93787712fe51346bf87dbae8b4cf4e38ed8c27) Thanks [@shadcn](https://github.com/shadcn)! - implement registry path validation
|
||||
|
||||
## 2.8.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "shadcn",
|
||||
"version": "2.8.0",
|
||||
"version": "2.9.0",
|
||||
"description": "Add components to your apps.",
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
|
||||
@@ -1,13 +1,18 @@
|
||||
import fs from "fs"
|
||||
import path from "path"
|
||||
import { runInit } from "@/src/commands/init"
|
||||
import { preFlightAdd } from "@/src/preflights/preflight-add"
|
||||
import { getRegistryIndex, getRegistryItem } from "@/src/registry/api"
|
||||
import { registryItemTypeSchema } from "@/src/registry/schema"
|
||||
import { isLocalFile, isUrl } from "@/src/registry/utils"
|
||||
import {
|
||||
isLocalFile,
|
||||
isUniversalRegistryItem,
|
||||
isUrl,
|
||||
} from "@/src/registry/utils"
|
||||
import { addComponents } from "@/src/utils/add-components"
|
||||
import { createProject } from "@/src/utils/create-project"
|
||||
import * as ERRORS from "@/src/utils/errors"
|
||||
import { getConfig } from "@/src/utils/get-config"
|
||||
import { createConfig, getConfig } from "@/src/utils/get-config"
|
||||
import { getProjectInfo } from "@/src/utils/get-project-info"
|
||||
import { handleError } from "@/src/utils/handle-error"
|
||||
import { highlighter } from "@/src/utils/highlighter"
|
||||
@@ -78,13 +83,14 @@ export const add = new Command()
|
||||
})
|
||||
|
||||
let itemType: z.infer<typeof registryItemTypeSchema> | undefined
|
||||
let registryItem: any = null
|
||||
|
||||
if (
|
||||
components.length > 0 &&
|
||||
(isUrl(components[0]) || isLocalFile(components[0]))
|
||||
) {
|
||||
const item = await getRegistryItem(components[0], "")
|
||||
itemType = item?.type
|
||||
registryItem = await getRegistryItem(components[0], "")
|
||||
itemType = registryItem?.type
|
||||
}
|
||||
|
||||
if (
|
||||
@@ -130,6 +136,22 @@ export const add = new Command()
|
||||
}
|
||||
}
|
||||
|
||||
if (isUniversalRegistryItem(registryItem)) {
|
||||
// Universal items only cares about the cwd.
|
||||
if (!fs.existsSync(options.cwd)) {
|
||||
throw new Error(`Directory ${options.cwd} does not exist`)
|
||||
}
|
||||
|
||||
const minimalConfig = createConfig({
|
||||
resolvedPaths: {
|
||||
cwd: options.cwd,
|
||||
},
|
||||
})
|
||||
|
||||
await addComponents(options.components, minimalConfig, options)
|
||||
return
|
||||
}
|
||||
|
||||
let { errors, config } = await preFlightAdd(options)
|
||||
|
||||
// No components.json file. Prompt the user to run init.
|
||||
|
||||
@@ -13,6 +13,7 @@ export const registryItemTypeSchema = z.enum([
|
||||
"registry:file",
|
||||
"registry:theme",
|
||||
"registry:style",
|
||||
"registry:item",
|
||||
|
||||
// Internal use only
|
||||
"registry:example",
|
||||
|
||||
@@ -1,6 +1,11 @@
|
||||
import { describe, expect, it } from "vitest"
|
||||
|
||||
import { getDependencyFromModuleSpecifier, isLocalFile, isUrl } from "./utils"
|
||||
import {
|
||||
getDependencyFromModuleSpecifier,
|
||||
isLocalFile,
|
||||
isUniversalRegistryItem,
|
||||
isUrl,
|
||||
} from "./utils"
|
||||
|
||||
describe("getDependencyFromModuleSpecifier", () => {
|
||||
it("should return the first part of a non-scoped package with path", () => {
|
||||
@@ -130,3 +135,139 @@ describe("isLocalFile", () => {
|
||||
expect(isLocalFile("/absolute/path")).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe("isUniversalRegistryItem", () => {
|
||||
it("should return true when all files have targets", () => {
|
||||
const registryItem = {
|
||||
files: [
|
||||
{
|
||||
path: "file1.ts",
|
||||
target: "src/file1.ts",
|
||||
type: "registry:lib" as const,
|
||||
},
|
||||
{
|
||||
path: "file2.ts",
|
||||
target: "src/utils/file2.ts",
|
||||
type: "registry:lib" as const,
|
||||
},
|
||||
],
|
||||
}
|
||||
expect(isUniversalRegistryItem(registryItem)).toBe(true)
|
||||
})
|
||||
|
||||
it("should return false when some files lack targets", () => {
|
||||
const registryItem = {
|
||||
files: [
|
||||
{
|
||||
path: "file1.ts",
|
||||
target: "src/file1.ts",
|
||||
type: "registry:lib" as const,
|
||||
},
|
||||
{ path: "file2.ts", target: "", type: "registry:lib" as const },
|
||||
],
|
||||
}
|
||||
expect(isUniversalRegistryItem(registryItem)).toBe(false)
|
||||
})
|
||||
|
||||
it("should return false when no files have targets", () => {
|
||||
const registryItem = {
|
||||
files: [
|
||||
{ path: "file1.ts", target: "", type: "registry:lib" as const },
|
||||
{ path: "file2.ts", target: "", type: "registry:lib" as const },
|
||||
],
|
||||
}
|
||||
expect(isUniversalRegistryItem(registryItem)).toBe(false)
|
||||
})
|
||||
|
||||
it("should return false when files array is empty", () => {
|
||||
const registryItem = {
|
||||
files: [],
|
||||
}
|
||||
expect(isUniversalRegistryItem(registryItem)).toBe(false)
|
||||
})
|
||||
|
||||
it("should return false when files is undefined", () => {
|
||||
const registryItem = {}
|
||||
expect(isUniversalRegistryItem(registryItem)).toBe(false)
|
||||
})
|
||||
|
||||
it("should return false when registryItem is null", () => {
|
||||
expect(isUniversalRegistryItem(null)).toBe(false)
|
||||
})
|
||||
|
||||
it("should return false when registryItem is undefined", () => {
|
||||
expect(isUniversalRegistryItem(undefined)).toBe(false)
|
||||
})
|
||||
|
||||
it("should return false when target is null", () => {
|
||||
const registryItem = {
|
||||
files: [
|
||||
{
|
||||
path: "file1.ts",
|
||||
target: null as any,
|
||||
type: "registry:lib" as const,
|
||||
},
|
||||
],
|
||||
}
|
||||
expect(isUniversalRegistryItem(registryItem)).toBe(false)
|
||||
})
|
||||
|
||||
it("should return false when target is undefined", () => {
|
||||
const registryItem = {
|
||||
files: [{ path: "file1.ts", type: "registry:lib" as const }],
|
||||
}
|
||||
expect(isUniversalRegistryItem(registryItem)).toBe(false)
|
||||
})
|
||||
|
||||
it("should handle mixed file types correctly", () => {
|
||||
const registryItem = {
|
||||
files: [
|
||||
{
|
||||
path: "component.tsx",
|
||||
target: "components/ui/component.tsx",
|
||||
type: "registry:ui" as const,
|
||||
},
|
||||
{
|
||||
path: "utils.ts",
|
||||
target: "lib/utils.ts",
|
||||
type: "registry:lib" as const,
|
||||
},
|
||||
{
|
||||
path: "hook.ts",
|
||||
target: "hooks/use-something.ts",
|
||||
type: "registry:hook" as const,
|
||||
},
|
||||
],
|
||||
}
|
||||
expect(isUniversalRegistryItem(registryItem)).toBe(true)
|
||||
})
|
||||
|
||||
it("should return true when all targets are non-empty strings", () => {
|
||||
const registryItem = {
|
||||
files: [
|
||||
{ path: "file1.ts", target: " ", type: "registry:lib" as const }, // whitespace is truthy
|
||||
{ path: "file2.ts", target: "0", type: "registry:lib" as const }, // "0" is truthy
|
||||
],
|
||||
}
|
||||
expect(isUniversalRegistryItem(registryItem)).toBe(true)
|
||||
})
|
||||
|
||||
it("should handle real-world example with path traversal attempts", () => {
|
||||
const registryItem = {
|
||||
files: [
|
||||
{
|
||||
path: "malicious.ts",
|
||||
target: "../../../etc/passwd",
|
||||
type: "registry:lib" as const,
|
||||
},
|
||||
{
|
||||
path: "normal.ts",
|
||||
target: "src/normal.ts",
|
||||
type: "registry:lib" as const,
|
||||
},
|
||||
],
|
||||
}
|
||||
// The function should still return true - path validation is handled elsewhere
|
||||
expect(isUniversalRegistryItem(registryItem)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -256,3 +256,20 @@ export function isUrl(path: string) {
|
||||
export function isLocalFile(path: string) {
|
||||
return path.endsWith(".json") && !isUrl(path)
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a registry item is universal (framework-agnostic).
|
||||
* A universal registry item has all files with explicit targets.
|
||||
* It can be installed without framework detection or components.json.
|
||||
*/
|
||||
export function isUniversalRegistryItem(
|
||||
registryItem:
|
||||
| Pick<z.infer<typeof registryItemSchema>, "files">
|
||||
| null
|
||||
| undefined
|
||||
): boolean {
|
||||
return (
|
||||
!!registryItem?.files?.length &&
|
||||
registryItem.files.every((file) => !!file.target)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -6,7 +6,10 @@ import {
|
||||
registryResolveItemsTree,
|
||||
resolveRegistryItems,
|
||||
} from "@/src/registry/api"
|
||||
import { registryItemSchema } from "@/src/registry/schema"
|
||||
import {
|
||||
registryItemFileSchema,
|
||||
registryItemSchema,
|
||||
} from "@/src/registry/schema"
|
||||
import {
|
||||
configSchema,
|
||||
findCommonRoot,
|
||||
@@ -17,6 +20,7 @@ import {
|
||||
} from "@/src/utils/get-config"
|
||||
import { getProjectTailwindVersionFromConfig } from "@/src/utils/get-project-info"
|
||||
import { handleError } from "@/src/utils/handle-error"
|
||||
import { isSafeTarget } from "@/src/utils/is-safe-target"
|
||||
import { logger } from "@/src/utils/logger"
|
||||
import { spinner } from "@/src/utils/spinner"
|
||||
import { updateCss } from "@/src/utils/updaters/update-css"
|
||||
@@ -79,6 +83,14 @@ async function addProjectComponents(
|
||||
registrySpinner?.fail()
|
||||
return handleError(new Error("Failed to fetch components from registry."))
|
||||
}
|
||||
|
||||
try {
|
||||
validateFilesTarget(tree.files ?? [], config.resolvedPaths.cwd)
|
||||
} catch (error) {
|
||||
registrySpinner?.fail()
|
||||
return handleError(error)
|
||||
}
|
||||
|
||||
registrySpinner?.succeed()
|
||||
|
||||
const tailwindVersion = await getProjectTailwindVersionFromConfig(config)
|
||||
@@ -147,6 +159,13 @@ async function addWorkspaceComponents(
|
||||
const filesUpdated: string[] = []
|
||||
const filesSkipped: string[] = []
|
||||
|
||||
const files = payload.flatMap((item) => item.files ?? [])
|
||||
try {
|
||||
validateFilesTarget(files, config.resolvedPaths.cwd)
|
||||
} catch (error) {
|
||||
return handleError(error)
|
||||
}
|
||||
|
||||
const rootSpinner = spinner(`Installing components.`)?.start()
|
||||
|
||||
for (const component of payload) {
|
||||
@@ -317,3 +336,20 @@ async function shouldOverwriteCssVars(
|
||||
component.type === "registry:theme" || component.type === "registry:style"
|
||||
)
|
||||
}
|
||||
|
||||
function validateFilesTarget(
|
||||
files: z.infer<typeof registryItemFileSchema>[],
|
||||
cwd: string
|
||||
) {
|
||||
for (const file of files) {
|
||||
if (!file?.target) {
|
||||
continue
|
||||
}
|
||||
|
||||
if (!isSafeTarget(file.target, cwd)) {
|
||||
throw new Error(
|
||||
`We found an unsafe file path "${file.target} in the registry item. Installation aborted.`
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -225,3 +225,64 @@ export async function getTargetStyleFromConfig(cwd: string, fallback: string) {
|
||||
const projectInfo = await getProjectInfo(cwd)
|
||||
return projectInfo?.tailwindVersion === "v4" ? "new-york-v4" : fallback
|
||||
}
|
||||
|
||||
type DeepPartial<T> = {
|
||||
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P]
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a config object with sensible defaults.
|
||||
* Useful for universal registry items that bypass framework detection.
|
||||
*
|
||||
* @param partial - Partial config values to override defaults
|
||||
* @returns A complete Config object
|
||||
*/
|
||||
export function createConfig(partial?: DeepPartial<Config>): Config {
|
||||
const defaultConfig: Config = {
|
||||
resolvedPaths: {
|
||||
cwd: process.cwd(),
|
||||
tailwindConfig: "",
|
||||
tailwindCss: "",
|
||||
utils: "",
|
||||
components: "",
|
||||
ui: "",
|
||||
lib: "",
|
||||
hooks: "",
|
||||
},
|
||||
style: "",
|
||||
tailwind: {
|
||||
config: "",
|
||||
css: "",
|
||||
baseColor: "",
|
||||
cssVariables: false,
|
||||
},
|
||||
rsc: false,
|
||||
tsx: true,
|
||||
aliases: {
|
||||
components: "",
|
||||
utils: "",
|
||||
},
|
||||
}
|
||||
|
||||
// Deep merge the partial config with defaults
|
||||
if (partial) {
|
||||
return {
|
||||
...defaultConfig,
|
||||
...partial,
|
||||
resolvedPaths: {
|
||||
...defaultConfig.resolvedPaths,
|
||||
...(partial.resolvedPaths || {}),
|
||||
},
|
||||
tailwind: {
|
||||
...defaultConfig.tailwind,
|
||||
...(partial.tailwind || {}),
|
||||
},
|
||||
aliases: {
|
||||
...defaultConfig.aliases,
|
||||
...(partial.aliases || {}),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
return defaultConfig
|
||||
}
|
||||
|
||||
156
packages/shadcn/src/utils/is-safe-target.test.ts
Normal file
156
packages/shadcn/src/utils/is-safe-target.test.ts
Normal file
@@ -0,0 +1,156 @@
|
||||
import { describe, expect, test } from "vitest"
|
||||
|
||||
import { isSafeTarget } from "./is-safe-target"
|
||||
|
||||
describe("isSafeTarget", () => {
|
||||
const cwd = "/foo/bar"
|
||||
|
||||
describe("should reject path traversal attempts", () => {
|
||||
test.each([
|
||||
{
|
||||
description: "basic path traversal with ../",
|
||||
target: "../../etc/passwd",
|
||||
},
|
||||
{
|
||||
description: "nested path traversal",
|
||||
target: "ui/../../../etc/hosts",
|
||||
},
|
||||
{
|
||||
description: "path traversal with ~/../",
|
||||
target: "~/../../../.ssh/authorized_keys",
|
||||
},
|
||||
{
|
||||
description: "absolute paths outside project",
|
||||
target: "/etc/passwd",
|
||||
},
|
||||
{
|
||||
description: "paths that resolve outside project root",
|
||||
target: "foo/bar/../../../../etc/passwd",
|
||||
},
|
||||
{
|
||||
description: "URL-encoded path traversal",
|
||||
target: "%2e%2e%2f%2e%2e%2fetc%2fpasswd",
|
||||
},
|
||||
{
|
||||
description: "double URL-encoded sequences",
|
||||
target: "%252e%252e%252fetc%252fpasswd",
|
||||
},
|
||||
{
|
||||
description: "mixed encoded/plain traversal",
|
||||
target: "..%2f..%2fetc%2fpasswd",
|
||||
},
|
||||
{
|
||||
description: "null byte injection",
|
||||
target: "valid/path\0../../etc/passwd",
|
||||
},
|
||||
{
|
||||
description: "Windows-style path traversal",
|
||||
target: "..\\..\\Windows\\System32\\config",
|
||||
},
|
||||
{
|
||||
description: "Windows absolute paths",
|
||||
target: "C:\\Windows\\System32\\drivers\\etc\\hosts",
|
||||
},
|
||||
{
|
||||
description: "mixed separator traversal",
|
||||
target: "foo\\..\\../etc/passwd",
|
||||
},
|
||||
{
|
||||
description: "current directory reference attacks",
|
||||
target: "foo/./././../../../etc/passwd",
|
||||
},
|
||||
{
|
||||
description: "control characters in paths",
|
||||
target: "foo/\x01\x02/../../etc/passwd",
|
||||
},
|
||||
{
|
||||
description: "Unicode normalization attacks",
|
||||
target: "foo/../\u2025/etc/passwd",
|
||||
},
|
||||
{
|
||||
description:
|
||||
"path traversal with square brackets outside [...] pattern",
|
||||
target: "foo/[bar]/../../etc/passwd",
|
||||
},
|
||||
])("$description", ({ target }) => {
|
||||
expect(isSafeTarget(target, cwd)).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe("should accept safe paths", () => {
|
||||
test.each([
|
||||
{
|
||||
description: "simple relative path",
|
||||
target: "ui/button.tsx",
|
||||
},
|
||||
{
|
||||
description: "nested relative path",
|
||||
target: "components/ui/button.tsx",
|
||||
},
|
||||
{
|
||||
description: "home directory expansion",
|
||||
target: "~/foo.json",
|
||||
},
|
||||
{
|
||||
description: "nested home directory path",
|
||||
target: "~/components/button.tsx",
|
||||
},
|
||||
{
|
||||
description: "dot in filename",
|
||||
target: "components/.env.local",
|
||||
},
|
||||
{
|
||||
description: "path with spaces",
|
||||
target: "my components/button.tsx",
|
||||
},
|
||||
{
|
||||
description: "path with special characters",
|
||||
target: "components/@ui/button.tsx",
|
||||
},
|
||||
{
|
||||
description: "framework routing with square brackets",
|
||||
target: "pages/[id].tsx",
|
||||
},
|
||||
{
|
||||
description: "catch-all routes with [...param]",
|
||||
target: "server/api/auth/[...].ts",
|
||||
},
|
||||
{
|
||||
description: "optional catch-all routes",
|
||||
target: "pages/[[...slug]].tsx",
|
||||
},
|
||||
{
|
||||
description: "dollar sign routes",
|
||||
target: "routes/$userId.tsx",
|
||||
},
|
||||
{
|
||||
description: "complex routing patterns",
|
||||
target: "app/[locale]/[...segments]/page.tsx",
|
||||
},
|
||||
])("$description", ({ target }) => {
|
||||
expect(isSafeTarget(target, cwd)).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe("edge cases", () => {
|
||||
test("should handle empty string", () => {
|
||||
expect(isSafeTarget("", cwd)).toBe(true)
|
||||
})
|
||||
|
||||
test("should handle single dot", () => {
|
||||
expect(isSafeTarget(".", cwd)).toBe(true)
|
||||
})
|
||||
|
||||
test("should reject malformed URL encoding", () => {
|
||||
expect(isSafeTarget("%zz%ff%2e%2e%2f", cwd)).toBe(false)
|
||||
})
|
||||
|
||||
test("should handle paths at project root", () => {
|
||||
expect(isSafeTarget("/foo/bar/test.txt", cwd)).toBe(true)
|
||||
})
|
||||
|
||||
test("should reject paths just outside project root", () => {
|
||||
expect(isSafeTarget("/foo/test.txt", cwd)).toBe(false)
|
||||
})
|
||||
})
|
||||
})
|
||||
98
packages/shadcn/src/utils/is-safe-target.ts
Normal file
98
packages/shadcn/src/utils/is-safe-target.ts
Normal file
@@ -0,0 +1,98 @@
|
||||
import path from "path"
|
||||
|
||||
export function isSafeTarget(targetPath: string, cwd: string): boolean {
|
||||
// Check for null bytes which can be used to bypass validations.
|
||||
if (targetPath.includes("\0")) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Decode URL-encoded sequences to catch encoded traversal attempts.
|
||||
let decodedPath: string
|
||||
try {
|
||||
// Decode multiple times to catch double-encoded sequences.
|
||||
decodedPath = targetPath
|
||||
let prevPath = ""
|
||||
while (decodedPath !== prevPath && decodedPath.includes("%")) {
|
||||
prevPath = decodedPath
|
||||
decodedPath = decodeURIComponent(decodedPath)
|
||||
}
|
||||
} catch {
|
||||
// If decoding fails, treat as unsafe.
|
||||
return false
|
||||
}
|
||||
|
||||
// Normalize both paths to handle different path separators.
|
||||
// Convert Windows backslashes to forward slashes for consistent handling.
|
||||
const normalizedTarget = path.normalize(decodedPath.replace(/\\/g, "/"))
|
||||
const normalizedRoot = path.normalize(cwd)
|
||||
|
||||
// Check for explicit path traversal sequences in both encoded and decoded forms.
|
||||
// Allow [...] pattern which is common in framework routing (e.g., [...slug])
|
||||
const hasPathTraversal = (path: string) => {
|
||||
// Remove [...] patterns before checking for ..
|
||||
const withoutBrackets = path.replace(/\[\.\.\..*?\]/g, "")
|
||||
return withoutBrackets.includes("..")
|
||||
}
|
||||
|
||||
if (
|
||||
hasPathTraversal(normalizedTarget) ||
|
||||
hasPathTraversal(decodedPath) ||
|
||||
hasPathTraversal(targetPath)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check for current directory references that might be used in traversal.
|
||||
// First, remove [...] patterns to avoid false positives
|
||||
const cleanPath = (path: string) => path.replace(/\[\.\.\..*?\]/g, "")
|
||||
const cleanTarget = cleanPath(targetPath)
|
||||
const cleanDecoded = cleanPath(decodedPath)
|
||||
|
||||
const suspiciousPatterns = [
|
||||
/\.\.[\/\\]/, // ../ or ..\
|
||||
/[\/\\]\.\./, // /.. or \..
|
||||
/\.\./, // .. anywhere
|
||||
/\.\.%/, // URL encoded traversal
|
||||
/\x00/, // null byte
|
||||
/[\x01-\x1f]/, // control characters
|
||||
]
|
||||
|
||||
if (
|
||||
suspiciousPatterns.some(
|
||||
(pattern) => pattern.test(cleanTarget) || pattern.test(cleanDecoded)
|
||||
)
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Allow ~/ at the start (home directory expansion within project) but reject ~/../ patterns.
|
||||
if (
|
||||
(targetPath.includes("~") || decodedPath.includes("~")) &&
|
||||
(targetPath.includes("../") || decodedPath.includes("../"))
|
||||
) {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check for Windows drive letters (even on non-Windows systems for safety).
|
||||
const driveLetterRegex = /^[a-zA-Z]:[\/\\]/
|
||||
if (driveLetterRegex.test(decodedPath)) {
|
||||
// On Windows, check if it starts with the project root.
|
||||
if (process.platform === "win32") {
|
||||
return decodedPath.toLowerCase().startsWith(cwd.toLowerCase())
|
||||
}
|
||||
// On non-Windows systems, reject all Windows absolute paths.
|
||||
return false
|
||||
}
|
||||
|
||||
// If it's an absolute path, ensure it's within the project root.
|
||||
if (path.isAbsolute(normalizedTarget)) {
|
||||
return normalizedTarget.startsWith(normalizedRoot + path.sep)
|
||||
}
|
||||
|
||||
// For relative paths, resolve and check if within project bounds.
|
||||
const resolvedPath = path.resolve(normalizedRoot, normalizedTarget)
|
||||
return (
|
||||
resolvedPath.startsWith(normalizedRoot + path.sep) ||
|
||||
resolvedPath === normalizedRoot
|
||||
)
|
||||
}
|
||||
@@ -51,7 +51,9 @@ export async function updateFiles(
|
||||
|
||||
const [projectInfo, baseColor] = await Promise.all([
|
||||
getProjectInfo(config.resolvedPaths.cwd),
|
||||
getRegistryBaseColor(config.tailwind.baseColor),
|
||||
config.tailwind.baseColor
|
||||
? getRegistryBaseColor(config.tailwind.baseColor)
|
||||
: Promise.resolve(undefined),
|
||||
])
|
||||
|
||||
let filesCreated: string[] = []
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
import path from "path"
|
||||
import { expect, test } from "vitest"
|
||||
import { describe, expect, test } from "vitest"
|
||||
|
||||
import { getConfig, getRawConfig } from "../../src/utils/get-config"
|
||||
import {
|
||||
createConfig,
|
||||
getConfig,
|
||||
getRawConfig,
|
||||
} from "../../src/utils/get-config"
|
||||
|
||||
test("get raw config", async () => {
|
||||
expect(
|
||||
@@ -183,3 +187,129 @@ test("get config", async () => {
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
describe("createConfig", () => {
|
||||
test("creates default config when called without arguments", () => {
|
||||
const config = createConfig()
|
||||
|
||||
expect(config).toMatchObject({
|
||||
resolvedPaths: {
|
||||
cwd: expect.any(String),
|
||||
tailwindConfig: "",
|
||||
tailwindCss: "",
|
||||
utils: "",
|
||||
components: "",
|
||||
ui: "",
|
||||
lib: "",
|
||||
hooks: "",
|
||||
},
|
||||
style: "",
|
||||
tailwind: {
|
||||
config: "",
|
||||
css: "",
|
||||
baseColor: "",
|
||||
cssVariables: false,
|
||||
},
|
||||
rsc: false,
|
||||
tsx: true,
|
||||
aliases: {
|
||||
components: "",
|
||||
utils: "",
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
test("overrides cwd in resolvedPaths", () => {
|
||||
const customCwd = "/custom/path"
|
||||
const config = createConfig({
|
||||
resolvedPaths: {
|
||||
cwd: customCwd,
|
||||
},
|
||||
})
|
||||
|
||||
expect(config.resolvedPaths.cwd).toBe(customCwd)
|
||||
expect(config.resolvedPaths.components).toBe("")
|
||||
expect(config.resolvedPaths.utils).toBe("")
|
||||
})
|
||||
|
||||
test("overrides style", () => {
|
||||
const config = createConfig({
|
||||
style: "new-york",
|
||||
})
|
||||
|
||||
expect(config.style).toBe("new-york")
|
||||
})
|
||||
|
||||
test("overrides tailwind settings", () => {
|
||||
const config = createConfig({
|
||||
tailwind: {
|
||||
baseColor: "slate",
|
||||
cssVariables: true,
|
||||
},
|
||||
})
|
||||
|
||||
expect(config.tailwind.baseColor).toBe("slate")
|
||||
expect(config.tailwind.cssVariables).toBe(true)
|
||||
expect(config.tailwind.config).toBe("")
|
||||
expect(config.tailwind.css).toBe("")
|
||||
})
|
||||
|
||||
test("overrides boolean flags", () => {
|
||||
const config = createConfig({
|
||||
rsc: true,
|
||||
tsx: false,
|
||||
})
|
||||
|
||||
expect(config.rsc).toBe(true)
|
||||
expect(config.tsx).toBe(false)
|
||||
})
|
||||
|
||||
test("overrides aliases", () => {
|
||||
const config = createConfig({
|
||||
aliases: {
|
||||
components: "@/components",
|
||||
utils: "@/lib/utils",
|
||||
},
|
||||
})
|
||||
|
||||
expect(config.aliases.components).toBe("@/components")
|
||||
expect(config.aliases.utils).toBe("@/lib/utils")
|
||||
})
|
||||
|
||||
test("handles complex partial overrides", () => {
|
||||
const config = createConfig({
|
||||
style: "default",
|
||||
resolvedPaths: {
|
||||
cwd: "/my/project",
|
||||
components: "/my/project/src/components",
|
||||
},
|
||||
tailwind: {
|
||||
baseColor: "zinc",
|
||||
prefix: "tw-",
|
||||
},
|
||||
aliases: {
|
||||
ui: "@/components/ui",
|
||||
},
|
||||
})
|
||||
|
||||
expect(config.style).toBe("default")
|
||||
expect(config.resolvedPaths.cwd).toBe("/my/project")
|
||||
expect(config.resolvedPaths.components).toBe("/my/project/src/components")
|
||||
expect(config.resolvedPaths.utils).toBe("")
|
||||
expect(config.tailwind.baseColor).toBe("zinc")
|
||||
expect(config.tailwind.prefix).toBe("tw-")
|
||||
expect(config.tailwind.css).toBe("")
|
||||
expect(config.aliases.ui).toBe("@/components/ui")
|
||||
expect(config.aliases.components).toBe("")
|
||||
})
|
||||
|
||||
test("returns new object instances", () => {
|
||||
const config1 = createConfig()
|
||||
const config2 = createConfig()
|
||||
|
||||
expect(config1).not.toBe(config2)
|
||||
expect(config1.resolvedPaths).not.toBe(config2.resolvedPaths)
|
||||
expect(config1.tailwind).not.toBe(config2.tailwind)
|
||||
expect(config1.aliases).not.toBe(config2.aliases)
|
||||
})
|
||||
})
|
||||
|
||||
47
pnpm-lock.yaml
generated
47
pnpm-lock.yaml
generated
@@ -132,6 +132,9 @@ importers:
|
||||
'@hookform/resolvers':
|
||||
specifier: ^3.10.0
|
||||
version: 3.10.0(react-hook-form@7.54.2(react@19.1.0))
|
||||
'@orama/orama':
|
||||
specifier: ^3.1.11
|
||||
version: 3.1.11
|
||||
'@radix-ui/react-accessible-icon':
|
||||
specifier: ^1.1.1
|
||||
version: 1.1.1(@types/react-dom@19.1.2(@types/react@19.1.2))(@types/react@19.1.2)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
@@ -294,6 +297,9 @@ importers:
|
||||
next-themes:
|
||||
specifier: 0.4.6
|
||||
version: 0.4.6(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
nuqs:
|
||||
specifier: ^2.4.3
|
||||
version: 2.4.3(next@15.3.1(@babel/core@7.26.7)(@opentelemetry/api@1.9.0)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(react@19.1.0)
|
||||
postcss:
|
||||
specifier: ^8.5.1
|
||||
version: 8.5.1
|
||||
@@ -322,7 +328,7 @@ importers:
|
||||
specifier: ^6.0.1
|
||||
version: 6.0.1
|
||||
shadcn:
|
||||
specifier: 2.8.0
|
||||
specifier: 2.9.0
|
||||
version: link:../../packages/shadcn
|
||||
shiki:
|
||||
specifier: ^1.10.1
|
||||
@@ -602,7 +608,7 @@ importers:
|
||||
specifier: 2.12.7
|
||||
version: 2.12.7(react-dom@18.3.1(react@18.3.1))(react@18.3.1)
|
||||
shadcn:
|
||||
specifier: 2.8.0
|
||||
specifier: 2.9.0
|
||||
version: link:../../packages/shadcn
|
||||
sharp:
|
||||
specifier: ^0.32.6
|
||||
@@ -2629,8 +2635,8 @@ packages:
|
||||
resolution: {integrity: sha512-lp4qAiMTD4sNWW4DbKLBkfiMZ4jbAboJIGOQr5DvciMRI494OapieI9qiODpOt0XBr1LjIDy1xAGAnVs5supTA==}
|
||||
engines: {node: '>=14'}
|
||||
|
||||
'@orama/orama@3.1.7':
|
||||
resolution: {integrity: sha512-6yB0117ZjsgNevZw3LP+bkrZa9mU/POPVaXgzMPOBbBc35w2P3R+1vMMhEfC06kYCpd5bf0jodBaTkYQW5TVeQ==}
|
||||
'@orama/orama@3.1.11':
|
||||
resolution: {integrity: sha512-Szki0cgFiXE5F9RLx2lUyEtJllnuCSQ4B8RLDwIjXkVit6qZjoDAxH+xhJs29MjKLDz0tbPLdKFa6QrQ/qoGGA==}
|
||||
engines: {node: '>= 20.0.0'}
|
||||
|
||||
'@oxc-transform/binding-darwin-arm64@0.53.0':
|
||||
@@ -7549,6 +7555,24 @@ packages:
|
||||
resolution: {integrity: sha512-tt6PvKu4WyzPwWUzy/hvPFqn+uwXO0K1ZHka8az3NnrhWJDmSqI8ncWq0fkL0k/lmmi5tAC11FXwXuh0rFbt1A==}
|
||||
engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0}
|
||||
|
||||
nuqs@2.4.3:
|
||||
resolution: {integrity: sha512-BgtlYpvRwLYiJuWzxt34q2bXu/AIS66sLU1QePIMr2LWkb+XH0vKXdbLSgn9t6p7QKzwI7f38rX3Wl9llTXQ8Q==}
|
||||
peerDependencies:
|
||||
'@remix-run/react': '>=2'
|
||||
next: '>=14.2.0'
|
||||
react: '>=18.2.0 || ^19.0.0-0'
|
||||
react-router: ^6 || ^7
|
||||
react-router-dom: ^6 || ^7
|
||||
peerDependenciesMeta:
|
||||
'@remix-run/react':
|
||||
optional: true
|
||||
next:
|
||||
optional: true
|
||||
react-router:
|
||||
optional: true
|
||||
react-router-dom:
|
||||
optional: true
|
||||
|
||||
object-assign@4.1.1:
|
||||
resolution: {integrity: sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==}
|
||||
engines: {node: '>=0.10.0'}
|
||||
@@ -10060,7 +10084,7 @@ snapshots:
|
||||
'@types/node': 20.5.1
|
||||
chalk: 4.1.2
|
||||
cosmiconfig: 8.3.6(typescript@5.7.3)
|
||||
cosmiconfig-typescript-loader: 4.4.0(@types/node@20.5.1)(cosmiconfig@8.3.6(typescript@5.7.3))(ts-node@10.9.2(@types/node@20.5.1)(typescript@5.7.3))(typescript@5.7.3)
|
||||
cosmiconfig-typescript-loader: 4.4.0(@types/node@20.5.1)(cosmiconfig@8.3.6(typescript@5.7.3))(ts-node@10.9.2(@types/node@20.17.16)(typescript@5.7.3))(typescript@5.7.3)
|
||||
lodash.isplainobject: 4.0.6
|
||||
lodash.merge: 4.6.2
|
||||
lodash.uniq: 4.5.0
|
||||
@@ -11437,7 +11461,7 @@ snapshots:
|
||||
|
||||
'@opentelemetry/semantic-conventions@1.28.0': {}
|
||||
|
||||
'@orama/orama@3.1.7': {}
|
||||
'@orama/orama@3.1.11': {}
|
||||
|
||||
'@oxc-transform/binding-darwin-arm64@0.53.0':
|
||||
optional: true
|
||||
@@ -14549,7 +14573,7 @@ snapshots:
|
||||
object-assign: 4.1.1
|
||||
vary: 1.1.2
|
||||
|
||||
cosmiconfig-typescript-loader@4.4.0(@types/node@20.5.1)(cosmiconfig@8.3.6(typescript@5.7.3))(ts-node@10.9.2(@types/node@20.5.1)(typescript@5.7.3))(typescript@5.7.3):
|
||||
cosmiconfig-typescript-loader@4.4.0(@types/node@20.5.1)(cosmiconfig@8.3.6(typescript@5.7.3))(ts-node@10.9.2(@types/node@20.17.16)(typescript@5.7.3))(typescript@5.7.3):
|
||||
dependencies:
|
||||
'@types/node': 20.5.1
|
||||
cosmiconfig: 8.3.6(typescript@5.7.3)
|
||||
@@ -15972,7 +15996,7 @@ snapshots:
|
||||
fumadocs-core@15.4.2(@types/react@19.1.2)(next@15.3.1(@babel/core@7.26.7)(@opentelemetry/api@1.9.0)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(react-dom@19.1.0(react@19.1.0))(react@19.1.0):
|
||||
dependencies:
|
||||
'@formatjs/intl-localematcher': 0.6.1
|
||||
'@orama/orama': 3.1.7
|
||||
'@orama/orama': 3.1.11
|
||||
'@shikijs/rehype': 3.4.2
|
||||
'@shikijs/transformers': 3.4.2
|
||||
github-slugger: 2.0.0
|
||||
@@ -18136,6 +18160,13 @@ snapshots:
|
||||
|
||||
npm-to-yarn@3.0.1: {}
|
||||
|
||||
nuqs@2.4.3(next@15.3.1(@babel/core@7.26.7)(@opentelemetry/api@1.9.0)(react-dom@19.1.0(react@19.1.0))(react@19.1.0))(react@19.1.0):
|
||||
dependencies:
|
||||
mitt: 3.0.1
|
||||
react: 19.1.0
|
||||
optionalDependencies:
|
||||
next: 15.3.1(@babel/core@7.26.7)(@opentelemetry/api@1.9.0)(react-dom@19.1.0(react@19.1.0))(react@19.1.0)
|
||||
|
||||
object-assign@4.1.1: {}
|
||||
|
||||
object-hash@3.0.0: {}
|
||||
|
||||
@@ -55,6 +55,10 @@
|
||||
"registry:build": {
|
||||
"cache": false,
|
||||
"outputs": []
|
||||
},
|
||||
"build:external": {
|
||||
"cache": false,
|
||||
"outputs": [".data/external-registries.json", ".data/external-registries-index.json"]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user