velyx 1.0.2 ā 1.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -11,7 +11,7 @@ document.addEventListener('alpine:init', () => {
|
|
|
11
11
|
});
|
|
12
12
|
`,R.writeFileSync(r,n,"utf8");}function qe(r){let e=r;for(let t=0;t<4;t+=1){let n=b.join(e,"colors");if(R.existsSync(n))return n;let o=b.join(e,"src/colors");if(R.existsSync(o))return o;let i=b.dirname(e);if(i===e)break;e=i;}return b.join(r,"colors")}var Be=process.argv[1]?b.dirname(b.resolve(process.argv[1])):process.cwd(),X=qe(Be);function we(){return R.existsSync(X)?R.readdirSync(X).filter(e=>e.endsWith(".json")).map(e=>{let t=b.join(X,e),n=R.readFileSync(t,"utf-8");return JSON.parse(n)}).filter(e=>!!e?.name).sort((e,t)=>e.name.localeCompare(t.name)):[]}function A(){return we()}function We(r){return we().find(e=>e.name===r)}function he(r){return Object.entries(r).map(([e,t])=>` --${e}: ${t};`)}function xe(r,e){let t=We(r);if(!t)throw new Error(`Theme "${r}" not found in colors registry.`);let n=he(t.cssVars.light),o=he(t.cssVars.dark),i=[":root {",...n,"}","",".dark {",...o,"}",""].join(`
|
|
13
13
|
`);R.writeFileSync(e,i,{encoding:"utf-8",flag:"wx"});}var m={error:red,warn:yellow,info:cyan,success:green};var s={error(...r){console.log(m.error(r.join(" ")));},warn(...r){console.log(m.warn(r.join(" ")));},info(...r){console.log(m.info(r.join(" ")));},success(...r){console.log(m.success(r.join(" ")));},log(...r){console.log(r.join(" "));},break(){console.log("");}};function ve(r){R.writeFileSync("velyx.json",JSON.stringify(r,null,2)+`
|
|
14
|
-
`,"utf8");}function be(){return R.existsSync("velyx.json")||(s.error("Velyx configuration not found."),process.exit(1)),JSON.parse(R.readFileSync("velyx.json","utf8"))}var P={version:"1.0.
|
|
14
|
+
`,"utf8");}function be(){return R.existsSync("velyx.json")||(s.error("Velyx configuration not found."),process.exit(1)),JSON.parse(R.readFileSync("velyx.json","utf8"))}var P={version:"1.0.3"};var L=class{constructor(e){this.fileSystem=e;}validateEnvironment(){if(!le())throw new Error("No Laravel project detected");let e=pe();if(!e||!me(e))throw new Error("Tailwind CSS v4 was not detected");let t=de(),n=D(),o=fe(),i=ge(),a=o?K(o.content):false;return {isLaravel:true,hasTailwindV4:true,hasAlpine:t,detectedPackageManager:n,cssFile:o,jsFile:i,canInjectCss:a}}displayEnvironmentInfo(e){e.hasAlpine?s.success("Alpine.js detected - components will be fully interactive"):(s.warn("Alpine.js not detected"),s.log(`Install Alpine.js: ${e.detectedPackageManager} install alpinejs`)),e.cssFile?e.canInjectCss||(s.warn("Tailwind import not found in CSS"),s.log("Velyx styles will not be auto-imported")):(s.warn("No main CSS file found"),s.log("Styles will be created but not auto-imported")),e.jsFile||(s.warn("No main JS file found"),s.log("Component scripts will not be auto-imported"));}async createComponentsDirectory(e="resources/views/components/ui"){await this.fileSystem.ensureDir(e);}async createThemeFile(e,t="resources/css/velyx.css"){let n=t.split("/").slice(0,-1).join("/");if(await this.fileSystem.ensureDir(n),R.existsSync(t))s.info("velyx.css already exists");else try{xe(e,t),s.success("Velyx theme created"),s.info(t);}catch(o){throw new Error(`Failed to create theme file: ${o.message}`)}}async injectStylesImport(e){ue(e),s.success("Velyx styles imported"),s.info(e);}async generateConfig(e,t){let n={version:P.version,theme:e.theme,packageManager:e.packageManager,css:{entry:t.cssFile?.path??"",velyx:"resources/css/velyx.css"},js:{entry:t.jsFile?.path??""},components:{path:"resources/views/components/ui"}};ve(n),s.success("velyx.json config generated");}displaySummary(e,t,n){console.log(`
|
|
15
15
|
---`),s.success("Laravel project detected"),s.success("Tailwind CSS v4 detected"),s.success(`Theme selected: ${e.theme}`),s.success(`Package manager: ${e.packageManager}`),s.success("UI components directory ready"),t.jsFile&&s.success("Main JS file detected"),s.success(n?"Styles import complete":"Styles import pending"),s.success("velyx.json created"),console.log(`
|
|
16
16
|
Next steps:`),console.log(" velyx add button"),console.log(`
|
|
17
17
|
\u{1F4A1} Want to customize your Tailwind palette? Try https://tweakcn.com/ \u2014 a visual generator for Tailwind-compatible color scales.`);}};var y={start(r){return Ze(r).start()},async withTask(r,e,t,n){let o=this.start(r);try{let i=await e();return t?o.succeed(t):o.stop(),i}catch(i){throw o.fail(n||"Operation failed"),i}}};var tt=promisify(exec);async function rt(r){try{let e=b.resolve(r,"composer.json"),t=b.resolve(r,"package.json");if(!w.existsSync(e))return null;let n=await w.readJson(e);if(!(n.require?.["laravel/framework"]||n.require?.["illuminate/foundation"]))return null;let i=process.cwd();process.chdir(r);let a=D();console.log(`Detected package manager: ${a}`),process.chdir(i);let l={name:n.name||b.basename(r),framework:{name:"laravel",label:"Laravel",version:n.require?.["laravel/framework"]||"unknown"},hasAlpine:!1,hasVite:!1,packageManager:a,paths:{views:"resources/views",assets:"resources/js",public:"public",config:"config"}};if(w.existsSync(t)){let g=await w.readJson(t);l.hasAlpine=!!(g.dependencies?.alpinejs||g.devDependencies?.alpinejs),l.hasVite=!!g.devDependencies?.vite;}let c=b.resolve(r,"resources/views"),d=b.resolve(r,"resources/js");return w.existsSync(c)&&(l.paths.views="resources/views"),w.existsSync(d)&&(l.paths.assets="resources/js"),l}catch{return null}}async function Ce(r){let e={};if(!w.existsSync(r.cwd))return e.MISSING_DIR=true,{errors:e,projectInfo:null};let t=y.start("Checking project environment..."),n=b.resolve(r.cwd,"velyx.json");if(w.existsSync(n)&&!r.force){t.fail(),s.break();let{action:l}=await Se({type:"select",name:"action",message:`A ${m.info("velyx.json")} file already exists. What would you like to do?`,choices:[{title:"Re-initialize Velyx configuration",value:"reinit"},{title:"Keep existing configuration",value:"keep"},{title:"Exit",value:"exit"}],initial:0});l==="exit"&&(s.log("Operation cancelled."),process.exit(0)),l==="keep"&&(s.log("Keeping existing configuration."),process.exit(0)),s.log("Re-initializing Velyx configuration...");}let o=await rt(r.cwd);(!o||o.framework.name!=="laravel")&&(e.UNSUPPORTED_PROJECT=true,t.fail(),s.break(),s.error(`We could not detect a supported Laravel project at ${m.info(r.cwd)}.
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/utils/file-helper.ts","../src/services/filesystem-service.ts","../src/utils/laravel.ts","../src/utils/tailwind.ts","../src/utils/requirements.ts","../src/utils/package-manager.ts","../src/utils/css.ts","../src/utils/js.ts","../src/utils/theme.ts","../src/utils/highlighter.ts","../src/utils/logger.ts","../src/utils/config.ts","../package.json","../src/services/init-service.ts","../src/utils/spinner.ts","../src/utils/preflight-init.ts","../src/utils/init-project.ts","../src/commands/init.ts","../src/errors/ErrorHandler.ts","../src/utils/errors.ts","../src/utils/handle-error.ts","../src/config/config-manager.ts","../src/services/dependency-service.ts","../src/services/component-service.ts","../src/services/add-service.ts","../src/errors/errors.ts","../src/services/http-service.ts","../src/utils/environment.ts","../src/services/velyx-registry-service.ts","../src/services/registry-service.ts","../src/utils/add-components.ts","../src/commands/add.ts","../src/utils/list-components.ts","../src/commands/list.ts","../src/index.ts"],"names":["FILE_BACKUP_SUFFIX","createFileBackup","filePath","fsExtra","backupPath","error","restoreFileBackup","deleteFileBackup","FilesystemService","fs","content","path","dirPath","isLaravelProject","readPackageJson","detectTailwindV4","pkg","deps","match","hasAlpineInPackageJson","hasInDeps","dep","hasInDevDeps","hasAlpineInLayouts","layoutDir","files","file","hasAlpineJs","detectPackageManager","CSS_CANDIDATES","findMainCss","rel","hasTailwindImport","css","injectVelyxImport","cssPath","JS_CANDIDATES","findMainJs","injectComponentJs","jsPath","componentName","componentImportPath","importStatement","lines","lastImportIndex","i","alpineDataRegistration","findColorsDir","startDir","current","depth","distPath","srcPath","parent","entryDir","COLORS_DIR","loadBaseColors","raw","color","a","b","getBaseColors","getBaseColor","name","renderCssVars","vars","key","value","copyTheme","theme","target","baseColor","lightVars","darkVars","highlighter","red","yellow","cyan","green","logger","args","writeVelyxConfig","config","readVelyxConfig","package_default","InitService","fileSystem","hasAlpine","detectedPm","js","canInject","validation","targetPath","options","stylesImported","spinner","message","ora","task","successMessage","failMessage","s","result","execAsync","promisify","exec","getProjectInfo","cwd","composerPath","packagePath","composer","originalDir","pkgManager","projectInfo","viewsPath","assetsPath","preFlightInit","errors","projectSpinner","velyxConfigPath","action","prompts","alpineSpinner","installAlpine","installSpinner","viteSpinner","initOptionsSchema","z","promptTheme","baseColors","promptStyleImport","shouldImport","resolveThemeFromOptions","matched","initProject","initService","packageManager","defaultTheme","code","init","Command","opts","VelyxError","context","ErrorHandler","RegistryErrorCode","RegistryError","handleError","ConfigManager","convertNpmToComposerFormat","DependencyService","dependencies","npmPromises","composerPromises","missingDeps","command","stdout","stderr","convertedDeps","installed","installedDeps","getFileTypeFromPath","ComponentService","registryService","configManager","componentNames","componentResult","component","plannedFiles","componentWithFiles","dest","fileType","existedBefore","jsComponents","jsComponent","jsEntry","importPath","tempFiles","backupTargets","tempPath","tempFile","AddService","componentService","registry","c","cause","NetworkError","ComponentNotFoundError","DEFAULT_RETRY_OPTIONS","sleep","ms","resolve","calculateDelay","attempt","initialDelay","backoffFactor","maxDelay","delay","isRetryableStatus","status","retryableStatusCodes","fetchWithTimeout","url","timeout","headers","controller","timeoutId","HttpService","retryOptions","lastError","response","getRegistryApiUrl","VelyxRegistryService","httpService","data","componentUrl","fileContent","visited","resolved","comp","depComponent","params","queryString","RegistryService","taskMessage","promptForRegistryComponents","availableComponents","components","addComponents","addService","available","err","addOptionsSchema","add","errorHandler","rawOptions","filterComponents","query","normalized","nameMatch","descriptionMatch","categoryMatch","category","sliceComponents","offset","limit","start","listComponents","sorted","filtered","sliced","chalk","table","Table","listOptionsSchema","list","displayIntro","program"],"mappings":"8UAEO,IAAMA,CAAAA,CAAqB,MAAA,CAE3B,SAASC,EAAAA,CAAiBC,CAAAA,CAAiC,CAChE,GAAI,CAACC,CAAAA,CAAQ,UAAA,CAAWD,CAAQ,CAAA,C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oBAAA,EAAkBvK,CAAAA,CAAY,OAAO,CAAA,CAAE,CAAC,CAAA,CACpE,OAAA,CAAQ,IAAIuK,CAAAA,CAAM,IAAA,CAAK,2CAA2C,CAAC,CAAA,CACnE,QAAQ,GAAA,CAAI,EAAE,EAChB,CAKA,IAAMM,EAAAA,CAAU,IAAIrH,OAAAA,CACpBqH,EAAAA,CACG,KAAK,OAAO,CAAA,CACZ,WAAA,CAAY,yDAAyD,EACrE,OAAA,CACC7K,CAAAA,CAAY,OAAW,CACvB,eAAA,CACA,4BACF,CAAA,CACC,IAAA,CAAK,WAAA,CAAa,IAAM,CACvB4K,EAAAA,GACF,CAAC,CAAA,CAEHC,EAAAA,CAAQ,WAAWxB,EAAG,CAAA,CAAE,UAAA,CAAW9F,EAAI,EAAE,UAAA,CAAWoH,EAAI,EAExDE,EAAAA,CAAQ,KAAA,CAAM,QAAQ,IAAI,CAAA","file":"index.js","sourcesContent":["import fsExtra from 'fs-extra'\n\nexport const FILE_BACKUP_SUFFIX = '.bak'\n\nexport function createFileBackup(filePath: string): string | null {\n if (!fsExtra.existsSync(filePath)) {\n return null\n }\n\n const backupPath = `${filePath}${FILE_BACKUP_SUFFIX}`\n try {\n fsExtra.renameSync(filePath, backupPath)\n return backupPath\n } catch (error) {\n console.error(`Failed to create backup of ${filePath}: ${error}`)\n return null\n }\n}\n\nexport function restoreFileBackup(filePath: string): boolean {\n const backupPath = `${filePath}${FILE_BACKUP_SUFFIX}`\n\n if (!fsExtra.existsSync(backupPath)) {\n return false\n }\n\n try {\n fsExtra.renameSync(backupPath, filePath)\n return true\n } catch (error) {\n console.error(\n `Warning: Could not restore backup file ${backupPath}: ${error}`,\n )\n return false\n }\n}\n\nexport function deleteFileBackup(filePath: string): boolean {\n const backupPath = `${filePath}${FILE_BACKUP_SUFFIX}`\n\n if (!fsExtra.existsSync(backupPath)) {\n return false\n }\n\n try {\n fsExtra.unlinkSync(backupPath)\n return true\n } catch {\n // Best effort - don't log as this is just cleanup\n return false\n }\n}\n","import { promises as fs } from 'fs'\nimport path from 'path'\nimport type { IFileSystemService } from '../types/interfaces'\n\n/**\n * Service for file system operations\n */\nexport class FilesystemService implements IFileSystemService {\n /**\n * Check if a file exists\n * @param filePath - Path to check\n * @returns Promise resolving to true if file exists\n */\n async fileExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath)\n return true\n } catch {\n return false\n }\n }\n\n /**\n * Write content to a file, creating directories if necessary\n * @param filePath - Path to write to\n * @param content - Content to write\n * @returns Promise that resolves when file is written\n * @throws Error if write fails\n */\n async writeFile(filePath: string, content: string): Promise<void> {\n await fs.mkdir(path.dirname(filePath), { recursive: true })\n await fs.writeFile(filePath, content, 'utf-8')\n }\n\n /**\n * Read content from a file\n * @param filePath - Path to read from\n * @returns Promise resolving to file content\n * @throws Error if file doesn't exist or read fails\n */\n async readFile(filePath: string): Promise<string> {\n return await fs.readFile(filePath, 'utf-8')\n }\n\n /**\n * Ensure a directory exists, creating it if necessary\n * @param dirPath - Directory path\n * @returns Promise that resolves when directory is ensured\n * @throws Error if directory creation fails\n */\n async ensureDir(dirPath: string): Promise<void> {\n await fs.mkdir(dirPath, { recursive: true })\n }\n}\n","import fs from 'fs'\n\n/**\n * Check if the current directory is a Laravel project\n * @returns True if Laravel project is detected\n */\nexport function isLaravelProject(): boolean {\n return fs.existsSync('composer.json') && fs.existsSync('artisan')\n}\n","import fs from 'fs'\n\n/**\n * Package.json structure\n */\ninterface PackageJson {\n dependencies?: Readonly<Record<string, string>>\n devDependencies?: Readonly<Record<string, string>>\n}\n\n/**\n * Read package.json file\n * @returns Package.json object or null if file doesn't exist or is invalid\n */\nexport function readPackageJson(): PackageJson | null {\n try {\n return JSON.parse(fs.readFileSync('package.json', 'utf8')) as PackageJson\n } catch {\n return null\n }\n}\n\n/**\n * Detect if Tailwind CSS v4 is installed\n * @param pkg - Package.json object\n * @returns True if Tailwind v4 is detected\n */\nexport function detectTailwindV4(pkg: PackageJson): boolean {\n const deps = { ...pkg.dependencies, ...pkg.devDependencies }\n if (deps['@tailwindcss/vite'] || deps['@tailwindcss/postcss']) {\n return true\n }\n if (deps['tailwindcss']) {\n const version = String(deps['tailwindcss'])\n const match = version.match(/(\\d+)/)\n return match ? Number(match[1]) >= 4 : false\n }\n return false\n}\n","import fs from 'fs'\nimport path from 'path'\n\n/**\n * Check if Alpine.js is listed in package.json dependencies\n * @returns True if Alpine.js is found in dependencies\n */\nexport function hasAlpineInPackageJson(): boolean {\n try {\n const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8')) as {\n dependencies?: Readonly<Record<string, string>>\n devDependencies?: Readonly<Record<string, string>>\n }\n const hasInDeps =\n pkg.dependencies &&\n Object.keys(pkg.dependencies).some((dep) =>\n dep.toLowerCase().includes('alpine'),\n )\n const hasInDevDeps =\n pkg.devDependencies &&\n Object.keys(pkg.devDependencies).some((dep) =>\n dep.toLowerCase().includes('alpine'),\n )\n return Boolean(hasInDeps || hasInDevDeps)\n } catch {\n return false\n }\n}\n\n/**\n * Check if Alpine.js is referenced in layout files\n * @returns True if Alpine.js is found in layout files\n */\nexport function hasAlpineInLayouts(): boolean {\n const layoutDir = 'resources/views/layouts'\n if (!fs.existsSync(layoutDir)) return false\n\n try {\n const files = fs.readdirSync(layoutDir, { recursive: true }) as string[]\n for (const file of files) {\n if (file.endsWith('.blade.php')) {\n const content = fs.readFileSync(path.join(layoutDir, file), 'utf8')\n if (content.toLowerCase().includes('alpine')) {\n return true\n }\n }\n }\n } catch {\n return false\n }\n return false\n}\n\n/**\n * Check if Alpine.js is available in the project\n * @returns True if Alpine.js is detected\n */\nexport function hasAlpineJs(): boolean {\n return hasAlpineInPackageJson() || hasAlpineInLayouts()\n}\n","import fs from 'fs'\nimport type { PackageManager } from '../types'\n\n/**\n * Detect the package manager used in the project\n * @returns Detected package manager name (defaults to \"npm\")\n */\nexport function detectPackageManager(): PackageManager {\n // Check lock files\n if (fs.existsSync('pnpm-lock.yaml') || fs.existsSync('pnpm-lock.yml')) {\n return 'pnpm'\n }\n if (fs.existsSync('yarn.lock')) {\n return 'yarn'\n }\n if (fs.existsSync('package-lock.json')) {\n return 'npm'\n }\n if (fs.existsSync('bun.lock')) {\n return 'bun'\n }\n\n // Default to npm\n return 'npm'\n}\n","import fs from 'fs'\nimport type { FileInfo } from '@/src/types'\n\n/**\n * Common CSS file paths to check for main stylesheet\n */\nexport const CSS_CANDIDATES = [\n 'resources/css/app.css',\n 'resources/css/app.scss',\n 'resources/css/main.css',\n 'resources/css/style.css',\n 'resources/css/styles.css',\n] as const\n\n/**\n * Find the main CSS file in the project\n * @returns CSS file info if found, null otherwise\n */\nexport function findMainCss(): FileInfo | null {\n for (const rel of CSS_CANDIDATES) {\n if (fs.existsSync(rel)) {\n return {\n path: rel,\n content: fs.readFileSync(rel, 'utf8'),\n }\n }\n }\n return null\n}\n\n/**\n * Check if CSS content has Tailwind import\n * @param css - CSS content to check\n * @returns True if Tailwind import is found\n */\nexport function hasTailwindImport(css: string): boolean {\n return /@import\\s+[\"']tailwindcss[\"']/.test(css)\n}\n\n/**\n * Inject Velyx CSS import into main CSS file\n * @param cssPath - Path to the CSS file\n * @throws Error if file read/write fails\n */\nexport function injectVelyxImport(cssPath: string): void {\n let content = fs.readFileSync(cssPath, 'utf8')\n if (content.includes('@import \"./velyx.css\"')) {\n return\n }\n if (hasTailwindImport(content)) {\n content = content.replace(\n /@import\\s+[\"']tailwindcss[\"'];?/,\n (match) => `${match}\\n@import \"./velyx.css\";`,\n )\n } else {\n content += '\\n@import \"./velyx.css\";\\n'\n }\n fs.writeFileSync(cssPath, content, 'utf8')\n}\n","import fs from 'fs'\nimport type { FileInfo } from '@/src/types'\n\n/**\n * Common JS file paths to check for main script\n */\nexport const JS_CANDIDATES = [\n 'resources/js/app.js',\n 'resources/js/main.js',\n 'resources/js/index.js',\n] as const\n\n/**\n * Find the main JS file in the project\n * @returns JS file info if found, null otherwise\n */\nexport function findMainJs(): FileInfo | null {\n for (const rel of JS_CANDIDATES) {\n if (fs.existsSync(rel)) {\n return {\n path: rel,\n content: fs.readFileSync(rel, 'utf8'),\n }\n }\n }\n return null\n}\n\n/**\n * Inject component JS import and Alpine initialization into main JS file\n * @param jsPath - Path to the JS file\n * @param componentName - Name of the component\n * @param componentImportPath - Path to import the component from\n * @throws Error if file read/write fails\n */\nexport function injectComponentJs(\n jsPath: string,\n componentName: string,\n componentImportPath: string,\n): void {\n let content = fs.readFileSync(jsPath, 'utf8')\n\n // Avoid duplicate imports\n const importStatement = `import ${componentName} from '${componentImportPath}'`\n if (\n content.includes(importStatement) ||\n content.includes(`import ${componentName} from \"${componentImportPath}\"`)\n ) {\n return\n }\n\n // Add import at the top (after other imports if possible)\n const lines = content.split('\\n')\n let lastImportIndex = -1\n for (let i = 0; i < lines.length; i++) {\n if (lines[i]?.startsWith('import ')) {\n lastImportIndex = i\n }\n }\n\n lines.splice(lastImportIndex + 1, 0, importStatement)\n content = lines.join('\\n')\n\n // Handle Alpine.data registration\n const alpineDataRegistration = `Alpine.data('${componentName}', ${componentName});`\n\n if (content.includes(\"document.addEventListener('alpine:init'\")) {\n // Inject into existing listener\n if (!content.includes(alpineDataRegistration)) {\n content = content.replace(\n /document\\.addEventListener\\('alpine:init',\\s*\\(\\)\\s*=>\\s*\\{/,\n (match) => `${match}\\n ${alpineDataRegistration}`,\n )\n }\n } else {\n // Create new listener at the end\n content += `\\n\\ndocument.addEventListener('alpine:init', () => {\\n ${alpineDataRegistration}\\n});\\n`\n }\n\n fs.writeFileSync(jsPath, content, 'utf8')\n}\n","import fs from 'fs'\nimport path from 'path'\nimport type { VelyxTheme } from '@/src/types'\n\ntype BaseColor = {\n name: VelyxTheme\n label: string\n cssVars: {\n light: Record<string, string>\n dark: Record<string, string>\n }\n}\n\nfunction findColorsDir(startDir: string): string {\n let current = startDir\n for (let depth = 0; depth < 4; depth += 1) {\n const distPath = path.join(current, 'colors')\n if (fs.existsSync(distPath)) {\n return distPath\n }\n\n const srcPath = path.join(current, 'src/colors')\n if (fs.existsSync(srcPath)) {\n return srcPath\n }\n\n const parent = path.dirname(current)\n if (parent === current) {\n break\n }\n current = parent\n }\n\n return path.join(startDir, 'colors')\n}\n\nconst entryDir = process.argv[1]\n ? path.dirname(path.resolve(process.argv[1]))\n : process.cwd()\nconst COLORS_DIR = findColorsDir(entryDir)\n\nfunction loadBaseColors(): BaseColor[] {\n if (!fs.existsSync(COLORS_DIR)) {\n return []\n }\n\n const files = fs\n .readdirSync(COLORS_DIR)\n .filter((file) => file.endsWith('.json'))\n\n return files\n .map((file) => {\n const filePath = path.join(COLORS_DIR, file)\n const raw = fs.readFileSync(filePath, 'utf-8')\n return JSON.parse(raw) as BaseColor\n })\n .filter((color) => !!color?.name)\n .sort((a, b) => a.name.localeCompare(b.name))\n}\n\nexport function getBaseColors(): BaseColor[] {\n return loadBaseColors()\n}\n\nexport function getBaseColor(name: VelyxTheme): BaseColor | undefined {\n return loadBaseColors().find((color) => color.name === name)\n}\n\nfunction renderCssVars(vars: Record<string, string>): string[] {\n return Object.entries(vars).map(([key, value]) => ` --${key}: ${value};`)\n}\n\n/**\n * Copy a theme CSS file to the target location\n * @param theme - Theme name to copy\n * @param target - Target file path\n * @throws Error if theme doesn't exist or copy fails\n */\nexport function copyTheme(theme: VelyxTheme, target: string): void {\n const baseColor = getBaseColor(theme)\n if (!baseColor) {\n throw new Error(`Theme \"${theme}\" not found in colors registry.`)\n }\n\n const lightVars = renderCssVars(baseColor.cssVars.light)\n const darkVars = renderCssVars(baseColor.cssVars.dark)\n\n const content = [\n ':root {',\n ...lightVars,\n '}',\n '',\n '.dark {',\n ...darkVars,\n '}',\n '',\n ].join('\\n')\n\n fs.writeFileSync(target, content, { encoding: 'utf-8', flag: 'wx' })\n}\n","import { cyan, green, red, yellow } from 'kleur/colors'\n\nexport const highlighter = {\n error: red,\n warn: yellow,\n info: cyan,\n success: green,\n}\n","import { highlighter } from '@/src/utils/highlighter'\n\nexport const logger = {\n error(...args: unknown[]) {\n console.log(highlighter.error(args.join(' ')))\n },\n warn(...args: unknown[]) {\n console.log(highlighter.warn(args.join(' ')))\n },\n info(...args: unknown[]) {\n console.log(highlighter.info(args.join(' ')))\n },\n success(...args: unknown[]) {\n console.log(highlighter.success(args.join(' ')))\n },\n log(...args: unknown[]) {\n console.log(args.join(' '))\n },\n break() {\n console.log('')\n },\n}\n","import fs from 'fs'\nimport type { VelyxConfig } from '../types'\nimport { logger } from './logger'\n\n/**\n * Write Velyx configuration to velyx.json file\n * @param config - Configuration object to write\n * @throws Error if file write fails\n */\nexport function writeVelyxConfig(config: VelyxConfig): void {\n fs.writeFileSync('velyx.json', JSON.stringify(config, null, 2) + '\\n', 'utf8')\n}\n\n/**\n * Read Velyx configuration from velyx.json file\n * @returns Configuration object\n * @throws Error if file doesn't exist or is invalid\n */\nexport function readVelyxConfig(): VelyxConfig {\n if (!fs.existsSync('velyx.json')) {\n logger.error('Velyx configuration not found.')\n process.exit(1)\n }\n return JSON.parse(fs.readFileSync('velyx.json', 'utf8')) as VelyxConfig\n}\n","{\n \"name\": \"velyx\",\n \"version\": \"1.0.2\",\n \"description\": \"CLI to add composable UI components to Laravel projects\",\n \"author\": \"\",\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=20\"\n },\n \"bin\": {\n \"velyx\": \"./dist/index.js\"\n },\n \"files\": [\n \"dist\"\n ],\n \"keywords\": [\n \"laravel\",\n \"cli\",\n \"ui\",\n \"blade\",\n \"tailwind\",\n \"alpine\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/velyx-labs/cli.git\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"packageManager\": \"pnpm@10.30.1+sha512.3590e550d5384caa39bd5c7c739f72270234b2f6059e13018f975c313b1eb9fefcc09714048765d4d9efe961382c312e624572c0420762bdc5d5940cdf9be73a\",\n \"pnpm\": {\n \"overrides\": {\n \"cli-spinners\": \"2.9.2\",\n \"velyx\": \"link:../../../../.local/share/pnpm/global/5/node_modules/velyx\"\n }\n },\n \"scripts\": {\n \"build:dev\": \"cross-env NODE_ENV=development VELYX_REGISTRY_URL=http://velyx.test/api/v1 tsup\",\n \"build\": \"cross-env NODE_ENV=production VELYX_REGISTRY_URL=https://registry.velyx.dev/api/v1 tsup\",\n \"check:ci\": \"pnpm run lint && pnpm run typecheck\",\n \"clean\": \"rimraf dist\",\n \"dev\": \"cross-env NODE_ENV=development VELYX_REGISTRY_URL=http://velyx.test/api/v1 tsup --watch\",\n \"check\": \"pnpm run format:write && eslint --fix\",\n \"format:check\": \"prettier --check \\\"**/*.{ts,tsx,mdx}\\\" --cache\",\n \"format:write\": \"prettier --write \\\"**/*.{ts,tsx,mdx}\\\" --cache\",\n \"lint\": \"eslint\",\n \"prepublishOnly\": \"pnpm run build\",\n \"pub:beta\": \"pnpm build && pnpm publish --no-git-checks --access public --tag beta\",\n \"pub:next\": \"pnpm build && pnpm publish --no-git-checks --access public --tag next\",\n \"pub:release\": \"pnpm build && pnpm publish --access public\",\n \"release\": \"changeset version\",\n \"start\": \"node dist/index.js\",\n \"start:dev\": \"cross-env NODE_ENV=development VELYX_REGISTRY_URL=http://velyx.test/api/v1 node dist/index.js\",\n \"test\": \"vitest run\",\n \"test:coverage\": \"vitest run --coverage\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc --noEmit\"\n },\n \"dependencies\": {\n \"@clack/prompts\": \"^0.11.0\",\n \"chalk\": \"^5.6.2\",\n \"cli-table3\": \"^0.6.5\",\n \"commander\": \"^14.0.2\",\n \"fs-extra\": \"^11.3.3\",\n \"kleur\": \"^4.1.5\",\n \"log-symbols\": \"^7.0.1\",\n \"ora\": \"^9.1.0\",\n \"prompts\": \"^2.4.2\",\n \"velyx\": \"link:../../../../.local/share/pnpm/global/5/node_modules/velyx\",\n \"vite-tsconfig-paths\": \"^6.0.5\",\n \"zod\": \"^3.24.1\",\n \"zod-to-json-schema\": \"^3.24.6\"\n },\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.29.8\",\n \"@eslint/js\": \"^9.39.2\",\n \"@eslint/json\": \"^0.14.0\",\n \"@eslint/markdown\": \"^7.5.1\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^25.0.9\",\n \"@types/prompts\": \"^2.4.9\",\n \"@vitest/coverage-v8\": \"^4.0.18\",\n \"cross-env\": \"^10.1.0\",\n \"eslint\": \"^9.39.2\",\n \"globals\": \"^17.0.0\",\n \"jiti\": \"^2.6.1\",\n \"prettier\": \"3.8.0\",\n \"rimraf\": \"^6.0.1\",\n \"tsc-alias\": \"^1.8.16\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^5.9.3\",\n \"typescript-eslint\": \"^8.53.0\",\n \"vitest\": \"^4.0.18\"\n }\n}\n","import type {\n VelyxConfig,\n PackageManager,\n VelyxTheme,\n FileInfo,\n} from '@/src/types'\nimport type { IFileSystemService } from '../types/interfaces'\nimport { isLaravelProject } from '../utils/laravel'\nimport { readPackageJson, detectTailwindV4 } from '../utils/tailwind'\nimport { hasAlpineJs } from '../utils/requirements'\nimport { detectPackageManager } from '../utils/package-manager'\nimport { findMainCss, hasTailwindImport, injectVelyxImport } from '../utils/css'\nimport { findMainJs } from '../utils/js'\nimport { copyTheme } from '../utils/theme'\nimport { writeVelyxConfig } from '../utils/config'\nimport fs from 'fs'\nimport { logger } from '../utils/logger'\nimport packageJson from '../../package.json'\n\n/**\n * Environment validation result\n */\nexport interface EnvironmentValidation {\n /** Whether Laravel project is detected */\n isLaravel: boolean\n /** Whether Tailwind v4 is detected */\n hasTailwindV4: boolean\n /** Whether Alpine.js is detected */\n hasAlpine: boolean\n /** Detected package manager */\n detectedPackageManager: PackageManager\n /** Main CSS file info if found */\n cssFile: FileInfo | null\n /** Main JS file info if found */\n jsFile: FileInfo | null\n /** Whether CSS can be injected */\n canInjectCss: boolean\n}\n\n/**\n * Initialization options\n */\nexport interface InitOptions {\n /** Selected package manager */\n packageManager: PackageManager\n /** Selected theme */\n theme: VelyxTheme\n /** Whether to import styles */\n importStyles: boolean\n}\n\n/**\n * Service for handling Velyx initialization\n */\nexport class InitService {\n /**\n * Create a new InitService instance\n * @param fileSystem - File system service\n */\n constructor(private readonly fileSystem: IFileSystemService) {}\n\n /**\n * Validate the project environment\n * @returns Environment validation result\n * @throws Error if critical requirements are not met\n */\n validateEnvironment(): EnvironmentValidation {\n // Validate Laravel project\n if (!isLaravelProject()) {\n throw new Error('No Laravel project detected')\n }\n\n // Check Tailwind v4\n const pkg = readPackageJson()\n if (!pkg || !detectTailwindV4(pkg)) {\n throw new Error('Tailwind CSS v4 was not detected')\n }\n\n // Check interactivity frameworks\n const hasAlpine = hasAlpineJs()\n const detectedPm = detectPackageManager()\n\n // Find CSS and JS files\n const css = findMainCss()\n const js = findMainJs()\n const canInject = css ? hasTailwindImport(css.content) : false\n\n return {\n isLaravel: true,\n hasTailwindV4: true,\n hasAlpine,\n detectedPackageManager: detectedPm,\n cssFile: css,\n jsFile: js,\n canInjectCss: canInject,\n }\n }\n\n /**\n * Display environment information and warnings\n * @param validation - Environment validation result\n */\n displayEnvironmentInfo(validation: EnvironmentValidation): void {\n // Display interactivity framework status\n if (!validation.hasAlpine) {\n logger.warn('Alpine.js not detected')\n logger.log(\n `Install Alpine.js: ${validation.detectedPackageManager} install alpinejs`,\n )\n } else {\n logger.success(\n 'Alpine.js detected - components will be fully interactive',\n )\n }\n\n // Display CSS file status\n if (!validation.cssFile) {\n logger.warn('No main CSS file found')\n logger.log('Styles will be created but not auto-imported')\n } else if (!validation.canInjectCss) {\n logger.warn('Tailwind import not found in CSS')\n logger.log('Velyx styles will not be auto-imported')\n }\n\n // Display JS file status\n if (!validation.jsFile) {\n logger.warn('No main JS file found')\n logger.log('Component scripts will not be auto-imported')\n }\n }\n\n /**\n * Create the UI components directory\n * @param path - Directory path (default: \"resources/views/components/ui\")\n * @returns Promise that resolves when directory is created\n */\n async createComponentsDirectory(\n path = 'resources/views/components/ui',\n ): Promise<void> {\n await this.fileSystem.ensureDir(path)\n }\n\n /**\n * Create the Velyx theme CSS file\n * @param theme - Theme to use\n * @param targetPath - Target CSS file path (default: \"resources/css/velyx.css\")\n * @returns Promise that resolves when theme is created\n * @throws Error if theme creation fails\n */\n async createThemeFile(\n theme: VelyxTheme,\n targetPath = 'resources/css/velyx.css',\n ): Promise<void> {\n // Ensure directory exists\n const dirPath = targetPath.split('/').slice(0, -1).join('/')\n await this.fileSystem.ensureDir(dirPath)\n\n // Create theme file if it doesn't exist\n if (!fs.existsSync(targetPath)) {\n try {\n copyTheme(theme, targetPath)\n logger.success('Velyx theme created')\n logger.info(targetPath)\n } catch (error) {\n throw new Error(\n `Failed to create theme file: ${(error as Error).message}`,\n )\n }\n } else {\n logger.info('velyx.css already exists')\n }\n }\n\n /**\n * Inject Velyx styles import into main CSS file\n * @param cssPath - Path to main CSS file\n * @returns Promise that resolves when import is injected\n */\n async injectStylesImport(cssPath: string): Promise<void> {\n injectVelyxImport(cssPath)\n logger.success('Velyx styles imported')\n logger.info(cssPath)\n }\n\n /**\n * Generate and write Velyx configuration file\n * @param options - Initialization options\n * @param validation - Environment validation result\n * @returns Promise that resolves when config is written\n */\n async generateConfig(\n options: InitOptions,\n validation: EnvironmentValidation,\n ): Promise<void> {\n const config: VelyxConfig = {\n version: packageJson.version as string,\n theme: options.theme,\n packageManager: options.packageManager,\n css: {\n entry: validation.cssFile?.path ?? '',\n velyx: 'resources/css/velyx.css',\n },\n js: {\n entry: validation.jsFile?.path ?? '',\n },\n components: {\n path: 'resources/views/components/ui',\n },\n }\n\n writeVelyxConfig(config)\n logger.success('velyx.json config generated')\n }\n\n /**\n * Display initialization summary\n * @param options - Initialization options\n * @param validation - Environment validation result\n * @param stylesImported - Whether styles were imported\n */\n displaySummary(\n options: InitOptions,\n validation: EnvironmentValidation,\n stylesImported: boolean,\n ): void {\n console.log('\\n---')\n logger.success('Laravel project detected')\n logger.success('Tailwind CSS v4 detected')\n logger.success(`Theme selected: ${options.theme}`)\n logger.success(`Package manager: ${options.packageManager}`)\n logger.success('UI components directory ready')\n if (validation.jsFile) {\n logger.success('Main JS file detected')\n }\n logger.success(\n stylesImported ? 'Styles import complete' : 'Styles import pending',\n )\n logger.success('velyx.json created')\n console.log('\\nNext steps:')\n console.log(' velyx add button')\n console.log(\n '\\nš” Want to customize your Tailwind palette? Try https://tweakcn.com/ ā a visual generator for Tailwind-compatible color scales.',\n )\n }\n}\n","import ora, { type Ora } from 'ora'\n\n/**\n * Utility to manage loading spinners\n */\nexport const spinner = {\n /**\n * Starts a spinner with a message\n * @param message - Message to display\n * @returns Ora spinner instance\n */\n start(message: string): Ora {\n return ora(message).start()\n },\n\n /**\n * Executes an asynchronous task with a spinner\n * @param message - Message during loading\n * @param task - Asynchronous function to execute\n * @param successMessage - Optional success message\n * @param failMessage - Optional error message\n * @returns Task result\n */\n async withTask<T>(\n message: string,\n task: () => Promise<T>,\n successMessage?: string,\n failMessage?: string,\n ): Promise<T> {\n const s = this.start(message)\n try {\n const result = await task()\n if (successMessage) {\n s.succeed(successMessage)\n } else {\n s.stop()\n }\n return result\n } catch (error) {\n s.fail(failMessage || 'Operation failed')\n throw error\n }\n },\n}\n","import { exec } from 'child_process'\nimport path from 'path'\nimport fs from 'fs-extra'\nimport { promisify } from 'util'\nimport { highlighter } from '@/src/utils/highlighter'\nimport { logger } from '@/src/utils/logger'\nimport { spinner } from '@/src/utils/spinner'\nimport prompts from 'prompts'\nimport { detectPackageManager } from '@/src/utils/package-manager'\nimport type { InitOptions } from '@/src/utils/init-project'\nimport type { PackageManager } from '@/src/types'\n\nconst execAsync = promisify(exec)\n\nexport interface ProjectInfo {\n name: string\n framework: {\n name: string\n label: string\n version?: string\n }\n hasAlpine: boolean\n hasVite: boolean\n packageManager: PackageManager\n paths: {\n views: string\n assets: string\n public: string\n config: string\n }\n}\n\nexport async function getProjectInfo(cwd: string): Promise<ProjectInfo | null> {\n try {\n const composerPath = path.resolve(cwd, 'composer.json')\n const packagePath = path.resolve(cwd, 'package.json')\n\n if (!fs.existsSync(composerPath)) {\n return null\n }\n\n const composer = await fs.readJson(composerPath)\n const isLaravel =\n composer.require?.['laravel/framework'] ||\n composer.require?.['illuminate/foundation']\n\n if (!isLaravel) {\n return null\n }\n\n // DĆ©tecter le package manager\n const originalDir = process.cwd()\n process.chdir(cwd)\n const pkgManager = detectPackageManager()\n console.log(`Detected package manager: ${pkgManager}`)\n process.chdir(originalDir)\n\n const projectInfo: ProjectInfo = {\n name: composer.name || path.basename(cwd),\n framework: {\n name: 'laravel',\n label: 'Laravel',\n version: composer.require?.['laravel/framework'] || 'unknown',\n },\n hasAlpine: false,\n hasVite: false,\n packageManager: pkgManager,\n paths: {\n views: 'resources/views',\n assets: 'resources/js',\n public: 'public',\n config: 'config',\n },\n }\n\n // VĆ©rifier les dĆ©pendances frontend\n if (fs.existsSync(packagePath)) {\n const pkg = await fs.readJson(packagePath)\n projectInfo.hasAlpine = !!(\n pkg.dependencies?.alpinejs || pkg.devDependencies?.alpinejs\n )\n projectInfo.hasVite = !!pkg.devDependencies?.vite\n }\n\n // VĆ©rifier la structure des dossiers\n const viewsPath = path.resolve(cwd, 'resources/views')\n const assetsPath = path.resolve(cwd, 'resources/js')\n\n if (fs.existsSync(viewsPath)) {\n projectInfo.paths.views = 'resources/views'\n }\n\n if (fs.existsSync(assetsPath)) {\n projectInfo.paths.assets = 'resources/js'\n }\n\n return projectInfo\n } catch {\n return null\n }\n}\n\nexport async function preFlightInit(options: InitOptions): Promise<{\n errors: Record<string, boolean>\n projectInfo: ProjectInfo | null\n}> {\n const errors: Record<string, boolean> = {}\n\n // VĆ©rifier si le rĆ©pertoire existe\n if (!fs.existsSync(options.cwd)) {\n errors['MISSING_DIR'] = true\n return { errors, projectInfo: null }\n }\n\n const projectSpinner = spinner.start('Checking project environment...')\n\n // VĆ©rifier si velyx.json existe dĆ©jĆ \n const velyxConfigPath = path.resolve(options.cwd, 'velyx.json')\n if (fs.existsSync(velyxConfigPath) && !options.force) {\n projectSpinner.fail()\n logger.break()\n\n const { action } = await prompts({\n type: 'select',\n name: 'action',\n message: `A ${highlighter.info('velyx.json')} file already exists. What would you like to do?`,\n choices: [\n {\n title: 'Re-initialize Velyx configuration',\n value: 'reinit',\n },\n {\n title: 'Keep existing configuration',\n value: 'keep',\n },\n {\n title: 'Exit',\n value: 'exit',\n },\n ],\n initial: 0,\n })\n\n if (action === 'exit') {\n logger.log('Operation cancelled.')\n process.exit(0)\n }\n\n if (action === 'keep') {\n logger.log('Keeping existing configuration.')\n process.exit(0)\n }\n\n // Continue with re-initialization\n logger.log(`Re-initializing Velyx configuration...`)\n }\n\n // RĆ©cupĆ©rer les infos du projet\n const projectInfo = await getProjectInfo(options.cwd)\n\n if (!projectInfo || projectInfo.framework.name !== 'laravel') {\n errors['UNSUPPORTED_PROJECT'] = true\n projectSpinner.fail()\n logger.break()\n logger.error(\n `We could not detect a supported Laravel project at ${highlighter.info(\n options.cwd,\n )}.\\nVelyx is designed to work with Laravel projects.`,\n )\n logger.break()\n process.exit(1)\n }\n\n projectSpinner.succeed(\n `Found ${highlighter.info(projectInfo.framework.label)} project`,\n )\n\n // VĆ©rifier Alpine.js\n const alpineSpinner = spinner.start('Checking Alpine.js...')\n\n if (!projectInfo.hasAlpine) {\n alpineSpinner.fail()\n logger.break()\n logger.warn(`Alpine.js is required but not found in your project.`)\n\n // Proposer d'installer Alpine.js directement\n const { installAlpine } = await prompts({\n type: 'confirm',\n name: 'installAlpine',\n message: 'Would you like to install Alpine.js now?',\n initial: true,\n })\n\n if (installAlpine) {\n // Installer Alpine.js avec le package manager dĆ©tectĆ©\n const pkgManager = projectInfo.packageManager\n const installSpinner = spinner.start(\n `Installing Alpine.js with ${pkgManager}...`,\n )\n\n try {\n await execAsync(`${pkgManager} install alpinejs`, {\n cwd: options.cwd,\n })\n installSpinner.succeed('Alpine.js installed successfully')\n projectInfo.hasAlpine = true\n } catch (error) {\n installSpinner.fail(\n `Failed to install Alpine.js: ${(error as Error).message}`,\n )\n logger.error(\n `Please install Alpine.js manually: ${highlighter.info(`${pkgManager} install alpinejs`)}`,\n )\n logger.break()\n process.exit(1)\n }\n } else {\n const pkgManager = projectInfo.packageManager\n logger.error(\n `Alpine.js is required. Install it with: ${highlighter.info(`${pkgManager} install alpinejs`)}`,\n )\n logger.break()\n process.exit(1)\n }\n } else {\n alpineSpinner.succeed('Alpine.js found')\n }\n\n // VĆ©rifier Vite (recommandĆ© pour Velyx)\n const viteSpinner = spinner.start('Checking build tools...')\n\n if (!projectInfo.hasVite) {\n logger.warn(\n `Vite not found. Using Vite is recommended for better development experience.`,\n )\n viteSpinner.warn('Vite not found (but optional)')\n } else {\n viteSpinner.succeed('Vite found')\n }\n\n // Afficher les erreurs bloquantes\n if (Object.keys(errors).length > 0) {\n logger.break()\n process.exit(1)\n }\n\n return { errors, projectInfo }\n}\n","import prompts from 'prompts'\nimport { FilesystemService } from '@/src/services/filesystem-service'\nimport { InitService } from '@/src/services/init-service'\nimport { preFlightInit, type ProjectInfo } from '@/src/utils/preflight-init'\nimport { getBaseColors } from '@/src/utils/theme'\nimport { logger } from '@/src/utils/logger'\nimport { highlighter } from '@/src/utils/highlighter'\nimport type { VelyxTheme } from '@/src/types'\nimport { z } from 'zod'\n\nexport const initOptionsSchema = z.object({\n baseColor: z.string().optional(),\n yes: z.boolean(),\n defaults: z.boolean(),\n force: z.boolean(),\n cwd: z.string(),\n silent: z.boolean(),\n})\n\nexport type InitOptions = z.infer<typeof initOptionsSchema>\n\nasync function promptTheme(): Promise<VelyxTheme> {\n const baseColors = getBaseColors()\n if (baseColors.length === 0) {\n logger.error('No base colors available.')\n process.exit(1)\n }\n const { theme } = await prompts(\n {\n type: 'select',\n name: 'theme',\n message: 'Choose a base color theme',\n choices: baseColors.map((color) => ({\n title: color.label,\n value: color.name,\n })),\n },\n {\n onCancel: () => {\n logger.error('Theme selection aborted')\n process.exit(1)\n },\n },\n )\n\n return theme as VelyxTheme\n}\n\nasync function promptStyleImport(): Promise<boolean> {\n const { shouldImport } = await prompts(\n {\n type: 'confirm',\n name: 'shouldImport',\n message: 'Import Velyx styles into your main CSS file?',\n initial: true,\n },\n {\n onCancel: () => false,\n },\n )\n\n return Boolean(shouldImport)\n}\n\nfunction resolveThemeFromOptions(options: InitOptions): VelyxTheme | undefined {\n if (!options.baseColor) {\n return undefined\n }\n\n const baseColors = getBaseColors()\n const matched = baseColors.find((color) => color.name === options.baseColor)\n if (matched) {\n return matched.name\n }\n\n logger.warn(`Unknown base color \"${options.baseColor}\".`)\n return undefined\n}\n\nexport async function initProject(\n options: InitOptions,\n projectInfo?: ProjectInfo | null,\n): Promise<void> {\n // Use provided projectInfo or run preflight checks\n if (!projectInfo) {\n const preflight = await preFlightInit(options)\n projectInfo = preflight.projectInfo\n }\n\n process.chdir(options.cwd)\n\n const fileSystem = new FilesystemService()\n const initService = new InitService(fileSystem)\n\n try {\n const validation = initService.validateEnvironment()\n initService.displayEnvironmentInfo(validation)\n\n // Use the package manager already detected in preflight checks\n const packageManager = projectInfo!.packageManager\n\n const baseColors = getBaseColors()\n const defaultTheme =\n baseColors.find((color) => color.name === 'neutral')?.name ??\n baseColors[0]?.name\n\n let theme = resolveThemeFromOptions(options)\n if (!theme) {\n theme =\n options.defaults && defaultTheme ? defaultTheme : await promptTheme()\n }\n\n if (!theme) {\n logger.error('No base color available.')\n process.exit(1)\n }\n\n await initService.createComponentsDirectory()\n await initService.createThemeFile(theme)\n\n let stylesImported = false\n if (validation.cssFile && validation.canInjectCss) {\n if (options.defaults || (await promptStyleImport())) {\n await initService.injectStylesImport(validation.cssFile.path)\n stylesImported = true\n }\n }\n\n await initService.generateConfig(\n {\n packageManager,\n theme,\n importStyles: stylesImported,\n },\n validation,\n )\n\n initService.displaySummary(\n {\n packageManager,\n theme,\n importStyles: stylesImported,\n },\n validation,\n stylesImported,\n )\n } catch (error) {\n logger.error((error as Error).message)\n if (error instanceof Error) {\n if (error.message.includes('Laravel project')) {\n logger.log('Run velyx init at the root of a Laravel project')\n } else if (error.message.includes('Tailwind')) {\n logger.log(`Velyx requires ${highlighter.info('Tailwind CSS v4+')}`)\n }\n }\n process.exit(1)\n }\n}\n","import { Command } from 'commander'\nimport path from 'path'\nimport { deleteFileBackup, restoreFileBackup } from '@/src/utils/file-helper'\nimport { initOptionsSchema, initProject } from '@/src/utils/init-project'\n\nprocess.on('exit', (code) => {\n const filePath = path.resolve(process.cwd(), 'velyx.json')\n\n // Delete backup if successful.\n if (code === 0) {\n return deleteFileBackup(filePath)\n }\n\n // Restore backup if error.\n return restoreFileBackup(filePath)\n})\n\nexport const init = new Command()\n .name('init')\n .description('initialize your project and install dependencies')\n .option(\n '-b, --base-color <base-color>',\n 'the base color to use. (neutral, gray, zinc, stone, slate)',\n undefined,\n )\n .option('-y, --yes', 'skip confirmation prompt.', true)\n .option('-d, --defaults', 'use default configuration.', false)\n .option('-f, --force', 'force overwrite of existing configuration.', false)\n .option(\n '-c, --cwd <cwd>',\n 'the working directory. defaults to the current directory.',\n process.cwd(),\n )\n .option('-s, --silent', 'mute output.', false)\n .action(async (opts) => {\n const options = initOptionsSchema.parse({\n baseColor: opts.baseColor,\n yes: Boolean(opts.yes),\n defaults: Boolean(opts.defaults),\n force: Boolean(opts.force),\n cwd: path.resolve(opts.cwd),\n silent: Boolean(opts.silent),\n })\n\n await initProject(options)\n })\n","/**\n * Custom error class for Velyx-specific errors with code and context\n */\nexport class VelyxError extends Error {\n /**\n * Create a new VelyxError\n * @param message - Error message\n * @param code - Error code for categorization\n * @param context - Additional context data\n */\n constructor(\n message: string,\n public readonly code: string,\n public readonly context?: Readonly<Record<string, unknown>>,\n ) {\n super(message)\n this.name = 'VelyxError'\n }\n}\n\n/**\n * Handles and formats errors for display\n */\nexport class ErrorHandler {\n /**\n * Handle an error and display it appropriately\n * @param error - Error to handle\n * @param context - Context where the error occurred\n */\n handle(error: Error, context: string): void {\n if (error instanceof VelyxError) {\n console.error(`[${error.code}] ${error.message}`)\n if (error.context) {\n console.error('Context:', error.context)\n }\n } else {\n console.error(`Unexpected error in ${context}: ${error.message}`)\n }\n\n // Don't exit here, let the caller handle it\n }\n}\n","import { z } from 'zod'\n\n// Error codes for programmatic error handling\nexport const RegistryErrorCode = {\n // Network errors\n NETWORK_ERROR: 'NETWORK_ERROR',\n NOT_FOUND: 'NOT_FOUND',\n UNAUTHORIZED: 'UNAUTHORIZED',\n FORBIDDEN: 'FORBIDDEN',\n FETCH_ERROR: 'FETCH_ERROR',\n\n // Configuration errors\n NOT_CONFIGURED: 'NOT_CONFIGURED',\n INVALID_CONFIG: 'INVALID_CONFIG',\n MISSING_ENV_VARS: 'MISSING_ENV_VARS',\n\n // File system errors\n LOCAL_FILE_ERROR: 'LOCAL_FILE_ERROR',\n\n // Parsing errors\n PARSE_ERROR: 'PARSE_ERROR',\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n\n // Generic errors\n UNKNOWN_ERROR: 'UNKNOWN_ERROR',\n} as const\n\nexport type RegistryErrorCode =\n (typeof RegistryErrorCode)[keyof typeof RegistryErrorCode]\n\nexport class RegistryError extends Error {\n public readonly code: RegistryErrorCode\n public readonly statusCode?: number\n public readonly context?: Record<string, unknown>\n public readonly suggestion?: string\n public readonly timestamp: Date\n public readonly cause?: unknown\n\n constructor(\n message: string,\n options: {\n code?: RegistryErrorCode\n statusCode?: number\n cause?: unknown\n context?: Record<string, unknown>\n suggestion?: string\n } = {},\n ) {\n super(message)\n this.name = 'RegistryError'\n this.code = options.code || RegistryErrorCode.UNKNOWN_ERROR\n this.statusCode = options.statusCode\n this.cause = options.cause\n this.context = options.context\n this.suggestion = options.suggestion\n this.timestamp = new Date()\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n statusCode: this.statusCode,\n context: this.context,\n suggestion: this.suggestion,\n timestamp: this.timestamp,\n stack: this.stack,\n }\n }\n}\n\nexport class RegistryNotFoundError extends RegistryError {\n constructor(\n public readonly url: string,\n cause?: unknown,\n ) {\n const message = `The item at ${url} was not found. It may not exist at the registry.`\n\n super(message, {\n code: RegistryErrorCode.NOT_FOUND,\n statusCode: 404,\n cause,\n context: { url },\n suggestion:\n 'Check if the item name is correct and the registry URL is accessible.',\n })\n this.name = 'RegistryNotFoundError'\n }\n}\n\nexport class RegistryUnauthorizedError extends RegistryError {\n constructor(\n public readonly url: string,\n cause?: unknown,\n ) {\n const message = `You are not authorized to access the item at ${url}. If this is a remote registry, you may need to authenticate.`\n\n super(message, {\n code: RegistryErrorCode.UNAUTHORIZED,\n statusCode: 401,\n cause,\n context: { url },\n suggestion:\n 'Check your authentication credentials and environment variables.',\n })\n this.name = 'RegistryUnauthorizedError'\n }\n}\n\nexport class RegistryForbiddenError extends RegistryError {\n constructor(\n public readonly url: string,\n cause?: unknown,\n ) {\n const message = `You are not authorized to access the item at ${url}. If this is a remote registry, you may need to authenticate.`\n\n super(message, {\n code: RegistryErrorCode.FORBIDDEN,\n statusCode: 403,\n cause,\n context: { url },\n suggestion:\n 'Check your authentication credentials and environment variables.',\n })\n this.name = 'RegistryForbiddenError'\n }\n}\n\nexport class RegistryFetchError extends RegistryError {\n constructor(\n public readonly url: string,\n statusCode?: number,\n public readonly responseBody?: string,\n cause?: unknown,\n ) {\n // Use the error detail from the server if available\n const baseMessage = statusCode\n ? `Failed to fetch from registry (${statusCode}): ${url}`\n : `Failed to fetch from registry: ${url}`\n\n const message =\n typeof cause === 'string' && cause\n ? `${baseMessage} - ${cause}`\n : baseMessage\n\n let suggestion = 'Check your network connection and try again.'\n if (statusCode === 404) {\n suggestion =\n 'The requested resource was not found. Check the URL or item name.'\n } else if (statusCode === 500) {\n suggestion = 'The registry server encountered an error. Try again later.'\n } else if (statusCode && statusCode >= 400 && statusCode < 500) {\n suggestion = 'There was a client error. Check your request parameters.'\n }\n\n super(message, {\n code: RegistryErrorCode.FETCH_ERROR,\n statusCode,\n cause,\n context: { url, responseBody },\n suggestion,\n })\n this.name = 'RegistryFetchError'\n }\n}\n\nexport class RegistryNotConfiguredError extends RegistryError {\n constructor(public readonly registryName: string | null) {\n const message = registryName\n ? `Unknown registry \"${registryName}\". Make sure it is defined in components.json as follows:\n{\n \"registries\": {\n \"${registryName}\": \"[URL_TO_REGISTRY]\"\n }\n}`\n : `Unknown registry. Make sure it is defined in components.json under \"registries\".`\n\n super(message, {\n code: RegistryErrorCode.NOT_CONFIGURED,\n context: { registryName },\n suggestion:\n 'Add the registry configuration to your components.json file. Consult the registry documentation for the correct format.',\n })\n this.name = 'RegistryNotConfiguredError'\n }\n}\n\nexport class RegistryLocalFileError extends RegistryError {\n constructor(\n public readonly filePath: string,\n cause?: unknown,\n ) {\n super(`Failed to read local registry file: ${filePath}`, {\n code: RegistryErrorCode.LOCAL_FILE_ERROR,\n cause,\n context: { filePath },\n suggestion: 'Check if the file exists and you have read permissions.',\n })\n this.name = 'RegistryLocalFileError'\n }\n}\n\nexport class RegistryParseError extends RegistryError {\n public readonly parseError: unknown\n\n constructor(\n public readonly item: string,\n parseError: unknown,\n ) {\n let message = `Failed to parse registry item: ${item}`\n\n if (parseError instanceof z.ZodError) {\n message = `Failed to parse registry item: ${item}\\n${parseError.errors\n .map((e) => ` - ${e.path.join('.')}: ${e.message}`)\n .join('\\n')}`\n }\n\n super(message, {\n code: RegistryErrorCode.PARSE_ERROR,\n cause: parseError,\n context: { item },\n suggestion:\n 'The registry item may be corrupted or have an invalid format. Please make sure it returns a valid JSON object. See https://ui.shadcn.com/schema/registry-item.json.',\n })\n\n this.parseError = parseError\n this.name = 'RegistryParseError'\n }\n}\n\nexport class RegistryMissingEnvironmentVariablesError extends RegistryError {\n constructor(\n public readonly registryName: string,\n public readonly missingVars: string[],\n ) {\n const message =\n `Registry \"${registryName}\" requires the following environment variables:\\n\\n` +\n missingVars.map((v) => ` ⢠${v}`).join('\\n')\n\n super(message, {\n code: RegistryErrorCode.MISSING_ENV_VARS,\n context: { registryName, missingVars },\n suggestion:\n 'Set the required environment variables to your .env or .env.local file.',\n })\n this.name = 'RegistryMissingEnvironmentVariablesError'\n }\n}\n\nexport class RegistryInvalidNamespaceError extends RegistryError {\n constructor(public readonly name: string) {\n const message = `Invalid registry namespace: \"${name}\". Registry names must start with @ (e.g., @shadcn, @v0).`\n\n super(message, {\n code: RegistryErrorCode.VALIDATION_ERROR,\n context: { name },\n suggestion:\n 'Use a valid registry name starting with @ or provide a direct URL to the registry.',\n })\n this.name = 'RegistryInvalidNamespaceError'\n }\n}\n\nexport class ConfigMissingError extends RegistryError {\n constructor(public readonly cwd: string) {\n const message = `No components.json found in ${cwd} or parent directories.`\n\n super(message, {\n code: RegistryErrorCode.NOT_CONFIGURED,\n context: { cwd },\n suggestion:\n \"Run 'npx shadcn@latest init' to create a components.json file, or check that you're in the correct directory.\",\n })\n this.name = 'ConfigMissingError'\n }\n}\n\nexport class ConfigParseError extends RegistryError {\n constructor(\n public readonly cwd: string,\n parseError: unknown,\n ) {\n let message = `Invalid components.json configuration in ${cwd}.`\n\n if (parseError instanceof z.ZodError) {\n message = `Invalid components.json configuration in ${cwd}:\\n${parseError.errors\n .map((e) => ` - ${e.path.join('.')}: ${e.message}`)\n .join('\\n')}`\n }\n\n super(message, {\n code: RegistryErrorCode.INVALID_CONFIG,\n cause: parseError,\n context: { cwd },\n suggestion:\n \"Check your components.json file for syntax errors or invalid configuration. Run 'npx shadcn@latest init' to regenerate a valid configuration.\",\n })\n this.name = 'ConfigParseError'\n }\n}\n\nexport class RegistriesIndexParseError extends RegistryError {\n public readonly parseError: unknown\n\n constructor(parseError: unknown) {\n let message = 'Failed to parse registries index'\n\n if (parseError instanceof z.ZodError) {\n const invalidNamespaces = parseError.errors\n .filter((e) => e.path.length > 0)\n .map((e) => `\"${e.path[0]}\"`)\n .filter((v, i, arr) => arr.indexOf(v) === i) // remove duplicates\n\n if (invalidNamespaces.length > 0) {\n message = `Failed to parse registries index. Invalid registry namespace(s): ${invalidNamespaces.join(\n ', ',\n )}\\n${parseError.errors\n .map((e) => ` - ${e.path.join('.')}: ${e.message}`)\n .join('\\n')}`\n } else {\n message = `Failed to parse registries index:\\n${parseError.errors\n .map((e) => ` - ${e.path.join('.')}: ${e.message}`)\n .join('\\n')}`\n }\n }\n\n super(message, {\n code: RegistryErrorCode.PARSE_ERROR,\n cause: parseError,\n context: { parseError },\n suggestion:\n 'The registries index may be corrupted or have invalid registry namespace format. Registry names must start with @ (e.g., @shadcn, @example).',\n })\n\n this.parseError = parseError\n this.name = 'RegistriesIndexParseError'\n }\n}\n\nexport class InvalidConfigIconLibraryError extends RegistryError {\n constructor(\n public readonly iconLibrary: string,\n public readonly validOptions: string[],\n ) {\n const message = `Invalid icon library \"${iconLibrary}\". Valid options are: ${validOptions.join(\n ', ',\n )}`\n\n super(message, {\n code: RegistryErrorCode.INVALID_CONFIG,\n context: { iconLibrary, validOptions },\n suggestion: `Update the \"iconLibrary\" field in your components.json to one of: ${validOptions.join(\n ', ',\n )}`,\n })\n this.name = 'InvalidConfigIconLibraryError'\n }\n}\n\nexport const MISSING_DIR_OR_EMPTY_PROJECT = '1'\nexport const EXISTING_CONFIG = '2'\nexport const MISSING_CONFIG = '3'\nexport const FAILED_CONFIG_READ = '4'\nexport const TAILWIND_NOT_CONFIGURED = '5'\nexport const IMPORT_ALIAS_MISSING = '6'\nexport const UNSUPPORTED_FRAMEWORK = '7'\nexport const COMPONENT_URL_NOT_FOUND = '8'\nexport const COMPONENT_URL_UNAUTHORIZED = '9'\nexport const COMPONENT_URL_FORBIDDEN = '10'\nexport const COMPONENT_URL_BAD_REQUEST = '11'\nexport const COMPONENT_URL_INTERNAL_SERVER_ERROR = '12'\nexport const BUILD_MISSING_REGISTRY_FILE = '13'\nexport const INVALID_CONFIG_ICON_LIBRARY = '14'\n","import { RegistryError } from '@/src/utils/errors'\nimport { highlighter } from '@/src/utils/highlighter'\nimport { logger } from '@/src/utils/logger'\nimport { z } from 'zod'\n\nexport function handleError(error: unknown): void {\n logger.break()\n logger.error(\n `Something went wrong. Please check the error below for more details.`,\n )\n logger.error(`If the problem persists, please open an issue on GitHub.`)\n logger.error('')\n if (typeof error === 'string') {\n logger.error(error)\n logger.break()\n process.exit(1)\n }\n\n if (error instanceof RegistryError) {\n if (error.message) {\n logger.error(error.cause ? 'Error:' : 'Message:')\n logger.error(error.message)\n }\n\n if (error.cause) {\n logger.error('\\nMessage:')\n logger.error(error.cause)\n }\n\n if (error.suggestion) {\n logger.error('\\nSuggestion:')\n logger.error(error.suggestion)\n }\n logger.break()\n process.exit(1)\n }\n\n if (error instanceof z.ZodError) {\n logger.error('Validation failed:')\n for (const [key, value] of Object.entries(error.flatten().fieldErrors)) {\n logger.error(`- ${highlighter.info(key)}: ${value}`)\n }\n logger.break()\n process.exit(1)\n }\n\n if (error instanceof Error) {\n logger.error(error.message)\n logger.break()\n process.exit(1)\n }\n\n logger.break()\n process.exit(1)\n}\n","import type { VelyxConfig, PackageManager, VelyxTheme } from '@/src/types'\nimport type { IConfigManager } from '@/src/types/interfaces'\nimport { readVelyxConfig } from '@/src/utils/config'\nimport { logger } from '@/src/utils/logger'\nimport { handleError } from '@/src/utils/handle-error'\n\n/**\n * Manages Velyx configuration loading and access\n */\nexport class ConfigManager implements IConfigManager {\n private config?: VelyxConfig\n\n /**\n * Load configuration from file\n * @returns Promise resolving to configuration\n * @throws Error if configuration not found or invalid\n */\n async load(): Promise<VelyxConfig> {\n try {\n this.config = readVelyxConfig()\n if (!this.config) {\n logger.error('')\n handleError(new Error('Configuration not found'))\n process.exit(1)\n }\n return this.config\n } catch {\n logger.error('')\n handleError(new Error('Something went wrong. Please try again.'))\n process.exit(1)\n }\n }\n\n /**\n * Get the package manager from config\n * @returns Package manager name\n * @throws Error if config not loaded\n */\n getPackageManager(): PackageManager {\n if (!this.config) {\n throw new Error('Configuration not loaded')\n }\n return (this.config.packageManager || 'npm') as PackageManager\n }\n\n /**\n * Validate that configuration is loaded\n * @returns True if configuration is valid\n */\n validate(): boolean {\n return !!this.config\n }\n\n /**\n * Get the components path from config\n * @returns Components directory path\n * @throws Error if config not loaded\n */\n getComponentsPath(): string {\n if (!this.config) {\n throw new Error('Configuration not loaded')\n }\n return this.config.components.path\n }\n\n /**\n * Get the theme CSS path from config\n * @returns Theme CSS file path\n * @throws Error if config not loaded\n */\n getThemePath(): string {\n if (!this.config) {\n throw new Error('Configuration not loaded')\n }\n return this.config.css.velyx\n }\n\n /**\n * Get the JS entry path from config\n * @returns JS entry file path\n * @throws Error if config not loaded\n */\n getJsEntryPath(): string {\n if (!this.config) {\n throw new Error('Configuration not loaded')\n }\n return this.config.js?.entry ?? ''\n }\n\n /**\n * Get the selected theme from config\n * @returns Theme name\n * @throws Error if config not loaded\n */\n getTheme(): VelyxTheme {\n if (!this.config) {\n throw new Error('Configuration not loaded')\n }\n return this.config.theme as VelyxTheme\n }\n}\n","import { exec } from 'child_process'\nimport { promisify } from 'util'\nimport type { PackageManager, VelyxDependency } from '@/src/types'\nimport type { IDependencyService } from '@/src/types/interfaces'\nimport { logger } from '@/src/utils/logger'\nimport { FilesystemService } from './filesystem-service'\n\nconst execAsync = promisify(exec)\n\n/**\n * Convert npm-style dependency string to Composer format\n * @param dep - Dependency string in npm format (e.g., \"vendor/package@1.0.0\")\n * @returns Dependency string in Composer format (e.g., \"vendor/package:1.0.0\")\n */\nfunction convertNpmToComposerFormat(dep: string): string {\n // Replace @ with : for version constraint\n // But only if it's not a scoped package (starting with @)\n if (dep.startsWith('@')) {\n // Scoped npm package like @alpinejs/alpinejs - return as-is for npm\n return dep\n }\n // Replace @ with : for Composer packages\n return dep.replace('@', ':')\n}\n\n/**\n * Service for managing dependency installation\n */\nexport class DependencyService implements IDependencyService {\n private readonly fileSystem: FilesystemService\n\n constructor(fileSystem?: FilesystemService) {\n this.fileSystem = fileSystem ?? new FilesystemService()\n }\n\n /**\n * Install component dependencies using appropriate package managers\n * @param dependencies - Dependencies to install\n * @param packageManager - Package manager to use for npm dependencies\n * @returns Promise that resolves when installation is complete\n */\n async installDependencies(\n dependencies: VelyxDependency,\n packageManager: PackageManager,\n ): Promise<void> {\n const npmPromises = []\n const composerPromises = []\n\n // Install npm dependencies\n if (dependencies.npm && dependencies.npm.length > 0) {\n npmPromises.push(\n this.installNpmDependencies(dependencies.npm, packageManager),\n )\n }\n\n // Install composer dependencies\n if (dependencies.composer && dependencies.composer.length > 0) {\n composerPromises.push(\n this.installComposerDependencies(dependencies.composer),\n )\n }\n\n // Execute installations in parallel\n await Promise.allSettled([...npmPromises, ...composerPromises])\n }\n\n /**\n * Install npm/yarn/pnpm/bun dependencies\n * @param dependencies - Array of dependency strings (e.g., \"alpinejs@^3.14.0\")\n * @param packageManager - Package manager to use\n * @returns Promise that resolves when installation is complete\n */\n async installNpmDependencies(\n dependencies: readonly string[],\n packageManager: PackageManager,\n ): Promise<void> {\n if (!this.fileSystem.fileExists('package.json')) {\n logger.warn('No package.json found, skipping npm dependencies')\n return\n }\n\n const missingDeps = await this.filterMissingNpmDependencies(dependencies)\n\n if (missingDeps.length === 0) {\n logger.info('All npm dependencies already installed')\n return\n }\n\n const command = this.getNpmInstallCommand(packageManager, missingDeps)\n\n try {\n logger.info(`Installing npm dependencies: ${missingDeps.join(', ')}`)\n\n const { stdout, stderr } = await execAsync(command, {\n cwd: process.cwd(),\n timeout: 120000, // 2 minutes timeout\n })\n\n if (stdout && process.env.NODE_ENV !== 'test') {\n console.log(stdout)\n }\n\n if (stderr && !stderr.includes('WARN')) {\n logger.warn(`npm install warnings: ${stderr}`)\n }\n\n logger.success(`Installed ${missingDeps.length} npm dependencies`)\n } catch (error) {\n logger.error(\n `Failed to install npm dependencies: ${(error as Error).message}`,\n )\n throw error\n }\n }\n\n /**\n * Install composer dependencies\n * @param dependencies - Array of dependency strings (e.g., \"livewire/livewire:^3.0\" or \"livewire/livewire@^3.0\")\n * @returns Promise that resolves when installation is complete\n */\n async installComposerDependencies(\n dependencies: readonly string[],\n ): Promise<void> {\n if (!this.fileSystem.fileExists('composer.json')) {\n logger.warn('No composer.json found, skipping composer dependencies')\n return\n }\n\n // Convert npm format (@) to Composer format (:) if needed\n const convertedDeps = dependencies.map(convertNpmToComposerFormat)\n\n const missingDeps =\n await this.filterMissingComposerDependencies(convertedDeps)\n\n if (missingDeps.length === 0) {\n logger.info('All composer dependencies already installed')\n return\n }\n\n try {\n logger.info(`Installing composer dependencies: ${missingDeps.join(', ')}`)\n\n const { stdout, stderr } = await execAsync(\n `composer require ${missingDeps.join(' ')}`,\n {\n cwd: process.cwd(),\n timeout: 300000, // 5 minutes timeout for composer\n },\n )\n\n if (stdout && process.env.NODE_ENV !== 'test') {\n console.log(stdout)\n }\n\n if (stderr) {\n logger.warn(`composer require warnings: ${stderr}`)\n }\n\n logger.success(`Installed ${missingDeps.length} composer dependencies`)\n } catch (error) {\n logger.error(\n `Failed to install composer dependencies: ${(error as Error).message}`,\n )\n throw error\n }\n }\n\n /**\n * Get the appropriate npm install command based on package manager\n * @param packageManager - Package manager to use\n * @param dependencies - Dependencies array\n * @returns Command string\n */\n private getNpmInstallCommand(\n packageManager: PackageManager,\n dependencies: readonly string[],\n ): string {\n switch (packageManager) {\n case 'pnpm':\n return `pnpm add ${dependencies.join(' ')}`\n case 'yarn':\n return `yarn add ${dependencies.join(' ')}`\n case 'bun':\n return `bun add ${dependencies.join(' ')}`\n case 'npm':\n default:\n return `npm install ${dependencies.join(' ')}`\n }\n }\n\n /**\n * Filter out npm dependencies that are already installed\n * @param dependencies - Dependencies to check\n * @returns Array of missing dependencies\n */\n private async filterMissingNpmDependencies(\n dependencies: readonly string[],\n ): Promise<string[]> {\n try {\n const { stdout } = await execAsync('npm list --json --depth=0', {\n cwd: process.cwd(),\n timeout: 30000,\n })\n\n const installed = JSON.parse(stdout) as Record<string, any>\n const installedDeps = Object.keys({\n ...installed.dependencies,\n ...installed.devDependencies,\n })\n\n return dependencies.filter((dep) => {\n const name = dep.split('@')[0]\n return !installedDeps.includes(name)\n })\n } catch {\n // If we can't check, assume all need to be installed\n return dependencies as string[]\n }\n }\n\n /**\n * Filter out composer dependencies that are already installed\n * @param dependencies - Dependencies to check\n * @returns Array of missing dependencies\n */\n private async filterMissingComposerDependencies(\n dependencies: readonly string[],\n ): Promise<string[]> {\n try {\n const { stdout } = await execAsync(\n 'composer show --installed --format=json',\n {\n cwd: process.cwd(),\n timeout: 30000,\n },\n )\n\n const installed = JSON.parse(stdout) as {\n installed: Array<{ name: string }>\n }\n const installedDeps = installed.installed.map((pkg) => pkg.name)\n\n return dependencies.filter((dep) => {\n const name = dep.split(':')[0]\n return !installedDeps.includes(name)\n })\n } catch {\n // If we can't check, assume all need to be installed\n return dependencies as string[]\n }\n }\n}\n","import prompts from 'prompts'\nimport fsExtra from 'fs-extra'\nimport type {\n AddResult,\n FailedComponent,\n VelyxComponentMeta,\n} from '@/src/types'\nimport type {\n IConfigManager,\n IFileSystemService,\n IRegistryService,\n} from '@/src/types/interfaces'\nimport { FilesystemService } from '@/src/services/filesystem-service'\nimport { DependencyService } from '@/src/services/dependency-service'\nimport { injectComponentJs } from '@/src/utils/js'\nimport { logger } from '@/src/utils/logger'\nimport {\n createFileBackup,\n deleteFileBackup,\n restoreFileBackup,\n} from '@/src/utils/file-helper'\n\ntype PlannedFile = {\n componentName: string\n filePath: string\n fileType: 'blade' | 'js' | 'css' | null\n destPath: string\n content: string\n existedBefore: boolean\n}\n\n/**\n * Determine file type from file path\n */\nfunction getFileTypeFromPath(filePath: string): 'blade' | 'js' | 'css' | null {\n if (filePath.endsWith('.blade.php')) return 'blade'\n if (filePath.endsWith('.js')) return 'js'\n if (filePath.endsWith('.css')) return 'css'\n return null\n}\n\n/**\n * Service for managing component operations\n */\nexport class ComponentService {\n private readonly fileSystem: IFileSystemService\n private readonly dependencyService: DependencyService\n\n /**\n * Create a new ComponentService instance\n * @param registryService - Service for registry operations\n * @param fileSystem - Optional file system service (creates new one if not provided)\n * @param configManager - Service for configuration management\n */\n constructor(\n private readonly registryService: IRegistryService,\n fileSystem?: IFileSystemService,\n private readonly configManager?: IConfigManager,\n ) {\n this.fileSystem = fileSystem ?? new FilesystemService()\n this.dependencyService = new DependencyService(this.fileSystem)\n if (!this.configManager) {\n throw new Error('ConfigManager is required')\n }\n }\n\n /**\n * Add multiple components to the project\n * @param componentNames - Array of component names to add\n * @returns Promise resolving to result of the operation\n */\n async addComponents(componentNames: readonly string[]): Promise<AddResult> {\n const result: {\n added: string[]\n skipped: string[]\n failed: FailedComponent[]\n } = {\n added: [],\n skipped: [],\n failed: [],\n }\n\n for (const componentName of componentNames) {\n try {\n const componentResult = await this.addComponent(componentName)\n result.added.push(...componentResult.added)\n result.skipped.push(...componentResult.skipped)\n result.failed.push(...componentResult.failed)\n } catch (error) {\n result.failed.push({\n name: componentName,\n error: (error as Error).message,\n })\n }\n }\n\n return result\n }\n\n /**\n * Add a single component to the project\n * @param componentName - Name of the component to add\n * @returns Promise resolving to result of the operation\n * @throws Error if component fetch fails\n */\n private async addComponent(componentName: string): Promise<AddResult> {\n const result: {\n added: string[]\n skipped: string[]\n failed: FailedComponent[]\n } = {\n added: [],\n skipped: [],\n failed: [],\n }\n\n // Fetch component metadata with files\n const component = await this.registryService.fetchComponent(\n componentName,\n { includeFiles: true },\n )\n\n // Resolve dependencies (fetch without files for dependencies)\n await this.registryService.resolveDependencies(component)\n\n // Install component dependencies (npm/composer)\n const dependencies = this.buildDependencies(component)\n if (dependencies) {\n const packageManager = this.configManager!.getPackageManager()\n try {\n await this.dependencyService.installDependencies(\n dependencies,\n packageManager,\n )\n } catch (error) {\n logger.warn(\n `Failed to install dependencies for ${componentName}: ${\n (error as Error).message\n }`,\n )\n // Continue with file installation even if dependencies fail\n }\n }\n\n const plannedFiles: PlannedFile[] = []\n\n // Fetch files for the main component with content\n const componentWithFiles = await this.fetchComponentWithFiles(componentName)\n \n for (const [filePath, content] of Object.entries(componentWithFiles.files)) {\n // Determine destination based on file type\n const dest = this.getDestinationPath(filePath)\n const fileType = getFileTypeFromPath(filePath)\n\n // Check if file exists and handle conflict\n const existedBefore = await this.fileSystem.fileExists(dest)\n if (existedBefore) {\n const action = await this.handleFileConflict(filePath)\n if (action === 'skip') {\n result.skipped.push(`${componentName}/${filePath}`)\n continue\n } else if (action === 'cancel') {\n logger.error('Cancelled.')\n process.exit(0)\n }\n }\n\n plannedFiles.push({\n componentName,\n filePath,\n fileType,\n destPath: dest,\n content,\n existedBefore,\n })\n }\n\n if (plannedFiles.length > 0) {\n try {\n await this.applyFileBatch(plannedFiles)\n plannedFiles.forEach((file) =>\n result.added.push(`${file.componentName}/${file.filePath}`),\n )\n\n const jsComponents = new Set(\n plannedFiles\n .filter((file) => file.fileType === 'js')\n .map((file) => file.componentName),\n )\n for (const jsComponent of Array.from(jsComponents)) {\n await this.autoImportJs(jsComponent)\n }\n } catch (error) {\n plannedFiles.forEach((file) =>\n result.failed.push({\n name: `${file.componentName}/${file.filePath}`,\n error: (error as Error).message,\n }),\n )\n }\n }\n\n return result\n }\n\n /**\n * Build dependencies object from component metadata\n */\n private buildDependencies(component: VelyxComponentMeta): {\n composer?: readonly string[]\n npm?: readonly string[]\n } | null {\n const dependencies: {\n composer?: string[]\n npm?: string[]\n } = {}\n\n if (component.requires && component.requires.length > 0) {\n dependencies.composer = [...component.requires]\n }\n\n if (component.requires_alpine) {\n dependencies.npm = ['alpinejs']\n }\n\n return Object.keys(dependencies).length > 0 ? dependencies : null\n }\n\n /**\n * Fetch component with files from registry\n */\n private async fetchComponentWithFiles(\n componentName: string,\n ): Promise<{ files: Record<string, string> }> {\n const result = await this.registryService.fetchComponent(componentName, {\n includeFiles: true,\n })\n\n // Check if the result has files (RegistryComponentWithFiles)\n if ('files' in result) {\n return result\n }\n\n // Fallback: if no files, return empty object\n return { files: {} }\n }\n\n /**\n * Automatically import component JS into the main JS entry\n * @param componentName - Name of the component\n */\n private async autoImportJs(componentName: string): Promise<void> {\n try {\n const jsEntry = this.configManager?.getJsEntryPath()\n if (!jsEntry || !(await this.fileSystem.fileExists(jsEntry))) {\n return\n }\n\n const importPath = `./ui/${componentName}`\n injectComponentJs(jsEntry, componentName, importPath)\n logger.success(`Auto-imported ${componentName} into ${jsEntry}`)\n } catch (error) {\n logger.warn(\n `Failed to auto-import JS for ${componentName}: ${\n (error as Error).message\n }`,\n )\n }\n }\n\n /**\n * Get the destination path for a component file\n * The API returns file paths in project structure format:\n * - resources/views/components/ui/{name}/{name}.blade.php\n * - resources/js/ui/{name}.js\n * - resources/css/ui/{name}.css\n *\n * We preserve the API's structure for consistency\n *\n * @param filePath - File path from API\n * @returns Destination file path\n */\n private getDestinationPath(filePath: string): string {\n // The API already provides the correct path structure\n // Just ensure it's relative to project root\n return filePath\n }\n\n /**\n * Handle file conflict by prompting user\n * @param filePath - Path of the conflicting file\n * @returns Promise resolving to user action (\"skip\", \"overwrite\", or \"cancel\")\n */\n private async handleFileConflict(\n filePath: string,\n ): Promise<'skip' | 'overwrite' | 'cancel'> {\n const { action } = await prompts(\n {\n type: 'select',\n name: 'action',\n message: `File \"${filePath}\" already exists. What do you want to do?`,\n choices: [\n { title: 'Skip', value: 'skip' },\n { title: 'Overwrite', value: 'overwrite' },\n { title: 'Cancel', value: 'cancel' },\n ],\n initial: 0,\n },\n {\n onCancel: () => {\n logger.error('Cancelled.')\n process.exit(0)\n },\n },\n )\n\n return action as 'skip' | 'overwrite' | 'cancel'\n }\n\n private async applyFileBatch(plannedFiles: PlannedFile[]): Promise<void> {\n const tempFiles: string[] = []\n const backupTargets: string[] = []\n\n try {\n for (const file of plannedFiles) {\n const tempPath = `${file.destPath}.velyx-tmp`\n await this.fileSystem.writeFile(tempPath, file.content)\n tempFiles.push(tempPath)\n }\n\n for (const file of plannedFiles) {\n if (!file.existedBefore) {\n continue\n }\n\n const backupPath = createFileBackup(file.destPath)\n if (!backupPath) {\n throw new Error(`Failed to create backup for ${file.destPath}`)\n }\n backupTargets.push(file.destPath)\n }\n\n for (const file of plannedFiles) {\n const tempPath = `${file.destPath}.velyx-tmp`\n await fsExtra.move(tempPath, file.destPath, { overwrite: true })\n }\n\n backupTargets.forEach((filePath) => deleteFileBackup(filePath))\n } catch (error) {\n for (const file of plannedFiles) {\n if (await this.fileSystem.fileExists(file.destPath)) {\n await fsExtra.remove(file.destPath)\n }\n if (file.existedBefore) {\n restoreFileBackup(file.destPath)\n }\n }\n\n for (const tempFile of tempFiles) {\n if (await this.fileSystem.fileExists(tempFile)) {\n await fsExtra.remove(tempFile)\n }\n }\n\n throw error\n }\n }\n}\n","import type { AddResult, RegistryData } from '@/src/types'\nimport type { IRegistryService, IConfigManager } from '../types/interfaces'\nimport { ComponentService } from './component-service'\nimport { FilesystemService } from './filesystem-service'\nimport { logger } from '../utils/logger'\n\n/**\n * Service for handling component addition operations\n */\nexport class AddService {\n private readonly componentService: ComponentService\n\n /**\n * Create a new AddService instance\n * @param registryService - Service for registry operations\n * @param configManager - Service for configuration management\n * @param componentService - Optional component service (creates new one if not provided)\n */\n constructor(\n private readonly registryService: IRegistryService,\n private readonly configManager: IConfigManager,\n componentService?: ComponentService,\n ) {\n // ComponentService will be created if not provided\n // This allows for dependency injection in tests\n this.componentService =\n componentService ??\n new ComponentService(\n registryService,\n new FilesystemService(),\n configManager,\n )\n }\n\n /**\n * Validate that Velyx is initialized\n * @throws Error if not initialized\n */\n validateInitialization(): void {\n if (!this.configManager.validate()) {\n throw new Error('Velyx is not initialized')\n }\n }\n\n /**\n * Validate that components exist in the registry\n * @param componentNames - Names of components to validate\n * @param registry - Registry data\n * @throws Error if any component is not found\n */\n validateComponents(\n componentNames: readonly string[],\n registry: RegistryData,\n ): void {\n for (const componentName of componentNames) {\n const found = registry.components.find((c) => c.name === componentName)\n if (!found) {\n throw new Error(`Component \"${componentName}\" not found`)\n }\n }\n }\n\n /**\n * Get available components from registry\n * @returns Promise resolving to registry data\n * @throws NetworkError if fetch fails\n */\n async getAvailableComponents(): Promise<RegistryData> {\n return await this.registryService.fetchRegistry()\n }\n\n /**\n * Add components to the project\n * @param componentNames - Names of components to add\n * @returns Promise resolving to result of the operation\n */\n async addComponents(componentNames: readonly string[]): Promise<AddResult> {\n return await this.componentService.addComponents(componentNames)\n }\n\n /**\n * Display the results of adding components\n * @param result - Result of the add operation\n */\n displayResults(result: AddResult): void {\n result.added.forEach((name) => logger.success(`Added ${name}`))\n result.skipped.forEach((name) => logger.warn(`Skipped ${name}`))\n result.failed.forEach(({ name, error }) =>\n logger.error(`Failed to add ${name}: ${error}`),\n )\n }\n\n /**\n * Display next steps after adding components\n * @param result - Result of the add operation\n */\n displayNextSteps(result: AddResult): void {\n if (result.added.length === 0) {\n return\n }\n\n console.log('\\nš Happy coding! Enjoy building beautiful components!')\n }\n}\n","/**\n * Base error class for registry-related errors\n */\nexport class RegistryError extends Error {\n /**\n * Create a new RegistryError\n * @param message - Error message\n * @param cause - Original error that caused this error\n */\n constructor(\n message: string,\n public readonly cause?: Error,\n ) {\n super(message)\n this.name = 'RegistryError'\n }\n}\n\n/**\n * Error thrown when a network request fails\n */\nexport class NetworkError extends RegistryError {\n /**\n * Create a new NetworkError\n * @param message - Error message\n * @param cause - Original error that caused this error\n */\n constructor(message: string, cause?: Error) {\n super(message, cause)\n this.name = 'NetworkError'\n }\n}\n\n/**\n * Error thrown when a component is not found in the registry\n */\nexport class ComponentNotFoundError extends RegistryError {\n /**\n * Create a new ComponentNotFoundError\n * @param componentName - Name of the component that was not found\n * @param cause - Original error that caused this error\n */\n constructor(componentName: string, cause?: Error) {\n super(`Component \"${componentName}\" not found`, cause)\n this.name = 'ComponentNotFoundError'\n }\n}\n","import { NetworkError } from '../errors/errors'\nimport type { FetchOptions } from '../types'\n\n/**\n * Default retry options\n */\nconst DEFAULT_RETRY_OPTIONS: Required<FetchOptions> = {\n maxRetries: 3,\n initialDelay: 1000,\n backoffFactor: 2,\n maxDelay: 10000,\n retryableStatusCodes: [408, 429, 500, 502, 503, 504],\n timeout: 30000,\n headers: {},\n}\n\n/**\n * Sleep utility for retry delays\n * @param ms - Milliseconds to sleep\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Calculate delay for retry attempt with exponential backoff\n * @param attempt - Current attempt number (0-indexed)\n * @param initialDelay - Initial delay in milliseconds\n * @param backoffFactor - Factor to multiply delay by each attempt\n * @param maxDelay - Maximum delay in milliseconds\n * @returns Delay in milliseconds\n */\nfunction calculateDelay(\n attempt: number,\n initialDelay: number,\n backoffFactor: number,\n maxDelay: number,\n): number {\n const delay = initialDelay * Math.pow(backoffFactor, attempt)\n return Math.min(delay, maxDelay)\n}\n\n/**\n * Check if a status code is retryable\n * @param status - HTTP status code\n * @param retryableStatusCodes - List of retryable status codes\n * @returns True if status code is retryable\n */\nfunction isRetryableStatus(\n status: number,\n retryableStatusCodes: readonly number[],\n): boolean {\n return retryableStatusCodes.includes(status)\n}\n\n/**\n * Create a fetch request with timeout\n * @param url - URL to fetch\n * @param options - Fetch options including timeout\n * @returns Promise resolving to Response\n */\nasync function fetchWithTimeout(\n url: string,\n options: FetchOptions,\n): Promise<Response> {\n const { timeout = DEFAULT_RETRY_OPTIONS.timeout, headers = {} } = options\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n try {\n const response = await fetch(url, {\n signal: controller.signal,\n headers: {\n 'User-Agent': 'Velyx-CLI',\n ...headers,\n },\n })\n return response\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new NetworkError(\n `Request timeout after ${timeout}ms for ${url}`,\n error,\n )\n }\n throw error\n } finally {\n clearTimeout(timeoutId)\n }\n}\n\n/**\n * HTTP service with retry logic and timeout support\n */\nexport class HttpService {\n /**\n * Fetch a URL with retry logic and timeout\n * @param url - URL to fetch\n * @param options - Fetch options including retry configuration\n * @returns Promise resolving to Response\n * @throws NetworkError if all retries fail\n */\n async fetch(url: string, options: FetchOptions = {}): Promise<Response> {\n const retryOptions = {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_OPTIONS.maxRetries,\n initialDelay: options.initialDelay ?? DEFAULT_RETRY_OPTIONS.initialDelay,\n backoffFactor:\n options.backoffFactor ?? DEFAULT_RETRY_OPTIONS.backoffFactor,\n maxDelay: options.maxDelay ?? DEFAULT_RETRY_OPTIONS.maxDelay,\n retryableStatusCodes:\n options.retryableStatusCodes ??\n DEFAULT_RETRY_OPTIONS.retryableStatusCodes,\n timeout: options.timeout ?? DEFAULT_RETRY_OPTIONS.timeout,\n headers: options.headers ?? DEFAULT_RETRY_OPTIONS.headers,\n }\n\n let lastError: Error | null = null\n\n for (let attempt = 0; attempt <= retryOptions.maxRetries; attempt++) {\n try {\n const response = await fetchWithTimeout(url, {\n ...options,\n timeout: retryOptions.timeout,\n headers: retryOptions.headers,\n })\n\n // If response is successful or not retryable, return it\n if (\n response.ok ||\n !isRetryableStatus(response.status, retryOptions.retryableStatusCodes)\n ) {\n return response\n }\n console.log('Attempt: ', attempt)\n // If this is the last attempt, throw error\n if (attempt === retryOptions.maxRetries) {\n throw new NetworkError(\n `Request failed after ${retryOptions.maxRetries + 1} attempts: ${response.status} ${response.statusText}`,\n )\n }\n\n // Calculate delay and wait before retry\n const delay = calculateDelay(\n attempt,\n retryOptions.initialDelay,\n retryOptions.backoffFactor,\n retryOptions.maxDelay,\n )\n await sleep(delay)\n } catch (error) {\n lastError = error as Error\n\n // Don't retry on certain errors\n if (\n error instanceof NetworkError &&\n error.message.includes('timeout')\n ) {\n if (attempt === retryOptions.maxRetries) {\n throw error\n }\n const delay = calculateDelay(\n attempt,\n retryOptions.initialDelay,\n retryOptions.backoffFactor,\n retryOptions.maxDelay,\n )\n await sleep(delay)\n continue\n }\n\n // If this is the last attempt, throw error\n if (attempt === retryOptions.maxRetries) {\n if (lastError instanceof NetworkError) {\n throw lastError\n }\n throw new NetworkError(\n `Request failed after ${retryOptions.maxRetries + 1} attempts: ${lastError.message}`,\n lastError,\n )\n }\n\n // Calculate delay and wait before retry\n const delay = calculateDelay(\n attempt,\n retryOptions.initialDelay,\n retryOptions.backoffFactor,\n retryOptions.maxDelay,\n )\n await sleep(delay)\n }\n }\n\n throw new NetworkError(\n `Request failed after ${retryOptions.maxRetries + 1} attempts: ${lastError?.message ?? 'Unknown error'}`,\n lastError ?? undefined,\n )\n }\n\n /**\n * Fetch JSON from a URL with retry logic\n * @param url - URL to fetch\n * @param options - Fetch options\n * @returns Promise resolving to parsed JSON\n * @throws NetworkError if fetch or parsing fails\n */\n async fetchJson<T>(url: string, options?: FetchOptions): Promise<T> {\n const response = await this.fetch(url, options)\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to fetch JSON from ${url}: ${response.status} ${response.statusText}`,\n )\n }\n\n try {\n return (await response.json()) as T\n } catch (error) {\n throw new NetworkError(\n `Failed to parse JSON from ${url}: ${(error as Error).message}`,\n error as Error,\n )\n }\n }\n\n /**\n * Fetch text from a URL with retry logic\n * @param url - URL to fetch\n * @param options - Fetch options\n * @returns Promise resolving to text content\n * @throws NetworkError if fetch fails\n */\n async fetchText(url: string, options?: FetchOptions): Promise<string> {\n const response = await this.fetch(url, options)\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to fetch text from ${url}: ${response.status} ${response.statusText}`,\n )\n }\n\n try {\n return await response.text()\n } catch (error) {\n throw new NetworkError(\n `Failed to read text from ${url}: ${(error as Error).message}`,\n error as Error,\n )\n }\n }\n}\n","/**\n * Get Velyx Registry API v1 URL\n * @returns Velyx Registry API URL\n */\nexport const getRegistryApiUrl = (): string => {\n // Allow override via environment variable for development\n if (process.env.VELYX_REGISTRY_URL) {\n return process.env.VELYX_REGISTRY_URL.replace(/\\/$/, '') // Remove trailing slash\n }\n\n // Default to local registry for development\n // In production, this would be https://registry.velyx.dev/api/v1\n return 'http://velyx.test/api/v1'\n}\n","import type {\n RegistryComponentWithFiles,\n RegistryComponentsResponse,\n RegistryVersionsResponse,\n RegistryComponentResponse,\n VelyxComponentMeta,\n} from '../types'\nimport type { IRegistryService } from '../types/interfaces'\nimport { NetworkError, ComponentNotFoundError } from '../errors/errors'\nimport { HttpService } from './http-service'\nimport { getRegistryApiUrl } from '../utils/environment'\n\n/**\n * Service for interacting with Velyx Registry API v1\n */\nexport class VelyxRegistryService implements IRegistryService {\n private readonly httpService: HttpService\n private readonly baseUrl: string\n\n /**\n * Create a new VelyxRegistryService instance\n * @param httpService - Optional HTTP service instance (creates new one if not provided)\n */\n constructor(httpService?: HttpService) {\n this.httpService = httpService ?? new HttpService()\n this.baseUrl = getRegistryApiUrl()\n }\n\n /**\n * Fetch complete registry data\n * @returns Promise resolving to registry data\n * @throws NetworkError if fetch fails\n */\n async fetchRegistry(): Promise<{\n components: readonly VelyxComponentMeta[]\n count: number\n }> {\n try {\n const response = await this.httpService.fetch(\n `${this.baseUrl}/components`,\n )\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to fetch registry: ${response.status} ${response.statusText}`,\n )\n }\n\n const data = await this.httpService.fetchJson<RegistryComponentsResponse>(\n `${this.baseUrl}/components`,\n )\n\n // Convert Registry API v1 format (object with keys) to array\n const components = Object.values(data.data)\n\n return { components, count: data.count }\n } catch (error) {\n if (error instanceof NetworkError) {\n throw error\n }\n throw new NetworkError(\n `Failed to fetch registry: ${(error as Error).message}`,\n )\n }\n }\n\n /**\n * Fetch metadata for a specific component\n * @param name - Component name\n * @param options - Optional parameters (version, includeFiles)\n * @returns Promise resolving to component metadata (with files if includeFiles is true)\n * @throws ComponentNotFoundError if component doesn't exist\n * @throws NetworkError if fetch fails\n */\n async fetchComponent(\n name: string,\n options?: { version?: string; includeFiles?: boolean },\n ): Promise<VelyxComponentMeta | RegistryComponentWithFiles> {\n try {\n const url = this.buildComponentUrl(name, options)\n\n const response = await this.httpService.fetch(url)\n\n if (response.status === 404) {\n throw new ComponentNotFoundError(name)\n }\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to fetch component: ${response.status} ${response.statusText}`,\n )\n }\n\n const result =\n await this.httpService.fetchJson<RegistryComponentResponse>(url)\n\n if (options?.includeFiles) {\n return result.data\n }\n\n return this.convertRegistryComponentToMeta(result.data)\n } catch (error) {\n if (\n error instanceof ComponentNotFoundError ||\n error instanceof NetworkError\n ) {\n throw error\n }\n throw new NetworkError(\n `Failed to fetch component \"${name}\": ${(error as Error).message}`,\n )\n }\n }\n\n /**\n * Fetch file content for a component\n * @param componentUrl - Component URL or name\n * @param path - File path within component\n * @returns Promise resolving to file content\n * @throws ComponentNotFoundError if component or file doesn't exist\n * @throws NetworkError if fetch fails\n */\n async fetchFile(componentUrl: string, path: string): Promise<string> {\n try {\n const componentName = componentUrl.split('/').pop() || componentUrl\n\n const response = await this.httpService.fetch(\n `${this.baseUrl}/components/${componentName}`,\n )\n\n if (response.status === 404) {\n throw new ComponentNotFoundError(componentName)\n }\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to fetch component: ${response.status} ${response.statusText}`,\n )\n }\n\n const component =\n await this.httpService.fetchJson<RegistryComponentWithFiles>(\n `${this.baseUrl}/components/${componentName}`,\n )\n\n // Find the file in the component's files\n const fileContent = component.files[path]\n if (fileContent === undefined) {\n throw new NetworkError(\n `File \"${path}\" not found in component \"${componentName}\"`,\n )\n }\n\n return fileContent\n } catch (error) {\n if (\n error instanceof ComponentNotFoundError ||\n error instanceof NetworkError\n ) {\n throw error\n }\n throw new NetworkError(\n `Failed to fetch file \"${path}\": ${(error as Error).message}`,\n )\n }\n }\n\n /**\n * Resolve component dependencies\n * @param component - Component metadata\n * @returns Promise resolving to array of components including dependencies\n */\n async resolveDependencies(\n component: VelyxComponentMeta,\n ): Promise<readonly VelyxComponentMeta[]> {\n const visited = new Set<string>()\n const resolved: VelyxComponentMeta[] = []\n\n const resolve = async (comp: VelyxComponentMeta) => {\n if (visited.has(comp.name)) return\n visited.add(comp.name)\n resolved.push(comp)\n\n // Resolve dependencies from the 'requires' field\n if (comp.requires && comp.requires.length > 0) {\n for (const dep of comp.requires) {\n try {\n // Try to fetch dependency as a Velyx component\n const depComponent = await this.fetchComponent(dep)\n await resolve(depComponent)\n } catch {\n // Skip if dependency is not a Velyx component (might be a composer package)\n }\n }\n }\n }\n\n await resolve(component)\n return resolved\n }\n\n /**\n * Convert Registry API v1 component format to VelyxComponentMeta\n */\n private convertRegistryComponentToMeta(\n component: RegistryComponentWithFiles,\n ): VelyxComponentMeta {\n return {\n name: component.name,\n description: component.description,\n latest: component.latest,\n versions: component.versions,\n requires_alpine: component.requires_alpine,\n requires: component.requires,\n categories: component.categories,\n laravel: component.laravel,\n }\n }\n\n /**\n * Build URL for fetching component with optional parameters\n */\n private buildComponentUrl(\n name: string,\n options?: { version?: string; includeFiles?: boolean },\n ): string {\n const params = new URLSearchParams()\n\n if (options?.version) {\n params.append('version', options.version)\n }\n\n if (options?.includeFiles) {\n params.append('include', 'files')\n }\n\n const queryString = params.toString()\n return `${this.baseUrl}/components/${name}${queryString ? `?${queryString}` : ''}`\n }\n\n /**\n * Get available versions for a component\n * @param name - Component name\n * @returns Promise resolving to versions data\n */\n async getComponentVersions(name: string): Promise<RegistryVersionsResponse> {\n try {\n const response = await this.httpService.fetch(\n `${this.baseUrl}/components/${name}/versions`,\n )\n\n if (response.status === 404) {\n throw new ComponentNotFoundError(name)\n }\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to fetch component versions: ${response.status} ${response.statusText}`,\n )\n }\n\n return await this.httpService.fetchJson<RegistryVersionsResponse>(\n `${this.baseUrl}/components/${name}/versions`,\n )\n } catch (error) {\n if (\n error instanceof ComponentNotFoundError ||\n error instanceof NetworkError\n ) {\n throw error\n }\n throw new NetworkError(\n `Failed to fetch versions for \"${name}\": ${(error as Error).message}`,\n )\n }\n }\n}\n","import type {\n VelyxComponentMeta,\n RegistryComponentWithFiles,\n} from '../types'\nimport type {\n IRegistryService,\n FetchComponentOptions,\n} from '../types/interfaces'\nimport { VelyxRegistryService } from './velyx-registry-service'\nimport { spinner } from '../utils/spinner'\n\n/**\n * Service for interacting with Velyx component registry\n * This is a wrapper around VelyxRegistryService with UI feedback\n */\nexport class RegistryService implements IRegistryService {\n private readonly velyxService: VelyxRegistryService\n\n /**\n * Create a new RegistryService instance\n */\n constructor() {\n this.velyxService = new VelyxRegistryService()\n }\n\n /**\n * Fetch complete registry data\n * @returns Promise resolving to registry data\n * @throws NetworkError if fetch fails\n */\n async fetchRegistry(): Promise<{\n components: readonly VelyxComponentMeta[]\n count: number\n }> {\n return await spinner.withTask(\n 'Fetching registry...',\n () => this.velyxService.fetchRegistry(),\n undefined,\n 'Failed to fetch registry',\n )\n }\n\n /**\n * Fetch metadata for a specific component\n * @param name - Component name\n * @param options - Optional parameters (version, includeFiles)\n * @returns Promise resolving to component metadata (with files if includeFiles is true)\n * @throws ComponentNotFoundError if component doesn't exist\n * @throws NetworkError if fetch fails\n */\n async fetchComponent(\n name: string,\n options?: FetchComponentOptions,\n ): Promise<VelyxComponentMeta | RegistryComponentWithFiles> {\n const taskMessage = options?.includeFiles\n ? `Fetching component \"${name}\" with files...`\n : `Fetching component \"${name}\" metadata...`\n\n return await spinner.withTask(\n taskMessage,\n () => this.velyxService.fetchComponent(name, options),\n undefined,\n `Failed to fetch component \"${name}\"`,\n )\n }\n\n /**\n * Resolve component dependencies\n * @param component - Component metadata\n * @returns Promise resolving to array of components including dependencies\n */\n async resolveDependencies(\n component: VelyxComponentMeta,\n ): Promise<readonly VelyxComponentMeta[]> {\n return await spinner.withTask(\n 'Resolving dependencies...',\n () => this.velyxService.resolveDependencies(component),\n undefined,\n 'Failed to resolve dependencies',\n )\n }\n}\n","import { ConfigManager } from '@/src/config/config-manager'\nimport { AddService } from '@/src/services/add-service'\nimport { RegistryService } from '@/src/services/registry-service'\nimport { logger } from '@/src/utils/logger'\nimport { z } from 'zod'\nimport prompts from 'prompts'\n\nexport type AddOptions = {\n components?: string[]\n yes: boolean\n overwrite: boolean\n cwd: string\n all: boolean\n path?: string\n silent: boolean\n srcDir?: boolean\n cssVariables?: boolean\n}\n\nasync function promptForRegistryComponents(\n options: AddOptions,\n availableComponents: readonly string[],\n): Promise<string[]> {\n if (options.all) {\n return [...availableComponents]\n }\n\n if (options.components?.length) {\n return options.components\n }\n\n logger.info('Use arrow keys and space to select, then press enter.')\n\n const { components } = await prompts({\n type: 'multiselect',\n name: 'components',\n message: 'Which components would you like to add?',\n hint: 'Space to select. A to toggle all. Enter to submit.',\n instructions: false,\n choices: availableComponents.map((name) => ({\n title: name,\n value: name,\n selected: options.all ? true : options.components?.includes(name),\n })),\n })\n\n if (!components?.length) {\n logger.warn('No components selected. Exiting.')\n logger.info('')\n process.exit(1)\n }\n\n const result = z.array(z.string()).safeParse(components)\n if (!result.success) {\n logger.error('Something went wrong. Please try again.')\n process.exit(1)\n }\n\n return result.data\n}\n\nexport async function addComponents(options: AddOptions): Promise<void> {\n const configManager = new ConfigManager()\n await configManager.load()\n\n const registryService = new RegistryService()\n const addService = new AddService(registryService, configManager)\n\n try {\n addService.validateInitialization()\n } catch {\n logger.error('Velyx is not initialized')\n logger.log('Run velyx init first')\n process.exit(1)\n }\n\n const registry = await addService.getAvailableComponents()\n\n const available = registry.components\n .map((component: { name: string }) => component.name)\n .sort((a: string, b: string) => a.localeCompare(b))\n const componentNames = await promptForRegistryComponents(options, available)\n try {\n addService.validateComponents(componentNames, registry)\n } catch (err) {\n logger.error((err as Error).message)\n logger.log('Run velyx list to see available components')\n process.exit(1)\n }\n\n const result = await addService.addComponents(componentNames)\n addService.displayResults(result)\n addService.displayNextSteps(result)\n}\n","#!/usr/bin/env node\nimport { ErrorHandler } from '@/src/errors/ErrorHandler'\nimport { addComponents } from '@/src/utils/add-components'\nimport { Command } from 'commander'\nimport { z } from 'zod'\nimport path from 'path'\n\nexport const addOptionsSchema = z.object({\n components: z.array(z.string()).optional(),\n yes: z.boolean(),\n overwrite: z.boolean(),\n cwd: z.string(),\n all: z.boolean(),\n path: z.string().optional(),\n silent: z.boolean(),\n srcDir: z.boolean().optional(),\n cssVariables: z.boolean().optional(),\n})\n\n/**\n * Register the 'add' command with the CLI program\n * @param program - Commander program instance\n */\nexport const add = new Command()\n .name('add')\n .argument('[components...]', 'Names of components to add')\n .option('-y, --yes', 'skip confirmation prompt.', false)\n .option('-o, --overwrite', 'overwrite existing files.', false)\n .option(\n '-c, --cwd <cwd>',\n 'the working directory. defaults to the current directory.',\n process.cwd(),\n )\n .option('-a, --all', 'add all available components', false)\n .option('-p, --path <path>', 'the path to add the component to.')\n .option('-s, --silent', 'mute output.', false)\n .option(\n '--src-dir',\n 'use the src directory when creating a new project.',\n false,\n )\n .option(\n '--no-src-dir',\n 'do not use the src directory when creating a new project.',\n )\n .option('--css-variables', 'use CSS variables for theming.', true)\n .option('--no-css-variables', 'do not use CSS variables for theming.')\n .description('Add one or more UI components to your Laravel project')\n .action(async (components, opts) => {\n const errorHandler = new ErrorHandler()\n\n try {\n const rawOptions = {\n components,\n cwd: path.resolve(opts.cwd),\n ...opts,\n cssVariables: opts.cssVariables ?? true,\n }\n\n const options = addOptionsSchema.parse(rawOptions)\n await addComponents(options)\n } catch (error) {\n errorHandler.handle(error as Error, 'add command')\n process.exit(1)\n }\n })\n","import chalk from 'chalk'\nimport Table from 'cli-table3'\nimport type { VelyxComponentMeta } from '@/src/types'\nimport { RegistryService } from '@/src/services/registry-service'\nimport { logger } from '@/src/utils/logger'\n\nexport type ListOptions = {\n query?: string\n limit?: number\n offset?: number\n json: boolean\n}\n\nfunction filterComponents(\n components: readonly VelyxComponentMeta[],\n query?: string,\n): VelyxComponentMeta[] {\n if (!query) {\n return [...components]\n }\n\n const normalized = query.toLowerCase()\n return components.filter((component) => {\n const nameMatch = component.name.toLowerCase().includes(normalized)\n const descriptionMatch = component.description\n ? component.description.toLowerCase().includes(normalized)\n : false\n const categoryMatch = component.categories\n ? component.categories.some((category) =>\n category.toLowerCase().includes(normalized),\n )\n : false\n\n return nameMatch || descriptionMatch || categoryMatch\n })\n}\n\nfunction sliceComponents(\n components: VelyxComponentMeta[],\n offset?: number,\n limit?: number,\n): VelyxComponentMeta[] {\n const start = Math.max(0, offset ?? 0)\n if (limit === undefined) {\n return components.slice(start)\n }\n return components.slice(start, start + Math.max(0, limit))\n}\n\nexport async function listComponents(options: ListOptions): Promise<void> {\n const registryService = new RegistryService()\n const registry = await registryService.fetchRegistry()\n\n const sorted = [...registry.components].sort((a, b) =>\n a.name.localeCompare(b.name),\n )\n\n const filtered = filterComponents(sorted, options.query)\n const sliced = sliceComponents(filtered, options.offset, options.limit)\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n total: filtered.length,\n count: sliced.length,\n offset: options.offset ?? 0,\n limit: options.limit ?? null,\n components: sliced,\n },\n null,\n 2,\n ),\n )\n return\n }\n\n if (sliced.length === 0) {\n logger.warn('No components found.')\n return\n }\n\n console.log(chalk.bold('\\nAvailable components:'))\n console.log('')\n\n const table = new Table({\n head: [\n chalk.bold('Component'),\n chalk.bold('Description'),\n chalk.bold('Categories'),\n ],\n colWidths: [24, 50, 24],\n wordWrap: true,\n style: {\n head: [],\n border: [],\n },\n })\n\n for (const component of sliced) {\n table.push([\n chalk.cyan(component.name),\n chalk.white(component.description || 'No description'),\n chalk.gray(component.categories?.join(', ') || '-'),\n ])\n }\n\n console.log(table.toString())\n console.log('')\n logger.info(`Run ${chalk.green('velyx add <component>')} to add one.`)\n}\n","import { Command } from 'commander'\nimport { z } from 'zod'\nimport path from 'path'\nimport { listComponents } from '@/src/utils/list-components'\nimport { ErrorHandler } from '@/src/errors/ErrorHandler'\nimport { logger } from '@/src/utils/logger'\nimport { ConfigManager } from '@/src/config/config-manager'\n\nconst listOptionsSchema = z.object({\n cwd: z.string(),\n query: z.string().optional(),\n limit: z.number().optional(),\n offset: z.number().optional(),\n json: z.boolean(),\n})\n\nexport const list = new Command()\n .name('list')\n .alias('search')\n .description('List or search components from the registry')\n .option(\n '-c, --cwd <cwd>',\n 'the working directory. defaults to the current directory.',\n process.cwd(),\n )\n .option('-q, --query <query>', 'query string')\n .option(\n '-l, --limit <number>',\n 'maximum number of items to display',\n undefined,\n )\n .option('-o, --offset <number>', 'number of items to skip', undefined)\n .option('--json', 'output JSON', false)\n .action(async (opts) => {\n const errorHandler = new ErrorHandler()\n\n try {\n const options = listOptionsSchema.parse({\n cwd: path.resolve(opts.cwd),\n query: opts.query,\n limit: opts.limit ? Number.parseInt(opts.limit, 10) : undefined,\n offset: opts.offset ? Number.parseInt(opts.offset, 10) : undefined,\n json: Boolean(opts.json),\n })\n\n process.chdir(options.cwd)\n\n // Validate initialization\n const configManager = new ConfigManager()\n try {\n await configManager.load()\n } catch {\n logger.error('Velyx is not initialized')\n logger.log('Run velyx init first')\n process.exit(1)\n }\n\n await listComponents(options)\n } catch (error) {\n errorHandler.handle(error as Error, 'list command')\n process.exit(1)\n }\n })\n","import chalk from 'chalk'\nimport { Command } from 'commander'\nimport { init } from '@/src/commands/init'\nimport { add } from '@/src/commands/add'\nimport { list } from '@/src/commands/list'\n\nimport packageJson from '../package.json'\n/**\n * Display a nice introduction banner\n */\nfunction displayIntro(): void {\n console.log('')\n console.log(chalk.bold.cyan(` ā¼ VELYX CLI v${packageJson.version}`))\n console.log(chalk.gray(' Tailwind CSS v4+ components for Laravel'))\n console.log('')\n}\n\n/**\n * Velyx CLI program entry point\n */\nconst program = new Command()\nprogram\n .name('velyx')\n .description('Velyx CLI: Copy UI components into your Laravel project')\n .version(\n packageJson.version || '1.0.0',\n '-v, --version',\n 'display the version number',\n )\n .hook('preAction', () => {\n displayIntro()\n })\n\nprogram.addCommand(add).addCommand(init).addCommand(list)\n\nprogram.parse(process.argv)\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/utils/file-helper.ts","../src/services/filesystem-service.ts","../src/utils/laravel.ts","../src/utils/tailwind.ts","../src/utils/requirements.ts","../src/utils/package-manager.ts","../src/utils/css.ts","../src/utils/js.ts","../src/utils/theme.ts","../src/utils/highlighter.ts","../src/utils/logger.ts","../src/utils/config.ts","../package.json","../src/services/init-service.ts","../src/utils/spinner.ts","../src/utils/preflight-init.ts","../src/utils/init-project.ts","../src/commands/init.ts","../src/errors/ErrorHandler.ts","../src/utils/errors.ts","../src/utils/handle-error.ts","../src/config/config-manager.ts","../src/services/dependency-service.ts","../src/services/component-service.ts","../src/services/add-service.ts","../src/errors/errors.ts","../src/services/http-service.ts","../src/utils/environment.ts","../src/services/velyx-registry-service.ts","../src/services/registry-service.ts","../src/utils/add-components.ts","../src/commands/add.ts","../src/utils/list-components.ts","../src/commands/list.ts","../src/index.ts"],"names":["FILE_BACKUP_SUFFIX","createFileBackup","filePath","fsExtra","backupPath","error","restoreFileBackup","deleteFileBackup","FilesystemService","fs","content","path","dirPath","isLaravelProject","readPackageJson","detectTailwindV4","pkg","deps","match","hasAlpineInPackageJson","hasInDeps","dep","hasInDevDeps","hasAlpineInLayouts","layoutDir","files","file","hasAlpineJs","detectPackageManager","CSS_CANDIDATES","findMainCss","rel","hasTailwindImport","css","injectVelyxImport","cssPath","JS_CANDIDATES","findMainJs","injectComponentJs","jsPath","componentName","componentImportPath","importStatement","lines","lastImportIndex","i","alpineDataRegistration","findColorsDir","startDir","current","depth","distPath","srcPath","parent","entryDir","COLORS_DIR","loadBaseColors","raw","color","a","b","getBaseColors","getBaseColor","name","renderCssVars","vars","key","value","copyTheme","theme","target","baseColor","lightVars","darkVars","highlighter","red","yellow","cyan","green","logger","args","writeVelyxConfig","config","readVelyxConfig","package_default","InitService","fileSystem","hasAlpine","detectedPm","js","canInject","validation","targetPath","options","stylesImported","spinner","message","ora","task","successMessage","failMessage","s","result","execAsync","promisify","exec","getProjectInfo","cwd","composerPath","packagePath","composer","originalDir","pkgManager","projectInfo","viewsPath","assetsPath","preFlightInit","errors","projectSpinner","velyxConfigPath","action","prompts","alpineSpinner","installAlpine","installSpinner","viteSpinner","initOptionsSchema","z","promptTheme","baseColors","promptStyleImport","shouldImport","resolveThemeFromOptions","matched","initProject","initService","packageManager","defaultTheme","code","init","Command","opts","VelyxError","context","ErrorHandler","RegistryErrorCode","RegistryError","handleError","ConfigManager","convertNpmToComposerFormat","DependencyService","dependencies","npmPromises","composerPromises","missingDeps","command","stdout","stderr","convertedDeps","installed","installedDeps","getFileTypeFromPath","ComponentService","registryService","configManager","componentNames","componentResult","component","plannedFiles","componentWithFiles","dest","fileType","existedBefore","jsComponents","jsComponent","jsEntry","importPath","tempFiles","backupTargets","tempPath","tempFile","AddService","componentService","registry","c","cause","NetworkError","ComponentNotFoundError","DEFAULT_RETRY_OPTIONS","sleep","ms","resolve","calculateDelay","attempt","initialDelay","backoffFactor","maxDelay","delay","isRetryableStatus","status","retryableStatusCodes","fetchWithTimeout","url","timeout","headers","controller","timeoutId","HttpService","retryOptions","lastError","response","getRegistryApiUrl","VelyxRegistryService","httpService","data","componentUrl","fileContent","visited","resolved","comp","depComponent","params","queryString","RegistryService","taskMessage","promptForRegistryComponents","availableComponents","components","addComponents","addService","available","err","addOptionsSchema","add","errorHandler","rawOptions","filterComponents","query","normalized","nameMatch","descriptionMatch","categoryMatch","category","sliceComponents","offset","limit","start","listComponents","sorted","filtered","sliced","chalk","table","Table","listOptionsSchema","list","displayIntro","program"],"mappings":"8UAEO,IAAMA,CAAAA,CAAqB,MAAA,CAE3B,SAASC,EAAAA,CAAiBC,CAAAA,CAAiC,CAChE,GAAI,CAACC,CAAAA,CAAQ,UAAA,CAAWD,CAAQ,CAAA,CAC9B,OAAO,IAAA,CAGT,IAAME,CAAAA,CAAa,CAAA,EAAGF,CAAQ,CAAA,EAAGF,CAAkB,CAAA,CAAA,CACnD,GAAI,CACF,OAAAG,CAAAA,CAAQ,UAAA,CAAWD,CAAAA,CAAUE,CAAU,CAAA,CAChCA,CACT,CAAA,MAASC,CAAAA,CAAO,CACd,OAAA,OAAA,CAAQ,KAAA,CAAM,CAAA,2BAAA,EAA8BH,CAAQ,CAAA,EAAA,EAAKG,CAAK,CAAA,CAAE,CAAA,CACzD,IACT,CACF,CAEO,SAASC,CAAAA,CAAkBJ,EAA2B,CAC3D,IAAME,CAAAA,CAAa,CAAA,EAAGF,CAAQ,CAAA,EAAGF,CAAkB,CAAA,CAAA,CAEnD,GAAI,CAACG,CAAAA,CAAQ,UAAA,CAAWC,CAAU,CAAA,CAChC,OAAO,MAAA,CAGT,GAAI,CACF,OAAAD,CAAAA,CAAQ,UAAA,CAAWC,CAAAA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CAAA","file":"index.js","sourcesContent":["import fsExtra from 'fs-extra'\n\nexport const FILE_BACKUP_SUFFIX = '.bak'\n\nexport function createFileBackup(filePath: string): string | null {\n if (!fsExtra.existsSync(filePath)) {\n return null\n }\n\n const backupPath = `${filePath}${FILE_BACKUP_SUFFIX}`\n try {\n fsExtra.renameSync(filePath, backupPath)\n return backupPath\n } catch (error) {\n console.error(`Failed to create backup of ${filePath}: ${error}`)\n return null\n }\n}\n\nexport function restoreFileBackup(filePath: string): boolean {\n const backupPath = `${filePath}${FILE_BACKUP_SUFFIX}`\n\n if (!fsExtra.existsSync(backupPath)) {\n return false\n }\n\n try {\n fsExtra.renameSync(backupPath, filePath)\n return true\n } catch (error) {\n console.error(\n `Warning: Could not restore backup file ${backupPath}: ${error}`,\n )\n return false\n }\n}\n\nexport function deleteFileBackup(filePath: string): boolean {\n const backupPath = `${filePath}${FILE_BACKUP_SUFFIX}`\n\n if (!fsExtra.existsSync(backupPath)) {\n return false\n }\n\n try {\n fsExtra.unlinkSync(backupPath)\n return true\n } catch {\n // Best effort - don't log as this is just cleanup\n return false\n }\n}\n","import { promises as fs } from 'fs'\nimport path from 'path'\nimport type { IFileSystemService } from '../types/interfaces'\n\n/**\n * Service for file system operations\n */\nexport class FilesystemService implements IFileSystemService {\n /**\n * Check if a file exists\n * @param filePath - Path to check\n * @returns Promise resolving to true if file exists\n */\n async fileExists(filePath: string): Promise<boolean> {\n try {\n await fs.access(filePath)\n return true\n } catch {\n return false\n }\n }\n\n /**\n * Write content to a file, creating directories if necessary\n * @param filePath - Path to write to\n * @param content - Content to write\n * @returns Promise that resolves when file is written\n * @throws Error if write fails\n */\n async writeFile(filePath: string, content: string): Promise<void> {\n await fs.mkdir(path.dirname(filePath), { recursive: true })\n await fs.writeFile(filePath, content, 'utf-8')\n }\n\n /**\n * Read content from a file\n * @param filePath - Path to read from\n * @returns Promise resolving to file content\n * @throws Error if file doesn't exist or read fails\n */\n async readFile(filePath: string): Promise<string> {\n return await fs.readFile(filePath, 'utf-8')\n }\n\n /**\n * Ensure a directory exists, creating it if necessary\n * @param dirPath - Directory path\n * @returns Promise that resolves when directory is ensured\n * @throws Error if directory creation fails\n */\n async ensureDir(dirPath: string): Promise<void> {\n await fs.mkdir(dirPath, { recursive: true })\n }\n}\n","import fs from 'fs'\n\n/**\n * Check if the current directory is a Laravel project\n * @returns True if Laravel project is detected\n */\nexport function isLaravelProject(): boolean {\n return fs.existsSync('composer.json') && fs.existsSync('artisan')\n}\n","import fs from 'fs'\n\n/**\n * Package.json structure\n */\ninterface PackageJson {\n dependencies?: Readonly<Record<string, string>>\n devDependencies?: Readonly<Record<string, string>>\n}\n\n/**\n * Read package.json file\n * @returns Package.json object or null if file doesn't exist or is invalid\n */\nexport function readPackageJson(): PackageJson | null {\n try {\n return JSON.parse(fs.readFileSync('package.json', 'utf8')) as PackageJson\n } catch {\n return null\n }\n}\n\n/**\n * Detect if Tailwind CSS v4 is installed\n * @param pkg - Package.json object\n * @returns True if Tailwind v4 is detected\n */\nexport function detectTailwindV4(pkg: PackageJson): boolean {\n const deps = { ...pkg.dependencies, ...pkg.devDependencies }\n if (deps['@tailwindcss/vite'] || deps['@tailwindcss/postcss']) {\n return true\n }\n if (deps['tailwindcss']) {\n const version = String(deps['tailwindcss'])\n const match = version.match(/(\\d+)/)\n return match ? Number(match[1]) >= 4 : false\n }\n return false\n}\n","import fs from 'fs'\nimport path from 'path'\n\n/**\n * Check if Alpine.js is listed in package.json dependencies\n * @returns True if Alpine.js is found in dependencies\n */\nexport function hasAlpineInPackageJson(): boolean {\n try {\n const pkg = JSON.parse(fs.readFileSync('package.json', 'utf8')) as {\n dependencies?: Readonly<Record<string, string>>\n devDependencies?: Readonly<Record<string, string>>\n }\n const hasInDeps =\n pkg.dependencies &&\n Object.keys(pkg.dependencies).some((dep) =>\n dep.toLowerCase().includes('alpine'),\n )\n const hasInDevDeps =\n pkg.devDependencies &&\n Object.keys(pkg.devDependencies).some((dep) =>\n dep.toLowerCase().includes('alpine'),\n )\n return Boolean(hasInDeps || hasInDevDeps)\n } catch {\n return false\n }\n}\n\n/**\n * Check if Alpine.js is referenced in layout files\n * @returns True if Alpine.js is found in layout files\n */\nexport function hasAlpineInLayouts(): boolean {\n const layoutDir = 'resources/views/layouts'\n if (!fs.existsSync(layoutDir)) return false\n\n try {\n const files = fs.readdirSync(layoutDir, { recursive: true }) as string[]\n for (const file of files) {\n if (file.endsWith('.blade.php')) {\n const content = fs.readFileSync(path.join(layoutDir, file), 'utf8')\n if (content.toLowerCase().includes('alpine')) {\n return true\n }\n }\n }\n } catch {\n return false\n }\n return false\n}\n\n/**\n * Check if Alpine.js is available in the project\n * @returns True if Alpine.js is detected\n */\nexport function hasAlpineJs(): boolean {\n return hasAlpineInPackageJson() || hasAlpineInLayouts()\n}\n","import fs from 'fs'\nimport type { PackageManager } from '../types'\n\n/**\n * Detect the package manager used in the project\n * @returns Detected package manager name (defaults to \"npm\")\n */\nexport function detectPackageManager(): PackageManager {\n // Check lock files\n if (fs.existsSync('pnpm-lock.yaml') || fs.existsSync('pnpm-lock.yml')) {\n return 'pnpm'\n }\n if (fs.existsSync('yarn.lock')) {\n return 'yarn'\n }\n if (fs.existsSync('package-lock.json')) {\n return 'npm'\n }\n if (fs.existsSync('bun.lock')) {\n return 'bun'\n }\n\n // Default to npm\n return 'npm'\n}\n","import fs from 'fs'\nimport type { FileInfo } from '@/src/types'\n\n/**\n * Common CSS file paths to check for main stylesheet\n */\nexport const CSS_CANDIDATES = [\n 'resources/css/app.css',\n 'resources/css/app.scss',\n 'resources/css/main.css',\n 'resources/css/style.css',\n 'resources/css/styles.css',\n] as const\n\n/**\n * Find the main CSS file in the project\n * @returns CSS file info if found, null otherwise\n */\nexport function findMainCss(): FileInfo | null {\n for (const rel of CSS_CANDIDATES) {\n if (fs.existsSync(rel)) {\n return {\n path: rel,\n content: fs.readFileSync(rel, 'utf8'),\n }\n }\n }\n return null\n}\n\n/**\n * Check if CSS content has Tailwind import\n * @param css - CSS content to check\n * @returns True if Tailwind import is found\n */\nexport function hasTailwindImport(css: string): boolean {\n return /@import\\s+[\"']tailwindcss[\"']/.test(css)\n}\n\n/**\n * Inject Velyx CSS import into main CSS file\n * @param cssPath - Path to the CSS file\n * @throws Error if file read/write fails\n */\nexport function injectVelyxImport(cssPath: string): void {\n let content = fs.readFileSync(cssPath, 'utf8')\n if (content.includes('@import \"./velyx.css\"')) {\n return\n }\n if (hasTailwindImport(content)) {\n content = content.replace(\n /@import\\s+[\"']tailwindcss[\"'];?/,\n (match) => `${match}\\n@import \"./velyx.css\";`,\n )\n } else {\n content += '\\n@import \"./velyx.css\";\\n'\n }\n fs.writeFileSync(cssPath, content, 'utf8')\n}\n","import fs from 'fs'\nimport type { FileInfo } from '@/src/types'\n\n/**\n * Common JS file paths to check for main script\n */\nexport const JS_CANDIDATES = [\n 'resources/js/app.js',\n 'resources/js/main.js',\n 'resources/js/index.js',\n] as const\n\n/**\n * Find the main JS file in the project\n * @returns JS file info if found, null otherwise\n */\nexport function findMainJs(): FileInfo | null {\n for (const rel of JS_CANDIDATES) {\n if (fs.existsSync(rel)) {\n return {\n path: rel,\n content: fs.readFileSync(rel, 'utf8'),\n }\n }\n }\n return null\n}\n\n/**\n * Inject component JS import and Alpine initialization into main JS file\n * @param jsPath - Path to the JS file\n * @param componentName - Name of the component\n * @param componentImportPath - Path to import the component from\n * @throws Error if file read/write fails\n */\nexport function injectComponentJs(\n jsPath: string,\n componentName: string,\n componentImportPath: string,\n): void {\n let content = fs.readFileSync(jsPath, 'utf8')\n\n // Avoid duplicate imports\n const importStatement = `import ${componentName} from '${componentImportPath}'`\n if (\n content.includes(importStatement) ||\n content.includes(`import ${componentName} from \"${componentImportPath}\"`)\n ) {\n return\n }\n\n // Add import at the top (after other imports if possible)\n const lines = content.split('\\n')\n let lastImportIndex = -1\n for (let i = 0; i < lines.length; i++) {\n if (lines[i]?.startsWith('import ')) {\n lastImportIndex = i\n }\n }\n\n lines.splice(lastImportIndex + 1, 0, importStatement)\n content = lines.join('\\n')\n\n // Handle Alpine.data registration\n const alpineDataRegistration = `Alpine.data('${componentName}', ${componentName});`\n\n if (content.includes(\"document.addEventListener('alpine:init'\")) {\n // Inject into existing listener\n if (!content.includes(alpineDataRegistration)) {\n content = content.replace(\n /document\\.addEventListener\\('alpine:init',\\s*\\(\\)\\s*=>\\s*\\{/,\n (match) => `${match}\\n ${alpineDataRegistration}`,\n )\n }\n } else {\n // Create new listener at the end\n content += `\\n\\ndocument.addEventListener('alpine:init', () => {\\n ${alpineDataRegistration}\\n});\\n`\n }\n\n fs.writeFileSync(jsPath, content, 'utf8')\n}\n","import fs from 'fs'\nimport path from 'path'\nimport type { VelyxTheme } from '@/src/types'\n\ntype BaseColor = {\n name: VelyxTheme\n label: string\n cssVars: {\n light: Record<string, string>\n dark: Record<string, string>\n }\n}\n\nfunction findColorsDir(startDir: string): string {\n let current = startDir\n for (let depth = 0; depth < 4; depth += 1) {\n const distPath = path.join(current, 'colors')\n if (fs.existsSync(distPath)) {\n return distPath\n }\n\n const srcPath = path.join(current, 'src/colors')\n if (fs.existsSync(srcPath)) {\n return srcPath\n }\n\n const parent = path.dirname(current)\n if (parent === current) {\n break\n }\n current = parent\n }\n\n return path.join(startDir, 'colors')\n}\n\nconst entryDir = process.argv[1]\n ? path.dirname(path.resolve(process.argv[1]))\n : process.cwd()\nconst COLORS_DIR = findColorsDir(entryDir)\n\nfunction loadBaseColors(): BaseColor[] {\n if (!fs.existsSync(COLORS_DIR)) {\n return []\n }\n\n const files = fs\n .readdirSync(COLORS_DIR)\n .filter((file) => file.endsWith('.json'))\n\n return files\n .map((file) => {\n const filePath = path.join(COLORS_DIR, file)\n const raw = fs.readFileSync(filePath, 'utf-8')\n return JSON.parse(raw) as BaseColor\n })\n .filter((color) => !!color?.name)\n .sort((a, b) => a.name.localeCompare(b.name))\n}\n\nexport function getBaseColors(): BaseColor[] {\n return loadBaseColors()\n}\n\nexport function getBaseColor(name: VelyxTheme): BaseColor | undefined {\n return loadBaseColors().find((color) => color.name === name)\n}\n\nfunction renderCssVars(vars: Record<string, string>): string[] {\n return Object.entries(vars).map(([key, value]) => ` --${key}: ${value};`)\n}\n\n/**\n * Copy a theme CSS file to the target location\n * @param theme - Theme name to copy\n * @param target - Target file path\n * @throws Error if theme doesn't exist or copy fails\n */\nexport function copyTheme(theme: VelyxTheme, target: string): void {\n const baseColor = getBaseColor(theme)\n if (!baseColor) {\n throw new Error(`Theme \"${theme}\" not found in colors registry.`)\n }\n\n const lightVars = renderCssVars(baseColor.cssVars.light)\n const darkVars = renderCssVars(baseColor.cssVars.dark)\n\n const content = [\n ':root {',\n ...lightVars,\n '}',\n '',\n '.dark {',\n ...darkVars,\n '}',\n '',\n ].join('\\n')\n\n fs.writeFileSync(target, content, { encoding: 'utf-8', flag: 'wx' })\n}\n","import { cyan, green, red, yellow } from 'kleur/colors'\n\nexport const highlighter = {\n error: red,\n warn: yellow,\n info: cyan,\n success: green,\n}\n","import { highlighter } from '@/src/utils/highlighter'\n\nexport const logger = {\n error(...args: unknown[]) {\n console.log(highlighter.error(args.join(' ')))\n },\n warn(...args: unknown[]) {\n console.log(highlighter.warn(args.join(' ')))\n },\n info(...args: unknown[]) {\n console.log(highlighter.info(args.join(' ')))\n },\n success(...args: unknown[]) {\n console.log(highlighter.success(args.join(' ')))\n },\n log(...args: unknown[]) {\n console.log(args.join(' '))\n },\n break() {\n console.log('')\n },\n}\n","import fs from 'fs'\nimport type { VelyxConfig } from '../types'\nimport { logger } from './logger'\n\n/**\n * Write Velyx configuration to velyx.json file\n * @param config - Configuration object to write\n * @throws Error if file write fails\n */\nexport function writeVelyxConfig(config: VelyxConfig): void {\n fs.writeFileSync('velyx.json', JSON.stringify(config, null, 2) + '\\n', 'utf8')\n}\n\n/**\n * Read Velyx configuration from velyx.json file\n * @returns Configuration object\n * @throws Error if file doesn't exist or is invalid\n */\nexport function readVelyxConfig(): VelyxConfig {\n if (!fs.existsSync('velyx.json')) {\n logger.error('Velyx configuration not found.')\n process.exit(1)\n }\n return JSON.parse(fs.readFileSync('velyx.json', 'utf8')) as VelyxConfig\n}\n","{\n \"name\": \"velyx\",\n \"version\": \"1.0.3\",\n \"description\": \"CLI to add composable UI components to Laravel projects\",\n \"author\": \"\",\n \"license\": \"MIT\",\n \"type\": \"module\",\n \"engines\": {\n \"node\": \">=20\"\n },\n \"bin\": {\n \"velyx\": \"./dist/index.js\"\n },\n \"files\": [\n \"dist\"\n ],\n \"keywords\": [\n \"laravel\",\n \"cli\",\n \"ui\",\n \"blade\",\n \"tailwind\",\n \"alpine\"\n ],\n \"repository\": {\n \"type\": \"git\",\n \"url\": \"https://github.com/velyx-labs/cli.git\"\n },\n \"publishConfig\": {\n \"access\": \"public\"\n },\n \"packageManager\": \"pnpm@10.30.1+sha512.3590e550d5384caa39bd5c7c739f72270234b2f6059e13018f975c313b1eb9fefcc09714048765d4d9efe961382c312e624572c0420762bdc5d5940cdf9be73a\",\n \"pnpm\": {\n \"overrides\": {\n \"cli-spinners\": \"2.9.2\"\n }\n },\n \"scripts\": {\n \"build:dev\": \"cross-env NODE_ENV=development VELYX_REGISTRY_URL=http://velyx.test/api/v1 tsup\",\n \"build\": \"cross-env NODE_ENV=production VELYX_REGISTRY_URL=https://registry.velyx.dev/api/v1 tsup\",\n \"check:ci\": \"pnpm run lint && pnpm run typecheck\",\n \"clean\": \"rimraf dist\",\n \"dev\": \"cross-env NODE_ENV=development VELYX_REGISTRY_URL=http://velyx.test/api/v1 tsup --watch\",\n \"check\": \"pnpm run format:write && eslint --fix\",\n \"format:check\": \"prettier --check \\\"**/*.{ts,tsx,mdx}\\\" --cache\",\n \"format:write\": \"prettier --write \\\"**/*.{ts,tsx,mdx}\\\" --cache\",\n \"lint\": \"eslint\",\n \"prepublishOnly\": \"pnpm run build\",\n \"pub:beta\": \"pnpm build && pnpm publish --no-git-checks --access public --tag beta\",\n \"pub:next\": \"pnpm build && pnpm publish --no-git-checks --access public --tag next\",\n \"pub:release\": \"pnpm build && pnpm publish --access public\",\n \"release\": \"changeset version\",\n \"start\": \"node dist/index.js\",\n \"start:dev\": \"cross-env NODE_ENV=development VELYX_REGISTRY_URL=http://velyx.test/api/v1 node dist/index.js\",\n \"test\": \"vitest run\",\n \"test:coverage\": \"vitest run --coverage\",\n \"test:watch\": \"vitest\",\n \"typecheck\": \"tsc --noEmit\"\n },\n \"dependencies\": {\n \"@clack/prompts\": \"^0.11.0\",\n \"chalk\": \"^5.6.2\",\n \"cli-table3\": \"^0.6.5\",\n \"commander\": \"^14.0.2\",\n \"fs-extra\": \"^11.3.3\",\n \"kleur\": \"^4.1.5\",\n \"log-symbols\": \"^7.0.1\",\n \"ora\": \"^9.1.0\",\n \"prompts\": \"^2.4.2\",\n \"velyx\": \"link:../../../../.local/share/pnpm/global/5/node_modules/velyx\",\n \"vite-tsconfig-paths\": \"^6.0.5\",\n \"zod\": \"^3.24.1\",\n \"zod-to-json-schema\": \"^3.24.6\"\n },\n \"devDependencies\": {\n \"@changesets/cli\": \"^2.29.8\",\n \"@eslint/js\": \"^9.39.2\",\n \"@eslint/json\": \"^0.14.0\",\n \"@eslint/markdown\": \"^7.5.1\",\n \"@types/fs-extra\": \"^11.0.4\",\n \"@types/node\": \"^25.0.9\",\n \"@types/prompts\": \"^2.4.9\",\n \"@vitest/coverage-v8\": \"^4.0.18\",\n \"cross-env\": \"^10.1.0\",\n \"eslint\": \"^9.39.2\",\n \"globals\": \"^17.0.0\",\n \"jiti\": \"^2.6.1\",\n \"prettier\": \"3.8.0\",\n \"rimraf\": \"^6.0.1\",\n \"tsc-alias\": \"^1.8.16\",\n \"tsup\": \"^8.5.0\",\n \"typescript\": \"^5.9.3\",\n \"typescript-eslint\": \"^8.53.0\",\n \"vitest\": \"^4.0.18\"\n }\n}\n","import type {\n VelyxConfig,\n PackageManager,\n VelyxTheme,\n FileInfo,\n} from '@/src/types'\nimport type { IFileSystemService } from '../types/interfaces'\nimport { isLaravelProject } from '../utils/laravel'\nimport { readPackageJson, detectTailwindV4 } from '../utils/tailwind'\nimport { hasAlpineJs } from '../utils/requirements'\nimport { detectPackageManager } from '../utils/package-manager'\nimport { findMainCss, hasTailwindImport, injectVelyxImport } from '../utils/css'\nimport { findMainJs } from '../utils/js'\nimport { copyTheme } from '../utils/theme'\nimport { writeVelyxConfig } from '../utils/config'\nimport fs from 'fs'\nimport { logger } from '../utils/logger'\nimport packageJson from '../../package.json'\n\n/**\n * Environment validation result\n */\nexport interface EnvironmentValidation {\n /** Whether Laravel project is detected */\n isLaravel: boolean\n /** Whether Tailwind v4 is detected */\n hasTailwindV4: boolean\n /** Whether Alpine.js is detected */\n hasAlpine: boolean\n /** Detected package manager */\n detectedPackageManager: PackageManager\n /** Main CSS file info if found */\n cssFile: FileInfo | null\n /** Main JS file info if found */\n jsFile: FileInfo | null\n /** Whether CSS can be injected */\n canInjectCss: boolean\n}\n\n/**\n * Initialization options\n */\nexport interface InitOptions {\n /** Selected package manager */\n packageManager: PackageManager\n /** Selected theme */\n theme: VelyxTheme\n /** Whether to import styles */\n importStyles: boolean\n}\n\n/**\n * Service for handling Velyx initialization\n */\nexport class InitService {\n /**\n * Create a new InitService instance\n * @param fileSystem - File system service\n */\n constructor(private readonly fileSystem: IFileSystemService) {}\n\n /**\n * Validate the project environment\n * @returns Environment validation result\n * @throws Error if critical requirements are not met\n */\n validateEnvironment(): EnvironmentValidation {\n // Validate Laravel project\n if (!isLaravelProject()) {\n throw new Error('No Laravel project detected')\n }\n\n // Check Tailwind v4\n const pkg = readPackageJson()\n if (!pkg || !detectTailwindV4(pkg)) {\n throw new Error('Tailwind CSS v4 was not detected')\n }\n\n // Check interactivity frameworks\n const hasAlpine = hasAlpineJs()\n const detectedPm = detectPackageManager()\n\n // Find CSS and JS files\n const css = findMainCss()\n const js = findMainJs()\n const canInject = css ? hasTailwindImport(css.content) : false\n\n return {\n isLaravel: true,\n hasTailwindV4: true,\n hasAlpine,\n detectedPackageManager: detectedPm,\n cssFile: css,\n jsFile: js,\n canInjectCss: canInject,\n }\n }\n\n /**\n * Display environment information and warnings\n * @param validation - Environment validation result\n */\n displayEnvironmentInfo(validation: EnvironmentValidation): void {\n // Display interactivity framework status\n if (!validation.hasAlpine) {\n logger.warn('Alpine.js not detected')\n logger.log(\n `Install Alpine.js: ${validation.detectedPackageManager} install alpinejs`,\n )\n } else {\n logger.success(\n 'Alpine.js detected - components will be fully interactive',\n )\n }\n\n // Display CSS file status\n if (!validation.cssFile) {\n logger.warn('No main CSS file found')\n logger.log('Styles will be created but not auto-imported')\n } else if (!validation.canInjectCss) {\n logger.warn('Tailwind import not found in CSS')\n logger.log('Velyx styles will not be auto-imported')\n }\n\n // Display JS file status\n if (!validation.jsFile) {\n logger.warn('No main JS file found')\n logger.log('Component scripts will not be auto-imported')\n }\n }\n\n /**\n * Create the UI components directory\n * @param path - Directory path (default: \"resources/views/components/ui\")\n * @returns Promise that resolves when directory is created\n */\n async createComponentsDirectory(\n path = 'resources/views/components/ui',\n ): Promise<void> {\n await this.fileSystem.ensureDir(path)\n }\n\n /**\n * Create the Velyx theme CSS file\n * @param theme - Theme to use\n * @param targetPath - Target CSS file path (default: \"resources/css/velyx.css\")\n * @returns Promise that resolves when theme is created\n * @throws Error if theme creation fails\n */\n async createThemeFile(\n theme: VelyxTheme,\n targetPath = 'resources/css/velyx.css',\n ): Promise<void> {\n // Ensure directory exists\n const dirPath = targetPath.split('/').slice(0, -1).join('/')\n await this.fileSystem.ensureDir(dirPath)\n\n // Create theme file if it doesn't exist\n if (!fs.existsSync(targetPath)) {\n try {\n copyTheme(theme, targetPath)\n logger.success('Velyx theme created')\n logger.info(targetPath)\n } catch (error) {\n throw new Error(\n `Failed to create theme file: ${(error as Error).message}`,\n )\n }\n } else {\n logger.info('velyx.css already exists')\n }\n }\n\n /**\n * Inject Velyx styles import into main CSS file\n * @param cssPath - Path to main CSS file\n * @returns Promise that resolves when import is injected\n */\n async injectStylesImport(cssPath: string): Promise<void> {\n injectVelyxImport(cssPath)\n logger.success('Velyx styles imported')\n logger.info(cssPath)\n }\n\n /**\n * Generate and write Velyx configuration file\n * @param options - Initialization options\n * @param validation - Environment validation result\n * @returns Promise that resolves when config is written\n */\n async generateConfig(\n options: InitOptions,\n validation: EnvironmentValidation,\n ): Promise<void> {\n const config: VelyxConfig = {\n version: packageJson.version as string,\n theme: options.theme,\n packageManager: options.packageManager,\n css: {\n entry: validation.cssFile?.path ?? '',\n velyx: 'resources/css/velyx.css',\n },\n js: {\n entry: validation.jsFile?.path ?? '',\n },\n components: {\n path: 'resources/views/components/ui',\n },\n }\n\n writeVelyxConfig(config)\n logger.success('velyx.json config generated')\n }\n\n /**\n * Display initialization summary\n * @param options - Initialization options\n * @param validation - Environment validation result\n * @param stylesImported - Whether styles were imported\n */\n displaySummary(\n options: InitOptions,\n validation: EnvironmentValidation,\n stylesImported: boolean,\n ): void {\n console.log('\\n---')\n logger.success('Laravel project detected')\n logger.success('Tailwind CSS v4 detected')\n logger.success(`Theme selected: ${options.theme}`)\n logger.success(`Package manager: ${options.packageManager}`)\n logger.success('UI components directory ready')\n if (validation.jsFile) {\n logger.success('Main JS file detected')\n }\n logger.success(\n stylesImported ? 'Styles import complete' : 'Styles import pending',\n )\n logger.success('velyx.json created')\n console.log('\\nNext steps:')\n console.log(' velyx add button')\n console.log(\n '\\nš” Want to customize your Tailwind palette? Try https://tweakcn.com/ ā a visual generator for Tailwind-compatible color scales.',\n )\n }\n}\n","import ora, { type Ora } from 'ora'\n\n/**\n * Utility to manage loading spinners\n */\nexport const spinner = {\n /**\n * Starts a spinner with a message\n * @param message - Message to display\n * @returns Ora spinner instance\n */\n start(message: string): Ora {\n return ora(message).start()\n },\n\n /**\n * Executes an asynchronous task with a spinner\n * @param message - Message during loading\n * @param task - Asynchronous function to execute\n * @param successMessage - Optional success message\n * @param failMessage - Optional error message\n * @returns Task result\n */\n async withTask<T>(\n message: string,\n task: () => Promise<T>,\n successMessage?: string,\n failMessage?: string,\n ): Promise<T> {\n const s = this.start(message)\n try {\n const result = await task()\n if (successMessage) {\n s.succeed(successMessage)\n } else {\n s.stop()\n }\n return result\n } catch (error) {\n s.fail(failMessage || 'Operation failed')\n throw error\n }\n },\n}\n","import { exec } from 'child_process'\nimport path from 'path'\nimport fs from 'fs-extra'\nimport { promisify } from 'util'\nimport { highlighter } from '@/src/utils/highlighter'\nimport { logger } from '@/src/utils/logger'\nimport { spinner } from '@/src/utils/spinner'\nimport prompts from 'prompts'\nimport { detectPackageManager } from '@/src/utils/package-manager'\nimport type { InitOptions } from '@/src/utils/init-project'\nimport type { PackageManager } from '@/src/types'\n\nconst execAsync = promisify(exec)\n\nexport interface ProjectInfo {\n name: string\n framework: {\n name: string\n label: string\n version?: string\n }\n hasAlpine: boolean\n hasVite: boolean\n packageManager: PackageManager\n paths: {\n views: string\n assets: string\n public: string\n config: string\n }\n}\n\nexport async function getProjectInfo(cwd: string): Promise<ProjectInfo | null> {\n try {\n const composerPath = path.resolve(cwd, 'composer.json')\n const packagePath = path.resolve(cwd, 'package.json')\n\n if (!fs.existsSync(composerPath)) {\n return null\n }\n\n const composer = await fs.readJson(composerPath)\n const isLaravel =\n composer.require?.['laravel/framework'] ||\n composer.require?.['illuminate/foundation']\n\n if (!isLaravel) {\n return null\n }\n\n // DĆ©tecter le package manager\n const originalDir = process.cwd()\n process.chdir(cwd)\n const pkgManager = detectPackageManager()\n console.log(`Detected package manager: ${pkgManager}`)\n process.chdir(originalDir)\n\n const projectInfo: ProjectInfo = {\n name: composer.name || path.basename(cwd),\n framework: {\n name: 'laravel',\n label: 'Laravel',\n version: composer.require?.['laravel/framework'] || 'unknown',\n },\n hasAlpine: false,\n hasVite: false,\n packageManager: pkgManager,\n paths: {\n views: 'resources/views',\n assets: 'resources/js',\n public: 'public',\n config: 'config',\n },\n }\n\n // VĆ©rifier les dĆ©pendances frontend\n if (fs.existsSync(packagePath)) {\n const pkg = await fs.readJson(packagePath)\n projectInfo.hasAlpine = !!(\n pkg.dependencies?.alpinejs || pkg.devDependencies?.alpinejs\n )\n projectInfo.hasVite = !!pkg.devDependencies?.vite\n }\n\n // VĆ©rifier la structure des dossiers\n const viewsPath = path.resolve(cwd, 'resources/views')\n const assetsPath = path.resolve(cwd, 'resources/js')\n\n if (fs.existsSync(viewsPath)) {\n projectInfo.paths.views = 'resources/views'\n }\n\n if (fs.existsSync(assetsPath)) {\n projectInfo.paths.assets = 'resources/js'\n }\n\n return projectInfo\n } catch {\n return null\n }\n}\n\nexport async function preFlightInit(options: InitOptions): Promise<{\n errors: Record<string, boolean>\n projectInfo: ProjectInfo | null\n}> {\n const errors: Record<string, boolean> = {}\n\n // VĆ©rifier si le rĆ©pertoire existe\n if (!fs.existsSync(options.cwd)) {\n errors['MISSING_DIR'] = true\n return { errors, projectInfo: null }\n }\n\n const projectSpinner = spinner.start('Checking project environment...')\n\n // VĆ©rifier si velyx.json existe dĆ©jĆ \n const velyxConfigPath = path.resolve(options.cwd, 'velyx.json')\n if (fs.existsSync(velyxConfigPath) && !options.force) {\n projectSpinner.fail()\n logger.break()\n\n const { action } = await prompts({\n type: 'select',\n name: 'action',\n message: `A ${highlighter.info('velyx.json')} file already exists. What would you like to do?`,\n choices: [\n {\n title: 'Re-initialize Velyx configuration',\n value: 'reinit',\n },\n {\n title: 'Keep existing configuration',\n value: 'keep',\n },\n {\n title: 'Exit',\n value: 'exit',\n },\n ],\n initial: 0,\n })\n\n if (action === 'exit') {\n logger.log('Operation cancelled.')\n process.exit(0)\n }\n\n if (action === 'keep') {\n logger.log('Keeping existing configuration.')\n process.exit(0)\n }\n\n // Continue with re-initialization\n logger.log(`Re-initializing Velyx configuration...`)\n }\n\n // RĆ©cupĆ©rer les infos du projet\n const projectInfo = await getProjectInfo(options.cwd)\n\n if (!projectInfo || projectInfo.framework.name !== 'laravel') {\n errors['UNSUPPORTED_PROJECT'] = true\n projectSpinner.fail()\n logger.break()\n logger.error(\n `We could not detect a supported Laravel project at ${highlighter.info(\n options.cwd,\n )}.\\nVelyx is designed to work with Laravel projects.`,\n )\n logger.break()\n process.exit(1)\n }\n\n projectSpinner.succeed(\n `Found ${highlighter.info(projectInfo.framework.label)} project`,\n )\n\n // VĆ©rifier Alpine.js\n const alpineSpinner = spinner.start('Checking Alpine.js...')\n\n if (!projectInfo.hasAlpine) {\n alpineSpinner.fail()\n logger.break()\n logger.warn(`Alpine.js is required but not found in your project.`)\n\n // Proposer d'installer Alpine.js directement\n const { installAlpine } = await prompts({\n type: 'confirm',\n name: 'installAlpine',\n message: 'Would you like to install Alpine.js now?',\n initial: true,\n })\n\n if (installAlpine) {\n // Installer Alpine.js avec le package manager dĆ©tectĆ©\n const pkgManager = projectInfo.packageManager\n const installSpinner = spinner.start(\n `Installing Alpine.js with ${pkgManager}...`,\n )\n\n try {\n await execAsync(`${pkgManager} install alpinejs`, {\n cwd: options.cwd,\n })\n installSpinner.succeed('Alpine.js installed successfully')\n projectInfo.hasAlpine = true\n } catch (error) {\n installSpinner.fail(\n `Failed to install Alpine.js: ${(error as Error).message}`,\n )\n logger.error(\n `Please install Alpine.js manually: ${highlighter.info(`${pkgManager} install alpinejs`)}`,\n )\n logger.break()\n process.exit(1)\n }\n } else {\n const pkgManager = projectInfo.packageManager\n logger.error(\n `Alpine.js is required. Install it with: ${highlighter.info(`${pkgManager} install alpinejs`)}`,\n )\n logger.break()\n process.exit(1)\n }\n } else {\n alpineSpinner.succeed('Alpine.js found')\n }\n\n // VĆ©rifier Vite (recommandĆ© pour Velyx)\n const viteSpinner = spinner.start('Checking build tools...')\n\n if (!projectInfo.hasVite) {\n logger.warn(\n `Vite not found. Using Vite is recommended for better development experience.`,\n )\n viteSpinner.warn('Vite not found (but optional)')\n } else {\n viteSpinner.succeed('Vite found')\n }\n\n // Afficher les erreurs bloquantes\n if (Object.keys(errors).length > 0) {\n logger.break()\n process.exit(1)\n }\n\n return { errors, projectInfo }\n}\n","import prompts from 'prompts'\nimport { FilesystemService } from '@/src/services/filesystem-service'\nimport { InitService } from '@/src/services/init-service'\nimport { preFlightInit, type ProjectInfo } from '@/src/utils/preflight-init'\nimport { getBaseColors } from '@/src/utils/theme'\nimport { logger } from '@/src/utils/logger'\nimport { highlighter } from '@/src/utils/highlighter'\nimport type { VelyxTheme } from '@/src/types'\nimport { z } from 'zod'\n\nexport const initOptionsSchema = z.object({\n baseColor: z.string().optional(),\n yes: z.boolean(),\n defaults: z.boolean(),\n force: z.boolean(),\n cwd: z.string(),\n silent: z.boolean(),\n})\n\nexport type InitOptions = z.infer<typeof initOptionsSchema>\n\nasync function promptTheme(): Promise<VelyxTheme> {\n const baseColors = getBaseColors()\n if (baseColors.length === 0) {\n logger.error('No base colors available.')\n process.exit(1)\n }\n const { theme } = await prompts(\n {\n type: 'select',\n name: 'theme',\n message: 'Choose a base color theme',\n choices: baseColors.map((color) => ({\n title: color.label,\n value: color.name,\n })),\n },\n {\n onCancel: () => {\n logger.error('Theme selection aborted')\n process.exit(1)\n },\n },\n )\n\n return theme as VelyxTheme\n}\n\nasync function promptStyleImport(): Promise<boolean> {\n const { shouldImport } = await prompts(\n {\n type: 'confirm',\n name: 'shouldImport',\n message: 'Import Velyx styles into your main CSS file?',\n initial: true,\n },\n {\n onCancel: () => false,\n },\n )\n\n return Boolean(shouldImport)\n}\n\nfunction resolveThemeFromOptions(options: InitOptions): VelyxTheme | undefined {\n if (!options.baseColor) {\n return undefined\n }\n\n const baseColors = getBaseColors()\n const matched = baseColors.find((color) => color.name === options.baseColor)\n if (matched) {\n return matched.name\n }\n\n logger.warn(`Unknown base color \"${options.baseColor}\".`)\n return undefined\n}\n\nexport async function initProject(\n options: InitOptions,\n projectInfo?: ProjectInfo | null,\n): Promise<void> {\n // Use provided projectInfo or run preflight checks\n if (!projectInfo) {\n const preflight = await preFlightInit(options)\n projectInfo = preflight.projectInfo\n }\n\n process.chdir(options.cwd)\n\n const fileSystem = new FilesystemService()\n const initService = new InitService(fileSystem)\n\n try {\n const validation = initService.validateEnvironment()\n initService.displayEnvironmentInfo(validation)\n\n // Use the package manager already detected in preflight checks\n const packageManager = projectInfo!.packageManager\n\n const baseColors = getBaseColors()\n const defaultTheme =\n baseColors.find((color) => color.name === 'neutral')?.name ??\n baseColors[0]?.name\n\n let theme = resolveThemeFromOptions(options)\n if (!theme) {\n theme =\n options.defaults && defaultTheme ? defaultTheme : await promptTheme()\n }\n\n if (!theme) {\n logger.error('No base color available.')\n process.exit(1)\n }\n\n await initService.createComponentsDirectory()\n await initService.createThemeFile(theme)\n\n let stylesImported = false\n if (validation.cssFile && validation.canInjectCss) {\n if (options.defaults || (await promptStyleImport())) {\n await initService.injectStylesImport(validation.cssFile.path)\n stylesImported = true\n }\n }\n\n await initService.generateConfig(\n {\n packageManager,\n theme,\n importStyles: stylesImported,\n },\n validation,\n )\n\n initService.displaySummary(\n {\n packageManager,\n theme,\n importStyles: stylesImported,\n },\n validation,\n stylesImported,\n )\n } catch (error) {\n logger.error((error as Error).message)\n if (error instanceof Error) {\n if (error.message.includes('Laravel project')) {\n logger.log('Run velyx init at the root of a Laravel project')\n } else if (error.message.includes('Tailwind')) {\n logger.log(`Velyx requires ${highlighter.info('Tailwind CSS v4+')}`)\n }\n }\n process.exit(1)\n }\n}\n","import { Command } from 'commander'\nimport path from 'path'\nimport { deleteFileBackup, restoreFileBackup } from '@/src/utils/file-helper'\nimport { initOptionsSchema, initProject } from '@/src/utils/init-project'\n\nprocess.on('exit', (code) => {\n const filePath = path.resolve(process.cwd(), 'velyx.json')\n\n // Delete backup if successful.\n if (code === 0) {\n return deleteFileBackup(filePath)\n }\n\n // Restore backup if error.\n return restoreFileBackup(filePath)\n})\n\nexport const init = new Command()\n .name('init')\n .description('initialize your project and install dependencies')\n .option(\n '-b, --base-color <base-color>',\n 'the base color to use. (neutral, gray, zinc, stone, slate)',\n undefined,\n )\n .option('-y, --yes', 'skip confirmation prompt.', true)\n .option('-d, --defaults', 'use default configuration.', false)\n .option('-f, --force', 'force overwrite of existing configuration.', false)\n .option(\n '-c, --cwd <cwd>',\n 'the working directory. defaults to the current directory.',\n process.cwd(),\n )\n .option('-s, --silent', 'mute output.', false)\n .action(async (opts) => {\n const options = initOptionsSchema.parse({\n baseColor: opts.baseColor,\n yes: Boolean(opts.yes),\n defaults: Boolean(opts.defaults),\n force: Boolean(opts.force),\n cwd: path.resolve(opts.cwd),\n silent: Boolean(opts.silent),\n })\n\n await initProject(options)\n })\n","/**\n * Custom error class for Velyx-specific errors with code and context\n */\nexport class VelyxError extends Error {\n /**\n * Create a new VelyxError\n * @param message - Error message\n * @param code - Error code for categorization\n * @param context - Additional context data\n */\n constructor(\n message: string,\n public readonly code: string,\n public readonly context?: Readonly<Record<string, unknown>>,\n ) {\n super(message)\n this.name = 'VelyxError'\n }\n}\n\n/**\n * Handles and formats errors for display\n */\nexport class ErrorHandler {\n /**\n * Handle an error and display it appropriately\n * @param error - Error to handle\n * @param context - Context where the error occurred\n */\n handle(error: Error, context: string): void {\n if (error instanceof VelyxError) {\n console.error(`[${error.code}] ${error.message}`)\n if (error.context) {\n console.error('Context:', error.context)\n }\n } else {\n console.error(`Unexpected error in ${context}: ${error.message}`)\n }\n\n // Don't exit here, let the caller handle it\n }\n}\n","import { z } from 'zod'\n\n// Error codes for programmatic error handling\nexport const RegistryErrorCode = {\n // Network errors\n NETWORK_ERROR: 'NETWORK_ERROR',\n NOT_FOUND: 'NOT_FOUND',\n UNAUTHORIZED: 'UNAUTHORIZED',\n FORBIDDEN: 'FORBIDDEN',\n FETCH_ERROR: 'FETCH_ERROR',\n\n // Configuration errors\n NOT_CONFIGURED: 'NOT_CONFIGURED',\n INVALID_CONFIG: 'INVALID_CONFIG',\n MISSING_ENV_VARS: 'MISSING_ENV_VARS',\n\n // File system errors\n LOCAL_FILE_ERROR: 'LOCAL_FILE_ERROR',\n\n // Parsing errors\n PARSE_ERROR: 'PARSE_ERROR',\n VALIDATION_ERROR: 'VALIDATION_ERROR',\n\n // Generic errors\n UNKNOWN_ERROR: 'UNKNOWN_ERROR',\n} as const\n\nexport type RegistryErrorCode =\n (typeof RegistryErrorCode)[keyof typeof RegistryErrorCode]\n\nexport class RegistryError extends Error {\n public readonly code: RegistryErrorCode\n public readonly statusCode?: number\n public readonly context?: Record<string, unknown>\n public readonly suggestion?: string\n public readonly timestamp: Date\n public readonly cause?: unknown\n\n constructor(\n message: string,\n options: {\n code?: RegistryErrorCode\n statusCode?: number\n cause?: unknown\n context?: Record<string, unknown>\n suggestion?: string\n } = {},\n ) {\n super(message)\n this.name = 'RegistryError'\n this.code = options.code || RegistryErrorCode.UNKNOWN_ERROR\n this.statusCode = options.statusCode\n this.cause = options.cause\n this.context = options.context\n this.suggestion = options.suggestion\n this.timestamp = new Date()\n\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor)\n }\n }\n\n toJSON() {\n return {\n name: this.name,\n message: this.message,\n code: this.code,\n statusCode: this.statusCode,\n context: this.context,\n suggestion: this.suggestion,\n timestamp: this.timestamp,\n stack: this.stack,\n }\n }\n}\n\nexport class RegistryNotFoundError extends RegistryError {\n constructor(\n public readonly url: string,\n cause?: unknown,\n ) {\n const message = `The item at ${url} was not found. It may not exist at the registry.`\n\n super(message, {\n code: RegistryErrorCode.NOT_FOUND,\n statusCode: 404,\n cause,\n context: { url },\n suggestion:\n 'Check if the item name is correct and the registry URL is accessible.',\n })\n this.name = 'RegistryNotFoundError'\n }\n}\n\nexport class RegistryUnauthorizedError extends RegistryError {\n constructor(\n public readonly url: string,\n cause?: unknown,\n ) {\n const message = `You are not authorized to access the item at ${url}. If this is a remote registry, you may need to authenticate.`\n\n super(message, {\n code: RegistryErrorCode.UNAUTHORIZED,\n statusCode: 401,\n cause,\n context: { url },\n suggestion:\n 'Check your authentication credentials and environment variables.',\n })\n this.name = 'RegistryUnauthorizedError'\n }\n}\n\nexport class RegistryForbiddenError extends RegistryError {\n constructor(\n public readonly url: string,\n cause?: unknown,\n ) {\n const message = `You are not authorized to access the item at ${url}. If this is a remote registry, you may need to authenticate.`\n\n super(message, {\n code: RegistryErrorCode.FORBIDDEN,\n statusCode: 403,\n cause,\n context: { url },\n suggestion:\n 'Check your authentication credentials and environment variables.',\n })\n this.name = 'RegistryForbiddenError'\n }\n}\n\nexport class RegistryFetchError extends RegistryError {\n constructor(\n public readonly url: string,\n statusCode?: number,\n public readonly responseBody?: string,\n cause?: unknown,\n ) {\n // Use the error detail from the server if available\n const baseMessage = statusCode\n ? `Failed to fetch from registry (${statusCode}): ${url}`\n : `Failed to fetch from registry: ${url}`\n\n const message =\n typeof cause === 'string' && cause\n ? `${baseMessage} - ${cause}`\n : baseMessage\n\n let suggestion = 'Check your network connection and try again.'\n if (statusCode === 404) {\n suggestion =\n 'The requested resource was not found. Check the URL or item name.'\n } else if (statusCode === 500) {\n suggestion = 'The registry server encountered an error. Try again later.'\n } else if (statusCode && statusCode >= 400 && statusCode < 500) {\n suggestion = 'There was a client error. Check your request parameters.'\n }\n\n super(message, {\n code: RegistryErrorCode.FETCH_ERROR,\n statusCode,\n cause,\n context: { url, responseBody },\n suggestion,\n })\n this.name = 'RegistryFetchError'\n }\n}\n\nexport class RegistryNotConfiguredError extends RegistryError {\n constructor(public readonly registryName: string | null) {\n const message = registryName\n ? `Unknown registry \"${registryName}\". Make sure it is defined in components.json as follows:\n{\n \"registries\": {\n \"${registryName}\": \"[URL_TO_REGISTRY]\"\n }\n}`\n : `Unknown registry. Make sure it is defined in components.json under \"registries\".`\n\n super(message, {\n code: RegistryErrorCode.NOT_CONFIGURED,\n context: { registryName },\n suggestion:\n 'Add the registry configuration to your components.json file. Consult the registry documentation for the correct format.',\n })\n this.name = 'RegistryNotConfiguredError'\n }\n}\n\nexport class RegistryLocalFileError extends RegistryError {\n constructor(\n public readonly filePath: string,\n cause?: unknown,\n ) {\n super(`Failed to read local registry file: ${filePath}`, {\n code: RegistryErrorCode.LOCAL_FILE_ERROR,\n cause,\n context: { filePath },\n suggestion: 'Check if the file exists and you have read permissions.',\n })\n this.name = 'RegistryLocalFileError'\n }\n}\n\nexport class RegistryParseError extends RegistryError {\n public readonly parseError: unknown\n\n constructor(\n public readonly item: string,\n parseError: unknown,\n ) {\n let message = `Failed to parse registry item: ${item}`\n\n if (parseError instanceof z.ZodError) {\n message = `Failed to parse registry item: ${item}\\n${parseError.errors\n .map((e) => ` - ${e.path.join('.')}: ${e.message}`)\n .join('\\n')}`\n }\n\n super(message, {\n code: RegistryErrorCode.PARSE_ERROR,\n cause: parseError,\n context: { item },\n suggestion:\n 'The registry item may be corrupted or have an invalid format. Please make sure it returns a valid JSON object. See https://ui.shadcn.com/schema/registry-item.json.',\n })\n\n this.parseError = parseError\n this.name = 'RegistryParseError'\n }\n}\n\nexport class RegistryMissingEnvironmentVariablesError extends RegistryError {\n constructor(\n public readonly registryName: string,\n public readonly missingVars: string[],\n ) {\n const message =\n `Registry \"${registryName}\" requires the following environment variables:\\n\\n` +\n missingVars.map((v) => ` ⢠${v}`).join('\\n')\n\n super(message, {\n code: RegistryErrorCode.MISSING_ENV_VARS,\n context: { registryName, missingVars },\n suggestion:\n 'Set the required environment variables to your .env or .env.local file.',\n })\n this.name = 'RegistryMissingEnvironmentVariablesError'\n }\n}\n\nexport class RegistryInvalidNamespaceError extends RegistryError {\n constructor(public readonly name: string) {\n const message = `Invalid registry namespace: \"${name}\". Registry names must start with @ (e.g., @shadcn, @v0).`\n\n super(message, {\n code: RegistryErrorCode.VALIDATION_ERROR,\n context: { name },\n suggestion:\n 'Use a valid registry name starting with @ or provide a direct URL to the registry.',\n })\n this.name = 'RegistryInvalidNamespaceError'\n }\n}\n\nexport class ConfigMissingError extends RegistryError {\n constructor(public readonly cwd: string) {\n const message = `No components.json found in ${cwd} or parent directories.`\n\n super(message, {\n code: RegistryErrorCode.NOT_CONFIGURED,\n context: { cwd },\n suggestion:\n \"Run 'npx shadcn@latest init' to create a components.json file, or check that you're in the correct directory.\",\n })\n this.name = 'ConfigMissingError'\n }\n}\n\nexport class ConfigParseError extends RegistryError {\n constructor(\n public readonly cwd: string,\n parseError: unknown,\n ) {\n let message = `Invalid components.json configuration in ${cwd}.`\n\n if (parseError instanceof z.ZodError) {\n message = `Invalid components.json configuration in ${cwd}:\\n${parseError.errors\n .map((e) => ` - ${e.path.join('.')}: ${e.message}`)\n .join('\\n')}`\n }\n\n super(message, {\n code: RegistryErrorCode.INVALID_CONFIG,\n cause: parseError,\n context: { cwd },\n suggestion:\n \"Check your components.json file for syntax errors or invalid configuration. Run 'npx shadcn@latest init' to regenerate a valid configuration.\",\n })\n this.name = 'ConfigParseError'\n }\n}\n\nexport class RegistriesIndexParseError extends RegistryError {\n public readonly parseError: unknown\n\n constructor(parseError: unknown) {\n let message = 'Failed to parse registries index'\n\n if (parseError instanceof z.ZodError) {\n const invalidNamespaces = parseError.errors\n .filter((e) => e.path.length > 0)\n .map((e) => `\"${e.path[0]}\"`)\n .filter((v, i, arr) => arr.indexOf(v) === i) // remove duplicates\n\n if (invalidNamespaces.length > 0) {\n message = `Failed to parse registries index. Invalid registry namespace(s): ${invalidNamespaces.join(\n ', ',\n )}\\n${parseError.errors\n .map((e) => ` - ${e.path.join('.')}: ${e.message}`)\n .join('\\n')}`\n } else {\n message = `Failed to parse registries index:\\n${parseError.errors\n .map((e) => ` - ${e.path.join('.')}: ${e.message}`)\n .join('\\n')}`\n }\n }\n\n super(message, {\n code: RegistryErrorCode.PARSE_ERROR,\n cause: parseError,\n context: { parseError },\n suggestion:\n 'The registries index may be corrupted or have invalid registry namespace format. Registry names must start with @ (e.g., @shadcn, @example).',\n })\n\n this.parseError = parseError\n this.name = 'RegistriesIndexParseError'\n }\n}\n\nexport class InvalidConfigIconLibraryError extends RegistryError {\n constructor(\n public readonly iconLibrary: string,\n public readonly validOptions: string[],\n ) {\n const message = `Invalid icon library \"${iconLibrary}\". Valid options are: ${validOptions.join(\n ', ',\n )}`\n\n super(message, {\n code: RegistryErrorCode.INVALID_CONFIG,\n context: { iconLibrary, validOptions },\n suggestion: `Update the \"iconLibrary\" field in your components.json to one of: ${validOptions.join(\n ', ',\n )}`,\n })\n this.name = 'InvalidConfigIconLibraryError'\n }\n}\n\nexport const MISSING_DIR_OR_EMPTY_PROJECT = '1'\nexport const EXISTING_CONFIG = '2'\nexport const MISSING_CONFIG = '3'\nexport const FAILED_CONFIG_READ = '4'\nexport const TAILWIND_NOT_CONFIGURED = '5'\nexport const IMPORT_ALIAS_MISSING = '6'\nexport const UNSUPPORTED_FRAMEWORK = '7'\nexport const COMPONENT_URL_NOT_FOUND = '8'\nexport const COMPONENT_URL_UNAUTHORIZED = '9'\nexport const COMPONENT_URL_FORBIDDEN = '10'\nexport const COMPONENT_URL_BAD_REQUEST = '11'\nexport const COMPONENT_URL_INTERNAL_SERVER_ERROR = '12'\nexport const BUILD_MISSING_REGISTRY_FILE = '13'\nexport const INVALID_CONFIG_ICON_LIBRARY = '14'\n","import { RegistryError } from '@/src/utils/errors'\nimport { highlighter } from '@/src/utils/highlighter'\nimport { logger } from '@/src/utils/logger'\nimport { z } from 'zod'\n\nexport function handleError(error: unknown): void {\n logger.break()\n logger.error(\n `Something went wrong. Please check the error below for more details.`,\n )\n logger.error(`If the problem persists, please open an issue on GitHub.`)\n logger.error('')\n if (typeof error === 'string') {\n logger.error(error)\n logger.break()\n process.exit(1)\n }\n\n if (error instanceof RegistryError) {\n if (error.message) {\n logger.error(error.cause ? 'Error:' : 'Message:')\n logger.error(error.message)\n }\n\n if (error.cause) {\n logger.error('\\nMessage:')\n logger.error(error.cause)\n }\n\n if (error.suggestion) {\n logger.error('\\nSuggestion:')\n logger.error(error.suggestion)\n }\n logger.break()\n process.exit(1)\n }\n\n if (error instanceof z.ZodError) {\n logger.error('Validation failed:')\n for (const [key, value] of Object.entries(error.flatten().fieldErrors)) {\n logger.error(`- ${highlighter.info(key)}: ${value}`)\n }\n logger.break()\n process.exit(1)\n }\n\n if (error instanceof Error) {\n logger.error(error.message)\n logger.break()\n process.exit(1)\n }\n\n logger.break()\n process.exit(1)\n}\n","import type { VelyxConfig, PackageManager, VelyxTheme } from '@/src/types'\nimport type { IConfigManager } from '@/src/types/interfaces'\nimport { readVelyxConfig } from '@/src/utils/config'\nimport { logger } from '@/src/utils/logger'\nimport { handleError } from '@/src/utils/handle-error'\n\n/**\n * Manages Velyx configuration loading and access\n */\nexport class ConfigManager implements IConfigManager {\n private config?: VelyxConfig\n\n /**\n * Load configuration from file\n * @returns Promise resolving to configuration\n * @throws Error if configuration not found or invalid\n */\n async load(): Promise<VelyxConfig> {\n try {\n this.config = readVelyxConfig()\n if (!this.config) {\n logger.error('')\n handleError(new Error('Configuration not found'))\n process.exit(1)\n }\n return this.config\n } catch {\n logger.error('')\n handleError(new Error('Something went wrong. Please try again.'))\n process.exit(1)\n }\n }\n\n /**\n * Get the package manager from config\n * @returns Package manager name\n * @throws Error if config not loaded\n */\n getPackageManager(): PackageManager {\n if (!this.config) {\n throw new Error('Configuration not loaded')\n }\n return (this.config.packageManager || 'npm') as PackageManager\n }\n\n /**\n * Validate that configuration is loaded\n * @returns True if configuration is valid\n */\n validate(): boolean {\n return !!this.config\n }\n\n /**\n * Get the components path from config\n * @returns Components directory path\n * @throws Error if config not loaded\n */\n getComponentsPath(): string {\n if (!this.config) {\n throw new Error('Configuration not loaded')\n }\n return this.config.components.path\n }\n\n /**\n * Get the theme CSS path from config\n * @returns Theme CSS file path\n * @throws Error if config not loaded\n */\n getThemePath(): string {\n if (!this.config) {\n throw new Error('Configuration not loaded')\n }\n return this.config.css.velyx\n }\n\n /**\n * Get the JS entry path from config\n * @returns JS entry file path\n * @throws Error if config not loaded\n */\n getJsEntryPath(): string {\n if (!this.config) {\n throw new Error('Configuration not loaded')\n }\n return this.config.js?.entry ?? ''\n }\n\n /**\n * Get the selected theme from config\n * @returns Theme name\n * @throws Error if config not loaded\n */\n getTheme(): VelyxTheme {\n if (!this.config) {\n throw new Error('Configuration not loaded')\n }\n return this.config.theme as VelyxTheme\n }\n}\n","import { exec } from 'child_process'\nimport { promisify } from 'util'\nimport type { PackageManager, VelyxDependency } from '@/src/types'\nimport type { IDependencyService } from '@/src/types/interfaces'\nimport { logger } from '@/src/utils/logger'\nimport { FilesystemService } from './filesystem-service'\n\nconst execAsync = promisify(exec)\n\n/**\n * Convert npm-style dependency string to Composer format\n * @param dep - Dependency string in npm format (e.g., \"vendor/package@1.0.0\")\n * @returns Dependency string in Composer format (e.g., \"vendor/package:1.0.0\")\n */\nfunction convertNpmToComposerFormat(dep: string): string {\n // Replace @ with : for version constraint\n // But only if it's not a scoped package (starting with @)\n if (dep.startsWith('@')) {\n // Scoped npm package like @alpinejs/alpinejs - return as-is for npm\n return dep\n }\n // Replace @ with : for Composer packages\n return dep.replace('@', ':')\n}\n\n/**\n * Service for managing dependency installation\n */\nexport class DependencyService implements IDependencyService {\n private readonly fileSystem: FilesystemService\n\n constructor(fileSystem?: FilesystemService) {\n this.fileSystem = fileSystem ?? new FilesystemService()\n }\n\n /**\n * Install component dependencies using appropriate package managers\n * @param dependencies - Dependencies to install\n * @param packageManager - Package manager to use for npm dependencies\n * @returns Promise that resolves when installation is complete\n */\n async installDependencies(\n dependencies: VelyxDependency,\n packageManager: PackageManager,\n ): Promise<void> {\n const npmPromises = []\n const composerPromises = []\n\n // Install npm dependencies\n if (dependencies.npm && dependencies.npm.length > 0) {\n npmPromises.push(\n this.installNpmDependencies(dependencies.npm, packageManager),\n )\n }\n\n // Install composer dependencies\n if (dependencies.composer && dependencies.composer.length > 0) {\n composerPromises.push(\n this.installComposerDependencies(dependencies.composer),\n )\n }\n\n // Execute installations in parallel\n await Promise.allSettled([...npmPromises, ...composerPromises])\n }\n\n /**\n * Install npm/yarn/pnpm/bun dependencies\n * @param dependencies - Array of dependency strings (e.g., \"alpinejs@^3.14.0\")\n * @param packageManager - Package manager to use\n * @returns Promise that resolves when installation is complete\n */\n async installNpmDependencies(\n dependencies: readonly string[],\n packageManager: PackageManager,\n ): Promise<void> {\n if (!this.fileSystem.fileExists('package.json')) {\n logger.warn('No package.json found, skipping npm dependencies')\n return\n }\n\n const missingDeps = await this.filterMissingNpmDependencies(dependencies)\n\n if (missingDeps.length === 0) {\n logger.info('All npm dependencies already installed')\n return\n }\n\n const command = this.getNpmInstallCommand(packageManager, missingDeps)\n\n try {\n logger.info(`Installing npm dependencies: ${missingDeps.join(', ')}`)\n\n const { stdout, stderr } = await execAsync(command, {\n cwd: process.cwd(),\n timeout: 120000, // 2 minutes timeout\n })\n\n if (stdout && process.env.NODE_ENV !== 'test') {\n console.log(stdout)\n }\n\n if (stderr && !stderr.includes('WARN')) {\n logger.warn(`npm install warnings: ${stderr}`)\n }\n\n logger.success(`Installed ${missingDeps.length} npm dependencies`)\n } catch (error) {\n logger.error(\n `Failed to install npm dependencies: ${(error as Error).message}`,\n )\n throw error\n }\n }\n\n /**\n * Install composer dependencies\n * @param dependencies - Array of dependency strings (e.g., \"livewire/livewire:^3.0\" or \"livewire/livewire@^3.0\")\n * @returns Promise that resolves when installation is complete\n */\n async installComposerDependencies(\n dependencies: readonly string[],\n ): Promise<void> {\n if (!this.fileSystem.fileExists('composer.json')) {\n logger.warn('No composer.json found, skipping composer dependencies')\n return\n }\n\n // Convert npm format (@) to Composer format (:) if needed\n const convertedDeps = dependencies.map(convertNpmToComposerFormat)\n\n const missingDeps =\n await this.filterMissingComposerDependencies(convertedDeps)\n\n if (missingDeps.length === 0) {\n logger.info('All composer dependencies already installed')\n return\n }\n\n try {\n logger.info(`Installing composer dependencies: ${missingDeps.join(', ')}`)\n\n const { stdout, stderr } = await execAsync(\n `composer require ${missingDeps.join(' ')}`,\n {\n cwd: process.cwd(),\n timeout: 300000, // 5 minutes timeout for composer\n },\n )\n\n if (stdout && process.env.NODE_ENV !== 'test') {\n console.log(stdout)\n }\n\n if (stderr) {\n logger.warn(`composer require warnings: ${stderr}`)\n }\n\n logger.success(`Installed ${missingDeps.length} composer dependencies`)\n } catch (error) {\n logger.error(\n `Failed to install composer dependencies: ${(error as Error).message}`,\n )\n throw error\n }\n }\n\n /**\n * Get the appropriate npm install command based on package manager\n * @param packageManager - Package manager to use\n * @param dependencies - Dependencies array\n * @returns Command string\n */\n private getNpmInstallCommand(\n packageManager: PackageManager,\n dependencies: readonly string[],\n ): string {\n switch (packageManager) {\n case 'pnpm':\n return `pnpm add ${dependencies.join(' ')}`\n case 'yarn':\n return `yarn add ${dependencies.join(' ')}`\n case 'bun':\n return `bun add ${dependencies.join(' ')}`\n case 'npm':\n default:\n return `npm install ${dependencies.join(' ')}`\n }\n }\n\n /**\n * Filter out npm dependencies that are already installed\n * @param dependencies - Dependencies to check\n * @returns Array of missing dependencies\n */\n private async filterMissingNpmDependencies(\n dependencies: readonly string[],\n ): Promise<string[]> {\n try {\n const { stdout } = await execAsync('npm list --json --depth=0', {\n cwd: process.cwd(),\n timeout: 30000,\n })\n\n const installed = JSON.parse(stdout) as Record<string, any>\n const installedDeps = Object.keys({\n ...installed.dependencies,\n ...installed.devDependencies,\n })\n\n return dependencies.filter((dep) => {\n const name = dep.split('@')[0]\n return !installedDeps.includes(name)\n })\n } catch {\n // If we can't check, assume all need to be installed\n return dependencies as string[]\n }\n }\n\n /**\n * Filter out composer dependencies that are already installed\n * @param dependencies - Dependencies to check\n * @returns Array of missing dependencies\n */\n private async filterMissingComposerDependencies(\n dependencies: readonly string[],\n ): Promise<string[]> {\n try {\n const { stdout } = await execAsync(\n 'composer show --installed --format=json',\n {\n cwd: process.cwd(),\n timeout: 30000,\n },\n )\n\n const installed = JSON.parse(stdout) as {\n installed: Array<{ name: string }>\n }\n const installedDeps = installed.installed.map((pkg) => pkg.name)\n\n return dependencies.filter((dep) => {\n const name = dep.split(':')[0]\n return !installedDeps.includes(name)\n })\n } catch {\n // If we can't check, assume all need to be installed\n return dependencies as string[]\n }\n }\n}\n","import prompts from 'prompts'\nimport fsExtra from 'fs-extra'\nimport type {\n AddResult,\n FailedComponent,\n VelyxComponentMeta,\n} from '@/src/types'\nimport type {\n IConfigManager,\n IFileSystemService,\n IRegistryService,\n} from '@/src/types/interfaces'\nimport { FilesystemService } from '@/src/services/filesystem-service'\nimport { DependencyService } from '@/src/services/dependency-service'\nimport { injectComponentJs } from '@/src/utils/js'\nimport { logger } from '@/src/utils/logger'\nimport {\n createFileBackup,\n deleteFileBackup,\n restoreFileBackup,\n} from '@/src/utils/file-helper'\n\ntype PlannedFile = {\n componentName: string\n filePath: string\n fileType: 'blade' | 'js' | 'css' | null\n destPath: string\n content: string\n existedBefore: boolean\n}\n\n/**\n * Determine file type from file path\n */\nfunction getFileTypeFromPath(filePath: string): 'blade' | 'js' | 'css' | null {\n if (filePath.endsWith('.blade.php')) return 'blade'\n if (filePath.endsWith('.js')) return 'js'\n if (filePath.endsWith('.css')) return 'css'\n return null\n}\n\n/**\n * Service for managing component operations\n */\nexport class ComponentService {\n private readonly fileSystem: IFileSystemService\n private readonly dependencyService: DependencyService\n\n /**\n * Create a new ComponentService instance\n * @param registryService - Service for registry operations\n * @param fileSystem - Optional file system service (creates new one if not provided)\n * @param configManager - Service for configuration management\n */\n constructor(\n private readonly registryService: IRegistryService,\n fileSystem?: IFileSystemService,\n private readonly configManager?: IConfigManager,\n ) {\n this.fileSystem = fileSystem ?? new FilesystemService()\n this.dependencyService = new DependencyService(this.fileSystem)\n if (!this.configManager) {\n throw new Error('ConfigManager is required')\n }\n }\n\n /**\n * Add multiple components to the project\n * @param componentNames - Array of component names to add\n * @returns Promise resolving to result of the operation\n */\n async addComponents(componentNames: readonly string[]): Promise<AddResult> {\n const result: {\n added: string[]\n skipped: string[]\n failed: FailedComponent[]\n } = {\n added: [],\n skipped: [],\n failed: [],\n }\n\n for (const componentName of componentNames) {\n try {\n const componentResult = await this.addComponent(componentName)\n result.added.push(...componentResult.added)\n result.skipped.push(...componentResult.skipped)\n result.failed.push(...componentResult.failed)\n } catch (error) {\n result.failed.push({\n name: componentName,\n error: (error as Error).message,\n })\n }\n }\n\n return result\n }\n\n /**\n * Add a single component to the project\n * @param componentName - Name of the component to add\n * @returns Promise resolving to result of the operation\n * @throws Error if component fetch fails\n */\n private async addComponent(componentName: string): Promise<AddResult> {\n const result: {\n added: string[]\n skipped: string[]\n failed: FailedComponent[]\n } = {\n added: [],\n skipped: [],\n failed: [],\n }\n\n // Fetch component metadata with files\n const component = await this.registryService.fetchComponent(\n componentName,\n { includeFiles: true },\n )\n\n // Resolve dependencies (fetch without files for dependencies)\n await this.registryService.resolveDependencies(component)\n\n // Install component dependencies (npm/composer)\n const dependencies = this.buildDependencies(component)\n if (dependencies) {\n const packageManager = this.configManager!.getPackageManager()\n try {\n await this.dependencyService.installDependencies(\n dependencies,\n packageManager,\n )\n } catch (error) {\n logger.warn(\n `Failed to install dependencies for ${componentName}: ${\n (error as Error).message\n }`,\n )\n // Continue with file installation even if dependencies fail\n }\n }\n\n const plannedFiles: PlannedFile[] = []\n\n // Fetch files for the main component with content\n const componentWithFiles = await this.fetchComponentWithFiles(componentName)\n \n for (const [filePath, content] of Object.entries(componentWithFiles.files)) {\n // Determine destination based on file type\n const dest = this.getDestinationPath(filePath)\n const fileType = getFileTypeFromPath(filePath)\n\n // Check if file exists and handle conflict\n const existedBefore = await this.fileSystem.fileExists(dest)\n if (existedBefore) {\n const action = await this.handleFileConflict(filePath)\n if (action === 'skip') {\n result.skipped.push(`${componentName}/${filePath}`)\n continue\n } else if (action === 'cancel') {\n logger.error('Cancelled.')\n process.exit(0)\n }\n }\n\n plannedFiles.push({\n componentName,\n filePath,\n fileType,\n destPath: dest,\n content,\n existedBefore,\n })\n }\n\n if (plannedFiles.length > 0) {\n try {\n await this.applyFileBatch(plannedFiles)\n plannedFiles.forEach((file) =>\n result.added.push(`${file.componentName}/${file.filePath}`),\n )\n\n const jsComponents = new Set(\n plannedFiles\n .filter((file) => file.fileType === 'js')\n .map((file) => file.componentName),\n )\n for (const jsComponent of Array.from(jsComponents)) {\n await this.autoImportJs(jsComponent)\n }\n } catch (error) {\n plannedFiles.forEach((file) =>\n result.failed.push({\n name: `${file.componentName}/${file.filePath}`,\n error: (error as Error).message,\n }),\n )\n }\n }\n\n return result\n }\n\n /**\n * Build dependencies object from component metadata\n */\n private buildDependencies(component: VelyxComponentMeta): {\n composer?: readonly string[]\n npm?: readonly string[]\n } | null {\n const dependencies: {\n composer?: string[]\n npm?: string[]\n } = {}\n\n if (component.requires && component.requires.length > 0) {\n dependencies.composer = [...component.requires]\n }\n\n if (component.requires_alpine) {\n dependencies.npm = ['alpinejs']\n }\n\n return Object.keys(dependencies).length > 0 ? dependencies : null\n }\n\n /**\n * Fetch component with files from registry\n */\n private async fetchComponentWithFiles(\n componentName: string,\n ): Promise<{ files: Record<string, string> }> {\n const result = await this.registryService.fetchComponent(componentName, {\n includeFiles: true,\n })\n\n // Check if the result has files (RegistryComponentWithFiles)\n if ('files' in result) {\n return result\n }\n\n // Fallback: if no files, return empty object\n return { files: {} }\n }\n\n /**\n * Automatically import component JS into the main JS entry\n * @param componentName - Name of the component\n */\n private async autoImportJs(componentName: string): Promise<void> {\n try {\n const jsEntry = this.configManager?.getJsEntryPath()\n if (!jsEntry || !(await this.fileSystem.fileExists(jsEntry))) {\n return\n }\n\n const importPath = `./ui/${componentName}`\n injectComponentJs(jsEntry, componentName, importPath)\n logger.success(`Auto-imported ${componentName} into ${jsEntry}`)\n } catch (error) {\n logger.warn(\n `Failed to auto-import JS for ${componentName}: ${\n (error as Error).message\n }`,\n )\n }\n }\n\n /**\n * Get the destination path for a component file\n * The API returns file paths in project structure format:\n * - resources/views/components/ui/{name}/{name}.blade.php\n * - resources/js/ui/{name}.js\n * - resources/css/ui/{name}.css\n *\n * We preserve the API's structure for consistency\n *\n * @param filePath - File path from API\n * @returns Destination file path\n */\n private getDestinationPath(filePath: string): string {\n // The API already provides the correct path structure\n // Just ensure it's relative to project root\n return filePath\n }\n\n /**\n * Handle file conflict by prompting user\n * @param filePath - Path of the conflicting file\n * @returns Promise resolving to user action (\"skip\", \"overwrite\", or \"cancel\")\n */\n private async handleFileConflict(\n filePath: string,\n ): Promise<'skip' | 'overwrite' | 'cancel'> {\n const { action } = await prompts(\n {\n type: 'select',\n name: 'action',\n message: `File \"${filePath}\" already exists. What do you want to do?`,\n choices: [\n { title: 'Skip', value: 'skip' },\n { title: 'Overwrite', value: 'overwrite' },\n { title: 'Cancel', value: 'cancel' },\n ],\n initial: 0,\n },\n {\n onCancel: () => {\n logger.error('Cancelled.')\n process.exit(0)\n },\n },\n )\n\n return action as 'skip' | 'overwrite' | 'cancel'\n }\n\n private async applyFileBatch(plannedFiles: PlannedFile[]): Promise<void> {\n const tempFiles: string[] = []\n const backupTargets: string[] = []\n\n try {\n for (const file of plannedFiles) {\n const tempPath = `${file.destPath}.velyx-tmp`\n await this.fileSystem.writeFile(tempPath, file.content)\n tempFiles.push(tempPath)\n }\n\n for (const file of plannedFiles) {\n if (!file.existedBefore) {\n continue\n }\n\n const backupPath = createFileBackup(file.destPath)\n if (!backupPath) {\n throw new Error(`Failed to create backup for ${file.destPath}`)\n }\n backupTargets.push(file.destPath)\n }\n\n for (const file of plannedFiles) {\n const tempPath = `${file.destPath}.velyx-tmp`\n await fsExtra.move(tempPath, file.destPath, { overwrite: true })\n }\n\n backupTargets.forEach((filePath) => deleteFileBackup(filePath))\n } catch (error) {\n for (const file of plannedFiles) {\n if (await this.fileSystem.fileExists(file.destPath)) {\n await fsExtra.remove(file.destPath)\n }\n if (file.existedBefore) {\n restoreFileBackup(file.destPath)\n }\n }\n\n for (const tempFile of tempFiles) {\n if (await this.fileSystem.fileExists(tempFile)) {\n await fsExtra.remove(tempFile)\n }\n }\n\n throw error\n }\n }\n}\n","import type { AddResult, RegistryData } from '@/src/types'\nimport type { IRegistryService, IConfigManager } from '../types/interfaces'\nimport { ComponentService } from './component-service'\nimport { FilesystemService } from './filesystem-service'\nimport { logger } from '../utils/logger'\n\n/**\n * Service for handling component addition operations\n */\nexport class AddService {\n private readonly componentService: ComponentService\n\n /**\n * Create a new AddService instance\n * @param registryService - Service for registry operations\n * @param configManager - Service for configuration management\n * @param componentService - Optional component service (creates new one if not provided)\n */\n constructor(\n private readonly registryService: IRegistryService,\n private readonly configManager: IConfigManager,\n componentService?: ComponentService,\n ) {\n // ComponentService will be created if not provided\n // This allows for dependency injection in tests\n this.componentService =\n componentService ??\n new ComponentService(\n registryService,\n new FilesystemService(),\n configManager,\n )\n }\n\n /**\n * Validate that Velyx is initialized\n * @throws Error if not initialized\n */\n validateInitialization(): void {\n if (!this.configManager.validate()) {\n throw new Error('Velyx is not initialized')\n }\n }\n\n /**\n * Validate that components exist in the registry\n * @param componentNames - Names of components to validate\n * @param registry - Registry data\n * @throws Error if any component is not found\n */\n validateComponents(\n componentNames: readonly string[],\n registry: RegistryData,\n ): void {\n for (const componentName of componentNames) {\n const found = registry.components.find((c) => c.name === componentName)\n if (!found) {\n throw new Error(`Component \"${componentName}\" not found`)\n }\n }\n }\n\n /**\n * Get available components from registry\n * @returns Promise resolving to registry data\n * @throws NetworkError if fetch fails\n */\n async getAvailableComponents(): Promise<RegistryData> {\n return await this.registryService.fetchRegistry()\n }\n\n /**\n * Add components to the project\n * @param componentNames - Names of components to add\n * @returns Promise resolving to result of the operation\n */\n async addComponents(componentNames: readonly string[]): Promise<AddResult> {\n return await this.componentService.addComponents(componentNames)\n }\n\n /**\n * Display the results of adding components\n * @param result - Result of the add operation\n */\n displayResults(result: AddResult): void {\n result.added.forEach((name) => logger.success(`Added ${name}`))\n result.skipped.forEach((name) => logger.warn(`Skipped ${name}`))\n result.failed.forEach(({ name, error }) =>\n logger.error(`Failed to add ${name}: ${error}`),\n )\n }\n\n /**\n * Display next steps after adding components\n * @param result - Result of the add operation\n */\n displayNextSteps(result: AddResult): void {\n if (result.added.length === 0) {\n return\n }\n\n console.log('\\nš Happy coding! Enjoy building beautiful components!')\n }\n}\n","/**\n * Base error class for registry-related errors\n */\nexport class RegistryError extends Error {\n /**\n * Create a new RegistryError\n * @param message - Error message\n * @param cause - Original error that caused this error\n */\n constructor(\n message: string,\n public readonly cause?: Error,\n ) {\n super(message)\n this.name = 'RegistryError'\n }\n}\n\n/**\n * Error thrown when a network request fails\n */\nexport class NetworkError extends RegistryError {\n /**\n * Create a new NetworkError\n * @param message - Error message\n * @param cause - Original error that caused this error\n */\n constructor(message: string, cause?: Error) {\n super(message, cause)\n this.name = 'NetworkError'\n }\n}\n\n/**\n * Error thrown when a component is not found in the registry\n */\nexport class ComponentNotFoundError extends RegistryError {\n /**\n * Create a new ComponentNotFoundError\n * @param componentName - Name of the component that was not found\n * @param cause - Original error that caused this error\n */\n constructor(componentName: string, cause?: Error) {\n super(`Component \"${componentName}\" not found`, cause)\n this.name = 'ComponentNotFoundError'\n }\n}\n","import { NetworkError } from '../errors/errors'\nimport type { FetchOptions } from '../types'\n\n/**\n * Default retry options\n */\nconst DEFAULT_RETRY_OPTIONS: Required<FetchOptions> = {\n maxRetries: 3,\n initialDelay: 1000,\n backoffFactor: 2,\n maxDelay: 10000,\n retryableStatusCodes: [408, 429, 500, 502, 503, 504],\n timeout: 30000,\n headers: {},\n}\n\n/**\n * Sleep utility for retry delays\n * @param ms - Milliseconds to sleep\n */\nfunction sleep(ms: number): Promise<void> {\n return new Promise((resolve) => setTimeout(resolve, ms))\n}\n\n/**\n * Calculate delay for retry attempt with exponential backoff\n * @param attempt - Current attempt number (0-indexed)\n * @param initialDelay - Initial delay in milliseconds\n * @param backoffFactor - Factor to multiply delay by each attempt\n * @param maxDelay - Maximum delay in milliseconds\n * @returns Delay in milliseconds\n */\nfunction calculateDelay(\n attempt: number,\n initialDelay: number,\n backoffFactor: number,\n maxDelay: number,\n): number {\n const delay = initialDelay * Math.pow(backoffFactor, attempt)\n return Math.min(delay, maxDelay)\n}\n\n/**\n * Check if a status code is retryable\n * @param status - HTTP status code\n * @param retryableStatusCodes - List of retryable status codes\n * @returns True if status code is retryable\n */\nfunction isRetryableStatus(\n status: number,\n retryableStatusCodes: readonly number[],\n): boolean {\n return retryableStatusCodes.includes(status)\n}\n\n/**\n * Create a fetch request with timeout\n * @param url - URL to fetch\n * @param options - Fetch options including timeout\n * @returns Promise resolving to Response\n */\nasync function fetchWithTimeout(\n url: string,\n options: FetchOptions,\n): Promise<Response> {\n const { timeout = DEFAULT_RETRY_OPTIONS.timeout, headers = {} } = options\n\n const controller = new AbortController()\n const timeoutId = setTimeout(() => controller.abort(), timeout)\n\n try {\n const response = await fetch(url, {\n signal: controller.signal,\n headers: {\n 'User-Agent': 'Velyx-CLI',\n ...headers,\n },\n })\n return response\n } catch (error) {\n if (error instanceof Error && error.name === 'AbortError') {\n throw new NetworkError(\n `Request timeout after ${timeout}ms for ${url}`,\n error,\n )\n }\n throw error\n } finally {\n clearTimeout(timeoutId)\n }\n}\n\n/**\n * HTTP service with retry logic and timeout support\n */\nexport class HttpService {\n /**\n * Fetch a URL with retry logic and timeout\n * @param url - URL to fetch\n * @param options - Fetch options including retry configuration\n * @returns Promise resolving to Response\n * @throws NetworkError if all retries fail\n */\n async fetch(url: string, options: FetchOptions = {}): Promise<Response> {\n const retryOptions = {\n maxRetries: options.maxRetries ?? DEFAULT_RETRY_OPTIONS.maxRetries,\n initialDelay: options.initialDelay ?? DEFAULT_RETRY_OPTIONS.initialDelay,\n backoffFactor:\n options.backoffFactor ?? DEFAULT_RETRY_OPTIONS.backoffFactor,\n maxDelay: options.maxDelay ?? DEFAULT_RETRY_OPTIONS.maxDelay,\n retryableStatusCodes:\n options.retryableStatusCodes ??\n DEFAULT_RETRY_OPTIONS.retryableStatusCodes,\n timeout: options.timeout ?? DEFAULT_RETRY_OPTIONS.timeout,\n headers: options.headers ?? DEFAULT_RETRY_OPTIONS.headers,\n }\n\n let lastError: Error | null = null\n\n for (let attempt = 0; attempt <= retryOptions.maxRetries; attempt++) {\n try {\n const response = await fetchWithTimeout(url, {\n ...options,\n timeout: retryOptions.timeout,\n headers: retryOptions.headers,\n })\n\n // If response is successful or not retryable, return it\n if (\n response.ok ||\n !isRetryableStatus(response.status, retryOptions.retryableStatusCodes)\n ) {\n return response\n }\n console.log('Attempt: ', attempt)\n // If this is the last attempt, throw error\n if (attempt === retryOptions.maxRetries) {\n throw new NetworkError(\n `Request failed after ${retryOptions.maxRetries + 1} attempts: ${response.status} ${response.statusText}`,\n )\n }\n\n // Calculate delay and wait before retry\n const delay = calculateDelay(\n attempt,\n retryOptions.initialDelay,\n retryOptions.backoffFactor,\n retryOptions.maxDelay,\n )\n await sleep(delay)\n } catch (error) {\n lastError = error as Error\n\n // Don't retry on certain errors\n if (\n error instanceof NetworkError &&\n error.message.includes('timeout')\n ) {\n if (attempt === retryOptions.maxRetries) {\n throw error\n }\n const delay = calculateDelay(\n attempt,\n retryOptions.initialDelay,\n retryOptions.backoffFactor,\n retryOptions.maxDelay,\n )\n await sleep(delay)\n continue\n }\n\n // If this is the last attempt, throw error\n if (attempt === retryOptions.maxRetries) {\n if (lastError instanceof NetworkError) {\n throw lastError\n }\n throw new NetworkError(\n `Request failed after ${retryOptions.maxRetries + 1} attempts: ${lastError.message}`,\n lastError,\n )\n }\n\n // Calculate delay and wait before retry\n const delay = calculateDelay(\n attempt,\n retryOptions.initialDelay,\n retryOptions.backoffFactor,\n retryOptions.maxDelay,\n )\n await sleep(delay)\n }\n }\n\n throw new NetworkError(\n `Request failed after ${retryOptions.maxRetries + 1} attempts: ${lastError?.message ?? 'Unknown error'}`,\n lastError ?? undefined,\n )\n }\n\n /**\n * Fetch JSON from a URL with retry logic\n * @param url - URL to fetch\n * @param options - Fetch options\n * @returns Promise resolving to parsed JSON\n * @throws NetworkError if fetch or parsing fails\n */\n async fetchJson<T>(url: string, options?: FetchOptions): Promise<T> {\n const response = await this.fetch(url, options)\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to fetch JSON from ${url}: ${response.status} ${response.statusText}`,\n )\n }\n\n try {\n return (await response.json()) as T\n } catch (error) {\n throw new NetworkError(\n `Failed to parse JSON from ${url}: ${(error as Error).message}`,\n error as Error,\n )\n }\n }\n\n /**\n * Fetch text from a URL with retry logic\n * @param url - URL to fetch\n * @param options - Fetch options\n * @returns Promise resolving to text content\n * @throws NetworkError if fetch fails\n */\n async fetchText(url: string, options?: FetchOptions): Promise<string> {\n const response = await this.fetch(url, options)\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to fetch text from ${url}: ${response.status} ${response.statusText}`,\n )\n }\n\n try {\n return await response.text()\n } catch (error) {\n throw new NetworkError(\n `Failed to read text from ${url}: ${(error as Error).message}`,\n error as Error,\n )\n }\n }\n}\n","/**\n * Get Velyx Registry API v1 URL\n * @returns Velyx Registry API URL\n */\nexport const getRegistryApiUrl = (): string => {\n // Allow override via environment variable for development\n if (process.env.VELYX_REGISTRY_URL) {\n return process.env.VELYX_REGISTRY_URL.replace(/\\/$/, '') // Remove trailing slash\n }\n\n // Default to local registry for development\n // In production, this would be https://registry.velyx.dev/api/v1\n return 'http://velyx.test/api/v1'\n}\n","import type {\n RegistryComponentWithFiles,\n RegistryComponentsResponse,\n RegistryVersionsResponse,\n RegistryComponentResponse,\n VelyxComponentMeta,\n} from '../types'\nimport type { IRegistryService } from '../types/interfaces'\nimport { NetworkError, ComponentNotFoundError } from '../errors/errors'\nimport { HttpService } from './http-service'\nimport { getRegistryApiUrl } from '../utils/environment'\n\n/**\n * Service for interacting with Velyx Registry API v1\n */\nexport class VelyxRegistryService implements IRegistryService {\n private readonly httpService: HttpService\n private readonly baseUrl: string\n\n /**\n * Create a new VelyxRegistryService instance\n * @param httpService - Optional HTTP service instance (creates new one if not provided)\n */\n constructor(httpService?: HttpService) {\n this.httpService = httpService ?? new HttpService()\n this.baseUrl = getRegistryApiUrl()\n }\n\n /**\n * Fetch complete registry data\n * @returns Promise resolving to registry data\n * @throws NetworkError if fetch fails\n */\n async fetchRegistry(): Promise<{\n components: readonly VelyxComponentMeta[]\n count: number\n }> {\n try {\n const response = await this.httpService.fetch(\n `${this.baseUrl}/components`,\n )\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to fetch registry: ${response.status} ${response.statusText}`,\n )\n }\n\n const data = await this.httpService.fetchJson<RegistryComponentsResponse>(\n `${this.baseUrl}/components`,\n )\n\n // Convert Registry API v1 format (object with keys) to array\n const components = Object.values(data.data)\n\n return { components, count: data.count }\n } catch (error) {\n if (error instanceof NetworkError) {\n throw error\n }\n throw new NetworkError(\n `Failed to fetch registry: ${(error as Error).message}`,\n )\n }\n }\n\n /**\n * Fetch metadata for a specific component\n * @param name - Component name\n * @param options - Optional parameters (version, includeFiles)\n * @returns Promise resolving to component metadata (with files if includeFiles is true)\n * @throws ComponentNotFoundError if component doesn't exist\n * @throws NetworkError if fetch fails\n */\n async fetchComponent(\n name: string,\n options?: { version?: string; includeFiles?: boolean },\n ): Promise<VelyxComponentMeta | RegistryComponentWithFiles> {\n try {\n const url = this.buildComponentUrl(name, options)\n\n const response = await this.httpService.fetch(url)\n\n if (response.status === 404) {\n throw new ComponentNotFoundError(name)\n }\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to fetch component: ${response.status} ${response.statusText}`,\n )\n }\n\n const result =\n await this.httpService.fetchJson<RegistryComponentResponse>(url)\n\n if (options?.includeFiles) {\n return result.data\n }\n\n return this.convertRegistryComponentToMeta(result.data)\n } catch (error) {\n if (\n error instanceof ComponentNotFoundError ||\n error instanceof NetworkError\n ) {\n throw error\n }\n throw new NetworkError(\n `Failed to fetch component \"${name}\": ${(error as Error).message}`,\n )\n }\n }\n\n /**\n * Fetch file content for a component\n * @param componentUrl - Component URL or name\n * @param path - File path within component\n * @returns Promise resolving to file content\n * @throws ComponentNotFoundError if component or file doesn't exist\n * @throws NetworkError if fetch fails\n */\n async fetchFile(componentUrl: string, path: string): Promise<string> {\n try {\n const componentName = componentUrl.split('/').pop() || componentUrl\n\n const response = await this.httpService.fetch(\n `${this.baseUrl}/components/${componentName}`,\n )\n\n if (response.status === 404) {\n throw new ComponentNotFoundError(componentName)\n }\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to fetch component: ${response.status} ${response.statusText}`,\n )\n }\n\n const component =\n await this.httpService.fetchJson<RegistryComponentWithFiles>(\n `${this.baseUrl}/components/${componentName}`,\n )\n\n // Find the file in the component's files\n const fileContent = component.files[path]\n if (fileContent === undefined) {\n throw new NetworkError(\n `File \"${path}\" not found in component \"${componentName}\"`,\n )\n }\n\n return fileContent\n } catch (error) {\n if (\n error instanceof ComponentNotFoundError ||\n error instanceof NetworkError\n ) {\n throw error\n }\n throw new NetworkError(\n `Failed to fetch file \"${path}\": ${(error as Error).message}`,\n )\n }\n }\n\n /**\n * Resolve component dependencies\n * @param component - Component metadata\n * @returns Promise resolving to array of components including dependencies\n */\n async resolveDependencies(\n component: VelyxComponentMeta,\n ): Promise<readonly VelyxComponentMeta[]> {\n const visited = new Set<string>()\n const resolved: VelyxComponentMeta[] = []\n\n const resolve = async (comp: VelyxComponentMeta) => {\n if (visited.has(comp.name)) return\n visited.add(comp.name)\n resolved.push(comp)\n\n // Resolve dependencies from the 'requires' field\n if (comp.requires && comp.requires.length > 0) {\n for (const dep of comp.requires) {\n try {\n // Try to fetch dependency as a Velyx component\n const depComponent = await this.fetchComponent(dep)\n await resolve(depComponent)\n } catch {\n // Skip if dependency is not a Velyx component (might be a composer package)\n }\n }\n }\n }\n\n await resolve(component)\n return resolved\n }\n\n /**\n * Convert Registry API v1 component format to VelyxComponentMeta\n */\n private convertRegistryComponentToMeta(\n component: RegistryComponentWithFiles,\n ): VelyxComponentMeta {\n return {\n name: component.name,\n description: component.description,\n latest: component.latest,\n versions: component.versions,\n requires_alpine: component.requires_alpine,\n requires: component.requires,\n categories: component.categories,\n laravel: component.laravel,\n }\n }\n\n /**\n * Build URL for fetching component with optional parameters\n */\n private buildComponentUrl(\n name: string,\n options?: { version?: string; includeFiles?: boolean },\n ): string {\n const params = new URLSearchParams()\n\n if (options?.version) {\n params.append('version', options.version)\n }\n\n if (options?.includeFiles) {\n params.append('include', 'files')\n }\n\n const queryString = params.toString()\n return `${this.baseUrl}/components/${name}${queryString ? `?${queryString}` : ''}`\n }\n\n /**\n * Get available versions for a component\n * @param name - Component name\n * @returns Promise resolving to versions data\n */\n async getComponentVersions(name: string): Promise<RegistryVersionsResponse> {\n try {\n const response = await this.httpService.fetch(\n `${this.baseUrl}/components/${name}/versions`,\n )\n\n if (response.status === 404) {\n throw new ComponentNotFoundError(name)\n }\n\n if (!response.ok) {\n throw new NetworkError(\n `Failed to fetch component versions: ${response.status} ${response.statusText}`,\n )\n }\n\n return await this.httpService.fetchJson<RegistryVersionsResponse>(\n `${this.baseUrl}/components/${name}/versions`,\n )\n } catch (error) {\n if (\n error instanceof ComponentNotFoundError ||\n error instanceof NetworkError\n ) {\n throw error\n }\n throw new NetworkError(\n `Failed to fetch versions for \"${name}\": ${(error as Error).message}`,\n )\n }\n }\n}\n","import type {\n VelyxComponentMeta,\n RegistryComponentWithFiles,\n} from '../types'\nimport type {\n IRegistryService,\n FetchComponentOptions,\n} from '../types/interfaces'\nimport { VelyxRegistryService } from './velyx-registry-service'\nimport { spinner } from '../utils/spinner'\n\n/**\n * Service for interacting with Velyx component registry\n * This is a wrapper around VelyxRegistryService with UI feedback\n */\nexport class RegistryService implements IRegistryService {\n private readonly velyxService: VelyxRegistryService\n\n /**\n * Create a new RegistryService instance\n */\n constructor() {\n this.velyxService = new VelyxRegistryService()\n }\n\n /**\n * Fetch complete registry data\n * @returns Promise resolving to registry data\n * @throws NetworkError if fetch fails\n */\n async fetchRegistry(): Promise<{\n components: readonly VelyxComponentMeta[]\n count: number\n }> {\n return await spinner.withTask(\n 'Fetching registry...',\n () => this.velyxService.fetchRegistry(),\n undefined,\n 'Failed to fetch registry',\n )\n }\n\n /**\n * Fetch metadata for a specific component\n * @param name - Component name\n * @param options - Optional parameters (version, includeFiles)\n * @returns Promise resolving to component metadata (with files if includeFiles is true)\n * @throws ComponentNotFoundError if component doesn't exist\n * @throws NetworkError if fetch fails\n */\n async fetchComponent(\n name: string,\n options?: FetchComponentOptions,\n ): Promise<VelyxComponentMeta | RegistryComponentWithFiles> {\n const taskMessage = options?.includeFiles\n ? `Fetching component \"${name}\" with files...`\n : `Fetching component \"${name}\" metadata...`\n\n return await spinner.withTask(\n taskMessage,\n () => this.velyxService.fetchComponent(name, options),\n undefined,\n `Failed to fetch component \"${name}\"`,\n )\n }\n\n /**\n * Resolve component dependencies\n * @param component - Component metadata\n * @returns Promise resolving to array of components including dependencies\n */\n async resolveDependencies(\n component: VelyxComponentMeta,\n ): Promise<readonly VelyxComponentMeta[]> {\n return await spinner.withTask(\n 'Resolving dependencies...',\n () => this.velyxService.resolveDependencies(component),\n undefined,\n 'Failed to resolve dependencies',\n )\n }\n}\n","import { ConfigManager } from '@/src/config/config-manager'\nimport { AddService } from '@/src/services/add-service'\nimport { RegistryService } from '@/src/services/registry-service'\nimport { logger } from '@/src/utils/logger'\nimport { z } from 'zod'\nimport prompts from 'prompts'\n\nexport type AddOptions = {\n components?: string[]\n yes: boolean\n overwrite: boolean\n cwd: string\n all: boolean\n path?: string\n silent: boolean\n srcDir?: boolean\n cssVariables?: boolean\n}\n\nasync function promptForRegistryComponents(\n options: AddOptions,\n availableComponents: readonly string[],\n): Promise<string[]> {\n if (options.all) {\n return [...availableComponents]\n }\n\n if (options.components?.length) {\n return options.components\n }\n\n logger.info('Use arrow keys and space to select, then press enter.')\n\n const { components } = await prompts({\n type: 'multiselect',\n name: 'components',\n message: 'Which components would you like to add?',\n hint: 'Space to select. A to toggle all. Enter to submit.',\n instructions: false,\n choices: availableComponents.map((name) => ({\n title: name,\n value: name,\n selected: options.all ? true : options.components?.includes(name),\n })),\n })\n\n if (!components?.length) {\n logger.warn('No components selected. Exiting.')\n logger.info('')\n process.exit(1)\n }\n\n const result = z.array(z.string()).safeParse(components)\n if (!result.success) {\n logger.error('Something went wrong. Please try again.')\n process.exit(1)\n }\n\n return result.data\n}\n\nexport async function addComponents(options: AddOptions): Promise<void> {\n const configManager = new ConfigManager()\n await configManager.load()\n\n const registryService = new RegistryService()\n const addService = new AddService(registryService, configManager)\n\n try {\n addService.validateInitialization()\n } catch {\n logger.error('Velyx is not initialized')\n logger.log('Run velyx init first')\n process.exit(1)\n }\n\n const registry = await addService.getAvailableComponents()\n\n const available = registry.components\n .map((component: { name: string }) => component.name)\n .sort((a: string, b: string) => a.localeCompare(b))\n const componentNames = await promptForRegistryComponents(options, available)\n try {\n addService.validateComponents(componentNames, registry)\n } catch (err) {\n logger.error((err as Error).message)\n logger.log('Run velyx list to see available components')\n process.exit(1)\n }\n\n const result = await addService.addComponents(componentNames)\n addService.displayResults(result)\n addService.displayNextSteps(result)\n}\n","#!/usr/bin/env node\nimport { ErrorHandler } from '@/src/errors/ErrorHandler'\nimport { addComponents } from '@/src/utils/add-components'\nimport { Command } from 'commander'\nimport { z } from 'zod'\nimport path from 'path'\n\nexport const addOptionsSchema = z.object({\n components: z.array(z.string()).optional(),\n yes: z.boolean(),\n overwrite: z.boolean(),\n cwd: z.string(),\n all: z.boolean(),\n path: z.string().optional(),\n silent: z.boolean(),\n srcDir: z.boolean().optional(),\n cssVariables: z.boolean().optional(),\n})\n\n/**\n * Register the 'add' command with the CLI program\n * @param program - Commander program instance\n */\nexport const add = new Command()\n .name('add')\n .argument('[components...]', 'Names of components to add')\n .option('-y, --yes', 'skip confirmation prompt.', false)\n .option('-o, --overwrite', 'overwrite existing files.', false)\n .option(\n '-c, --cwd <cwd>',\n 'the working directory. defaults to the current directory.',\n process.cwd(),\n )\n .option('-a, --all', 'add all available components', false)\n .option('-p, --path <path>', 'the path to add the component to.')\n .option('-s, --silent', 'mute output.', false)\n .option(\n '--src-dir',\n 'use the src directory when creating a new project.',\n false,\n )\n .option(\n '--no-src-dir',\n 'do not use the src directory when creating a new project.',\n )\n .option('--css-variables', 'use CSS variables for theming.', true)\n .option('--no-css-variables', 'do not use CSS variables for theming.')\n .description('Add one or more UI components to your Laravel project')\n .action(async (components, opts) => {\n const errorHandler = new ErrorHandler()\n\n try {\n const rawOptions = {\n components,\n cwd: path.resolve(opts.cwd),\n ...opts,\n cssVariables: opts.cssVariables ?? true,\n }\n\n const options = addOptionsSchema.parse(rawOptions)\n await addComponents(options)\n } catch (error) {\n errorHandler.handle(error as Error, 'add command')\n process.exit(1)\n }\n })\n","import chalk from 'chalk'\nimport Table from 'cli-table3'\nimport type { VelyxComponentMeta } from '@/src/types'\nimport { RegistryService } from '@/src/services/registry-service'\nimport { logger } from '@/src/utils/logger'\n\nexport type ListOptions = {\n query?: string\n limit?: number\n offset?: number\n json: boolean\n}\n\nfunction filterComponents(\n components: readonly VelyxComponentMeta[],\n query?: string,\n): VelyxComponentMeta[] {\n if (!query) {\n return [...components]\n }\n\n const normalized = query.toLowerCase()\n return components.filter((component) => {\n const nameMatch = component.name.toLowerCase().includes(normalized)\n const descriptionMatch = component.description\n ? component.description.toLowerCase().includes(normalized)\n : false\n const categoryMatch = component.categories\n ? component.categories.some((category) =>\n category.toLowerCase().includes(normalized),\n )\n : false\n\n return nameMatch || descriptionMatch || categoryMatch\n })\n}\n\nfunction sliceComponents(\n components: VelyxComponentMeta[],\n offset?: number,\n limit?: number,\n): VelyxComponentMeta[] {\n const start = Math.max(0, offset ?? 0)\n if (limit === undefined) {\n return components.slice(start)\n }\n return components.slice(start, start + Math.max(0, limit))\n}\n\nexport async function listComponents(options: ListOptions): Promise<void> {\n const registryService = new RegistryService()\n const registry = await registryService.fetchRegistry()\n\n const sorted = [...registry.components].sort((a, b) =>\n a.name.localeCompare(b.name),\n )\n\n const filtered = filterComponents(sorted, options.query)\n const sliced = sliceComponents(filtered, options.offset, options.limit)\n\n if (options.json) {\n console.log(\n JSON.stringify(\n {\n total: filtered.length,\n count: sliced.length,\n offset: options.offset ?? 0,\n limit: options.limit ?? null,\n components: sliced,\n },\n null,\n 2,\n ),\n )\n return\n }\n\n if (sliced.length === 0) {\n logger.warn('No components found.')\n return\n }\n\n console.log(chalk.bold('\\nAvailable components:'))\n console.log('')\n\n const table = new Table({\n head: [\n chalk.bold('Component'),\n chalk.bold('Description'),\n chalk.bold('Categories'),\n ],\n colWidths: [24, 50, 24],\n wordWrap: true,\n style: {\n head: [],\n border: [],\n },\n })\n\n for (const component of sliced) {\n table.push([\n chalk.cyan(component.name),\n chalk.white(component.description || 'No description'),\n chalk.gray(component.categories?.join(', ') || '-'),\n ])\n }\n\n console.log(table.toString())\n console.log('')\n logger.info(`Run ${chalk.green('velyx add <component>')} to add one.`)\n}\n","import { Command } from 'commander'\nimport { z } from 'zod'\nimport path from 'path'\nimport { listComponents } from '@/src/utils/list-components'\nimport { ErrorHandler } from '@/src/errors/ErrorHandler'\nimport { logger } from '@/src/utils/logger'\nimport { ConfigManager } from '@/src/config/config-manager'\n\nconst listOptionsSchema = z.object({\n cwd: z.string(),\n query: z.string().optional(),\n limit: z.number().optional(),\n offset: z.number().optional(),\n json: z.boolean(),\n})\n\nexport const list = new Command()\n .name('list')\n .alias('search')\n .description('List or search components from the registry')\n .option(\n '-c, --cwd <cwd>',\n 'the working directory. defaults to the current directory.',\n process.cwd(),\n )\n .option('-q, --query <query>', 'query string')\n .option(\n '-l, --limit <number>',\n 'maximum number of items to display',\n undefined,\n )\n .option('-o, --offset <number>', 'number of items to skip', undefined)\n .option('--json', 'output JSON', false)\n .action(async (opts) => {\n const errorHandler = new ErrorHandler()\n\n try {\n const options = listOptionsSchema.parse({\n cwd: path.resolve(opts.cwd),\n query: opts.query,\n limit: opts.limit ? Number.parseInt(opts.limit, 10) : undefined,\n offset: opts.offset ? Number.parseInt(opts.offset, 10) : undefined,\n json: Boolean(opts.json),\n })\n\n process.chdir(options.cwd)\n\n // Validate initialization\n const configManager = new ConfigManager()\n try {\n await configManager.load()\n } catch {\n logger.error('Velyx is not initialized')\n logger.log('Run velyx init first')\n process.exit(1)\n }\n\n await listComponents(options)\n } catch (error) {\n errorHandler.handle(error as Error, 'list command')\n process.exit(1)\n }\n })\n","import chalk from 'chalk'\nimport { Command } from 'commander'\nimport { init } from '@/src/commands/init'\nimport { add } from '@/src/commands/add'\nimport { list } from '@/src/commands/list'\n\nimport packageJson from '../package.json'\n/**\n * Display a nice introduction banner\n */\nfunction displayIntro(): void {\n console.log('')\n console.log(chalk.bold.cyan(` ā¼ VELYX CLI v${packageJson.version}`))\n console.log(chalk.gray(' Tailwind CSS v4+ components for Laravel'))\n console.log('')\n}\n\n/**\n * Velyx CLI program entry point\n */\nconst program = new Command()\nprogram\n .name('velyx')\n .description('Velyx CLI: Copy UI components into your Laravel project')\n .version(\n packageJson.version || '1.0.0',\n '-v, --version',\n 'display the version number',\n )\n .hook('preAction', () => {\n displayIntro()\n })\n\nprogram.addCommand(add).addCommand(init).addCommand(list)\n\nprogram.parse(process.argv)\n"]}
|