velloo 0.7.0 → 0.9.0

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.
Files changed (95) hide show
  1. package/BUN-LICENSE.md +4 -3
  2. package/README.md +8 -1
  3. package/THIRD-PARTY-NOTICES.md +3 -3
  4. package/canvas/assets/index-CkVteRZ9.css +2 -0
  5. package/canvas/assets/index-DFOlwAKW.js +31 -0
  6. package/canvas/assets/lucide-all-CezGNjGW.js +1 -0
  7. package/canvas/index.html +2 -2
  8. package/{chunk-qrnkrkkt.js → chunk-00n2d68z.js} +1 -1
  9. package/{chunk-mdgwdqnq.js → chunk-02gpgqj4.js} +8 -8
  10. package/{chunk-qp3wahg4.js → chunk-0ztxyzac.js} +1 -1
  11. package/{chunk-4y2xy1kf.js → chunk-2x5rw009.js} +3 -3
  12. package/{chunk-abr2hgay.js → chunk-3f2p94wa.js} +1 -1
  13. package/{chunk-srp5gyr1.js → chunk-3jqbybmp.js} +1 -1
  14. package/{chunk-0vaff40g.js → chunk-5tatkt2j.js} +1 -1
  15. package/{chunk-asfgvzse.js → chunk-640swnrm.js} +1 -1
  16. package/{chunk-bms1sg4c.js → chunk-6600wkmq.js} +1 -1
  17. package/{chunk-7gyzh0vq.js → chunk-6adv9eke.js} +1 -1
  18. package/{chunk-fvezyap4.js → chunk-6wfvb07c.js} +1 -1
  19. package/chunk-8a2agf28.js +22 -0
  20. package/{chunk-82x2jkfq.js → chunk-8kn6tp4b.js} +2 -2
  21. package/{chunk-fmcm06xb.js → chunk-9b4akcfp.js} +1 -1
  22. package/{chunk-0pxm5v0b.js → chunk-9kvbe53e.js} +3 -3
  23. package/{chunk-gfppsgvv.js → chunk-a5mxgvcz.js} +1 -1
  24. package/{chunk-g7d065ek.js → chunk-as4rn21e.js} +1 -1
  25. package/{chunk-xg71h7nb.js → chunk-avewjans.js} +4 -4
  26. package/chunk-bpb97rsk.js +17 -0
  27. package/{chunk-j306gr0c.js → chunk-bsn761jv.js} +1 -1
  28. package/{chunk-kkvf0xk2.js → chunk-c11n1tve.js} +2 -2
  29. package/{chunk-sme6hv6f.js → chunk-cfksd3zh.js} +1 -1
  30. package/{chunk-zv17t1n7.js → chunk-ck3bg8rf.js} +1 -1
  31. package/{chunk-d93kpv7s.js → chunk-cy1nmr0f.js} +1 -1
  32. package/{chunk-qqrac4va.js → chunk-dqy6a75x.js} +1 -1
  33. package/{chunk-xzf52wvn.js → chunk-f8jchnwe.js} +1 -1
  34. package/{chunk-s84vxcdv.js → chunk-fejhav0p.js} +1 -1
  35. package/{chunk-ykpctq15.js → chunk-fzqt4rsz.js} +1 -1
  36. package/{chunk-3m28pvzr.js → chunk-g7pbfad5.js} +1 -1
  37. package/{chunk-b8vcbbrg.js → chunk-gv209d5j.js} +1 -1
  38. package/chunk-j4rt31qb.js +2 -0
  39. package/{chunk-d0j8dg1e.js → chunk-kmsbcb3q.js} +1 -1
  40. package/{chunk-5s1wjhtj.js → chunk-ktps9v0k.js} +1 -1
  41. package/{chunk-667ag8ts.js → chunk-ktsdzzgx.js} +1 -1
  42. package/{chunk-0e5j6nqs.js → chunk-kvxn1cyx.js} +1 -1
  43. package/{chunk-ex36z3b3.js → chunk-n70zfv0m.js} +906 -906
  44. package/{chunk-rqd4swxx.js → chunk-n8pr0kc8.js} +1 -1
  45. package/{chunk-eh2xp4v6.js → chunk-pasvz8xw.js} +1 -1
  46. package/{chunk-j4fn2a2b.js → chunk-qewarcqf.js} +1 -1
  47. package/{chunk-dvh0b2r4.js → chunk-qf1c6jxh.js} +1 -1
  48. package/chunk-qn05hn7a.js +5 -0
  49. package/{chunk-gcce587w.js → chunk-qvdvxqs0.js} +1 -1
  50. package/{chunk-pjkkp7xa.js → chunk-r014f76h.js} +1 -1
  51. package/{chunk-acsv6m3n.js → chunk-seaar5na.js} +1 -1
  52. package/{chunk-84n18xgx.js → chunk-tax7fxav.js} +2 -2
  53. package/{chunk-gbq5wv7x.js → chunk-tmjs6xas.js} +1 -1
  54. package/{chunk-vs8j3x6t.js → chunk-v6w8akph.js} +1 -1
  55. package/{chunk-5x4nw0zz.js → chunk-w40pqmyz.js} +4 -4
  56. package/{chunk-vdbr81a3.js → chunk-x05grjd9.js} +1 -1
  57. package/{chunk-md4mpvqc.js → chunk-x61f42fj.js} +2 -2
  58. package/{chunk-531xzfq5.js → chunk-xc6mats8.js} +1 -1
  59. package/chunk-yp39f93e.js +815 -0
  60. package/{chunk-5yhnnhkd.js → chunk-ysf9388d.js} +1 -1
  61. package/{chunk-64pex3mw.js → chunk-z3r8px3d.js} +1 -1
  62. package/{chunk-ejppcfa5.js → chunk-z9kcdgj8.js} +1 -1
  63. package/chunk-zexzy6zv.js +2 -0
  64. package/chunk-zjbbd87h.js +2 -0
  65. package/cli.js +1 -1
  66. package/package.json +9 -9
  67. package/pkgs/provider-antd/src/index.ts +1 -0
  68. package/pkgs/provider-html/src/index.ts +1 -0
  69. package/pkgs/provider-mui/src/index.ts +10 -0
  70. package/pkgs/provider-none/src/index.ts +1 -0
  71. package/pkgs/schema/src/board.ts +13 -1
  72. package/pkgs/schema/src/config.ts +34 -0
  73. package/pkgs/schema/src/flow.ts +230 -0
  74. package/pkgs/schema/src/frame.ts +7 -0
  75. package/pkgs/schema/src/index.ts +22 -0
  76. package/pkgs/schema/src/node-identity.ts +48 -0
  77. package/pkgs/schema/src/node.ts +80 -9
  78. package/pkgs/schema/src/snippet-resolve.ts +43 -0
  79. package/pkgs/schema/src/theme.ts +56 -0
  80. package/plugins/claude/velloo/agents/velloo-designer.md +7 -4
  81. package/plugins/claude/velloo/commands/setup.md +13 -0
  82. package/plugins/gemini/GEMINI.md +9 -5
  83. package/plugins/gemini/commands/velloo/setup.toml +11 -0
  84. package/skills/velloo-design/SKILL.md +11 -6
  85. package/skills/velloo-setup/SKILL.md +179 -36
  86. package/canvas/assets/index-BQ5710lu.js +0 -29
  87. package/canvas/assets/index-GNLd0pCG.css +0 -2
  88. package/canvas/assets/lucide-all-DIRZdJPK.js +0 -1
  89. package/chunk-brnkprt5.js +0 -723
  90. package/chunk-bys7pqdb.js +0 -2
  91. package/chunk-g8xrwjvq.js +0 -22
  92. package/chunk-jbgde2v9.js +0 -2
  93. package/chunk-rxkvjyst.js +0 -18
  94. package/chunk-sjjnm4a1.js +0 -2
  95. package/chunk-snak5zpr.js +0 -5
@@ -0,0 +1,22 @@
1
+ // @bun
2
+ import{isCancel,confirm,log,cancel,note,spinner,select,text}from"./chunk-80fjfyha.js";import{designNameIssue,CURRENT_SCHEMA_VERSION,schemaVersionOf,APP_PATH_PREFIX,planMigration,ConfigSchema}from"./chunk-w40pqmyz.js";import{writeJsonAtomic,managedDesignPath,managedDesignId,localDesignOf,writeLocalDesign,removeLocalDesign,resolveAppPath,recordedDesignName,pickDesign,readRepoFeedback,writeRepoFeedback,writeFeedbackContactOk,loadDesignFolder,hostAppRootFrom,recordThemeSource,topUpTokens}from"./chunk-yp39f93e.js";import{CHROMIUM_INSTALL_CMD,chromiumExecutable}from"./chunk-n70zfv0m.js";import{PROJECT_AGENT_IDS,resolveProjectRoot,manualSetupText,askAgentWiring,globallyWiredAgents,connect}from"./chunk-2x5rw009.js";import{TOOL_VERSION}from"./chunk-g7pbfad5.js";import{fail}from"./chunk-s23gtejf.js";import{daemonRoot,ensureDaemon,stopDaemon}from"./chunk-f8jchnwe.js";import{detectHost,findComponentsDir}from"./chunk-gv209d5j.js";import{installedVellooBin,updateStatus,upgradeInstalledVelloo}from"./chunk-fejhav0p.js";import{dirExists,discoverScanRoots,scanApps,primaryApp,buildScreensFromScan,buildBoardsFromScan,hasAppToMatch,DEFAULT_THEME_PRESET,NEUTRAL_THEME_PRESET,isValidPreset,WIZARD_PROVIDERS,LIBRARY_IDS,DEFAULT_LIBRARY_ID,interactiveLibraryChoices,planInstall,scanAdoption,libraryForApp,libraryForSample,DEFAULT_STACK_ID,stackForFramework,isValidStack,importThemeFromDesignMd,isEmptyOrMissing,resolveTheme,buildScaffold,writeScaffold,displayPath,printSummary,printThemeImport,printExitInstructions,printScreenshotReadiness,promptShellCompletions}from"./chunk-02gpgqj4.js";import{loadCredential,saveCredential,verifyCredential,performDeviceLogin}from"./chunk-c11n1tve.js";import{installChromiumInteractive}from"./chunk-pasvz8xw.js";import{copyToClipboard}from"./chunk-vbk1qhdz.js";import{openUrl}from"./chunk-hggap8fq.js";import{upgradeFolder}from"./chunk-ysf9388d.js";import{findManifest,manifestListing,findDesigns,withoutDesign,isWithin,findGitRoot,chooseDesignName,registerDesign,registerLocalDesign,existingDesignFolder,isDesignFolderSync,isEmptyOrMissingSync,hasDesignConfig,resolveDesign}from"./chunk-z3r8px3d.js";import{defaultCloudUrl}from"./chunk-3f2p94wa.js";import{require_picocolors}from"./chunk-jrsknzjt.js";import{__toESM,defineCommand}from"./chunk-2smsg2ct.js";import{randomUUID as randomUUID2}from"crypto";import{dirname as dirname2,relative as relative7,resolve as resolve7}from"path";var import_picocolors11=__toESM(require_picocolors(),1);import{existsSync}from"fs";import{readFile}from"fs/promises";import{join,relative,resolve,sep}from"path";function isSentinel(path){return path==="binary"||path.startsWith("~/")}function toPosix(path){return path.split(sep).join("/")||"."}function isUnder(parent,child){let rel=relative(parent,child);return rel===""||!rel.startsWith("..")&&!/^(?:[\\/]|[A-Za-z]:)/.test(rel)}async function readConfig(folder){return ConfigSchema.parse(JSON.parse(await readFile(join(folder,".design","config.json"),"utf8")))}async function recordedAppRoot(designFolder){let folder=resolve(designFolder),local=localDesignOf(folder);if(local){let path=resolve(local.appRoot);return{path,kind:"local",localId:local.id,checkout:local.root,...appShape(path)}}let recorded=(await readConfig(folder)).hostApp?.root,path=recorded&&!isSentinel(recorded)?resolveAppPath(folder,recorded):resolve(folder,".."),found=await manifestListing(folder).catch(()=>null),designName=recordedDesignName(folder);return{path,kind:"in-repo",...designName?{designName}:{},...found?{manifestPath:found.path}:{},...appShape(path)}}function appShape(path){let exists=existsSync(path);return{exists,looksLikeApp:exists&&existsSync(join(path,"package.json"))}}function pathSlots(config){let slots=[];for(let[name,app]of Object.entries(config.hostApps??{}))slots.push({field:`hostApps.${name}.root`,kind:"folder",value:app.root,set:(next)=>{app.root=next}});for(let[name,library]of Object.entries(config.libraries)){if(library.source!=="in-repo")continue;slots.push({field:`libraries.${name}.componentsPath`,kind:"folder",value:library.componentsPath,set:(next)=>{library.componentsPath=next}})}let aliases=config.hostApp?.aliases;for(let[pattern,target]of Object.entries(aliases??{}))slots.push({field:`hostApp.aliases["${pattern}"]`,kind:"app",value:target,set:(next)=>{if(aliases)aliases[pattern]=next}});let include=config.hostApp?.components?.include;for(let[index,entry]of(include??[]).entries())slots.push({field:`hostApp.components.include[${index}]`,kind:"app",value:entry,onlyIfExists:!0,set:(next)=>{if(include)include[index]=next}});let codegen=config.codegen;if(codegen?.componentsDir!==void 0)slots.push({field:"codegen.componentsDir",kind:"app",value:codegen.componentsDir,set:(next)=>{codegen.componentsDir=next}});return slots}async function planAppRootChange(designFolder,newRoot){let folder=resolve(designFolder),current=await recordedAppRoot(folder),from=current.path,to=resolve(newRoot),change={from,to,rewritten:[]},local=current.kind==="local"&&current.localId!==void 0;if(current.kind==="local"&&current.localId&&current.checkout){if(!isUnder(current.checkout,to))throw Error(`An application root must live inside the design's checkout (${current.checkout}). ${to} is outside it.`);change.local={id:current.localId,root:current.checkout}}let config=await readConfig(folder);if(!local){let stored=config.hostApp?.root,next=toPosix(relative(folder,to));if(stored===void 0||!isSentinel(stored)&&next!==stored)change.rewritten.push({field:"hostApp.root",from:stored??"(unset)",to:next})}let nested=isUnder(from,to)||isUnder(to,from),staysPut=(abs,moved)=>{if(!nested)return!1;let here=existsSync(abs);if(here!==existsSync(moved))return here;return isUnder(to,abs)};for(let slot of pathSlots(config)){if(isSentinel(slot.value))continue;let appRef=slot.kind==="folder"&&slot.value.startsWith(APP_PATH_PREFIX),tail=slot.kind==="app"?/\/?\*?$/.exec(slot.value)?.[0]??"":"",stored=slot.value.slice(0,slot.value.length-tail.length),abs=slot.kind==="app"?resolve(from,stored):resolveAppPath(folder,stored);if(!isUnder(from,abs))continue;if(slot.onlyIfExists&&!existsSync(abs))continue;let stays=staysPut(abs,join(to,relative(from,abs))),followsRoot=slot.kind==="app"||appRef;if(stays!==followsRoot)continue;let next;if(!stays)next=toPosix(relative(folder,join(to,relative(from,abs))));else{let rel=abs===to?"":toPosix(relative(to,abs));if(appRef)next=`${APP_PATH_PREFIX}${rel||"."}`;else next=rel===""?tail.replace(/^\//,"")||".":`${rel}${tail}`}if(next!==slot.value)change.rewritten.push({field:slot.field,from:slot.value,to:next})}return change}async function applyAppRootChange(designFolder,change){let folder=resolve(designFolder);if(change.rewritten.length>0){let config=await readConfig(folder),patch=new Map(change.rewritten.map((r)=>[r.field,r.to])),hostRoot=patch.get("hostApp.root");if(hostRoot!==void 0)config.hostApp=config.hostApp?{...config.hostApp,root:hostRoot}:{root:hostRoot};for(let slot of pathSlots(config)){let next=patch.get(slot.field);if(next!==void 0)slot.set(next)}await writeJsonAtomic(join(folder,".design","config.json"),ConfigSchema.parse(config))}if(change.local)await writeLocalDesign(change.local.id,{root:change.local.root,appRoot:change.to,...managedDesignId(folder)?{}:{designPath:folder}})}async function appRootCandidates(near){let start=resolve(near),from=(await findManifest(start).catch(()=>null))?.dir??await findGitRoot(start)??start;return(await discoverScanRoots(from)).map((app)=>({dir:app.dir,rel:relative(from,app.dir)||"."}))}async function appRootIsNotAnApp(appRoot){let abs=resolve(appRoot);if(existsSync(join(abs,"package.json"))&&(await discoverScanRoots(abs))[0]?.dir===abs)return null;let candidates=(await appRootCandidates(abs)).filter((c)=>c.dir!==abs);return candidates.length>0?candidates:null}async function promptAppRootChoice(current,opts={}){let message=opts.message??"Which application is this design for?",currentHint=opts.currentHint??"recorded now",abs=resolve(current),candidates=await appRootCandidates(abs),options=candidates.map((c)=>({value:c.dir,label:c.rel,...c.dir===abs?{hint:currentHint}:{}}));if(!candidates.some((c)=>c.dir===abs))options.push({value:abs,label:current,hint:currentHint});if(options.length<=1)return null;let chosen=await select({message,options});if(isCancel(chosen))return null;return chosen}import{createHash,randomUUID}from"crypto";import{existsSync as existsSync2,lstatSync,realpathSync}from"fs";import{cp,lstat,mkdir,readdir,readFile as readFile2,rm}from"fs/promises";import{basename,dirname,join as join2,relative as relative2,resolve as resolve2,sep as sep2}from"path";function physicalDestination(path){if(lstatSync(path,{throwIfNoEntry:!1}))return realpathSync(path);let parent=dirname(path);return join2(physicalDestination(parent),relative2(parent,path))}var RUNTIME=[".design/cache",".velloo","node_modules"];async function rebaseDesignConfig(source,destination,appRoot,external){let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(destination,".design/config.json"),"utf8"))),rebase=(path)=>{if(path==="binary"||path.startsWith("~/"))return path;let abs=resolveAppPath(source,path),withinDesign=relative2(source,abs);if(withinDesign===""||withinDesign!==".."&&!withinDesign.startsWith(`..${sep2}`)&&!/^(?:[\\/]|[A-Za-z]:)/.test(withinDesign))return withinDesign.split(sep2).join("/")||".";return external?`${APP_PATH_PREFIX}${relative2(appRoot,abs).split(sep2).join("/")||"."}`:relative2(destination,abs).split(sep2).join("/")||"."};config.hostApp=config.hostApp?{...config.hostApp,root:rebase(config.hostApp.root)}:{root:rebase("..")};for(let app of Object.values(config.hostApps??{}))app.root=rebase(app.root);for(let library of Object.values(config.libraries))if(library.componentsPath)library.componentsPath=rebase(library.componentsPath);await writeJsonAtomic(join2(destination,".design/config.json"),config)}async function fingerprint(folder){let hash=createHash("sha256");async function walk(rel){if(rel===".git"||RUNTIME.some((p)=>rel===p||rel.startsWith(`${p}/`)))return;let path=join2(folder,rel),stat=await lstat(path);if(stat.isSymbolicLink())throw Error(`Cannot relocate symbolic link ${path}. Replace it with its actual design content first.`);if(stat.isDirectory())for(let name of(await readdir(path)).sort())await walk(rel?`${rel}/${name}`:name);else if(stat.isFile())hash.update(rel).update("\x00").update(await readFile2(path));else throw Error(`Unsupported filesystem entry: ${path}`)}return await walk(""),hash.digest("hex")}async function planRelocation(source,cwd,to,external){if(Boolean(to)===external)throw Error("Choose exactly one destination: --external or --to <path>.");let designs=await findDesigns(cwd),physicalSource=realpathSync(source),local=designs?.local.find((design)=>realOr(design.designRoot)===physicalSource),repo=designs?.repo??null,index=repo?.folders.findIndex((path)=>existsSync2(path)&&realpathSync(path)===physicalSource)??-1;if(!local&&index===-1)throw Error("Run relocation from the checkout the design belongs to; the source must be one of its designs.");let root=local?.root??repo?.dir,name=recordedDesignName(source);if(!name)throw Error(`${source} has no design name \u2014 run \`velloo upgrade\` first.`);let physicalRoot=realpathSync(root);if(physicalSource===physicalRoot)throw Error("Cannot relocate the application repository itself. Use a separate design directory.");if(external&&managedDesignId(source))throw Error("This design already lives in managed storage.");let destination=external?managedDesignPath(local?.id??randomUUID()):resolve2(cwd,to??""),physicalTarget=physicalDestination(destination),inRepo=!external&&isWithin(physicalRoot,physicalTarget);if(physicalTarget===physicalSource||physicalTarget.startsWith(physicalSource+sep2)||physicalSource.startsWith(physicalTarget+sep2))throw Error("Source and destination cannot contain each other.");if(existsSync2(destination))throw Error(`Destination is occupied: ${destination}. Choose a new path; nothing was changed.`);let manifestPath=repo?.path??join2(root,"velloo.json"),before=repo?await readFile2(repo.path,"utf8"):null,manifest,destinationManifestPath;if(repo?.legacy)throw Error(`${repo.path} is in the pre-designs format \u2014 run \`velloo upgrade\` first.`);if(inRepo){destinationManifestPath=relative2(physicalRoot,physicalTarget).split(sep2).join("/")||".";let designs=[...repo?.manifest.designs??[]];if(index===-1)designs.push(destinationManifestPath);else designs[index]=destinationManifestPath;manifest={...repo?.manifest??{},designs}}else if(repo&&index!==-1)manifest=withoutDesign(repo.manifest,index,name);let config=ConfigSchema.parse(JSON.parse(await readFile2(join2(source,".design/config.json"),"utf8")));return{source,destination,root,appRoot:local?.appRoot??hostAppRootFrom(source,config.hostApp),designName:name,sourceLocalId:local?.id,sourceManifestPath:index===-1?void 0:repo?.manifest.designs[index],destinationManifestPath,destinationLocal:inRepo?void 0:{id:local?.id??(external?basename(destination):randomUUID()),...external?{}:{designPath:destination}},manifestPath,before,manifest}}function realOr(path){return existsSync2(path)?realpathSync(path):resolve2(path)}async function relocateDesign(plan){await stopDaemon(daemonRoot(plan.source));let original=await fingerprint(plan.source);await mkdir(dirname(plan.destination),{recursive:!0}),await mkdir(plan.destination);let committed=!1;try{for(let entry of await readdir(plan.source))await cp(join2(plan.source,entry),join2(plan.destination,entry),{recursive:!0,errorOnExist:!0,force:!1,filter:(path)=>!RUNTIME.some((p)=>{let rel=relative2(plan.source,path).split(sep2).join("/");return rel===p||rel.startsWith(`${p}/`)})});if(await fingerprint(plan.destination)!==original)throw Error("Copied content did not match the source.");if(await rebaseDesignConfig(plan.source,plan.destination,plan.appRoot,plan.destinationLocal!==void 0),await loadDesignFolder(plan.destination,{preferences:!1}),await fingerprint(plan.source)!==original)throw Error("The source changed during relocation. Close editors and retry.");if(await readFile2(plan.manifestPath,"utf8").catch(()=>null)!==plan.before)throw Error("The manifest changed during relocation. Review it and retry.");if(plan.destinationLocal){if(plan.sourceLocalId&&plan.sourceLocalId!==plan.destinationLocal.id)await removeLocalDesign(plan.sourceLocalId);await writeLocalDesign(plan.destinationLocal.id,{root:plan.root,appRoot:plan.appRoot,...plan.destinationLocal.designPath?{designPath:plan.destinationLocal.designPath}:{}})}else if(plan.sourceLocalId)await removeLocalDesign(plan.sourceLocalId);if(plan.manifest===null)await rm(plan.manifestPath,{force:!0});else if(plan.manifest)await writeJsonAtomic(plan.manifestPath,plan.manifest);committed=!0}finally{if(!committed)await rm(plan.destination,{recursive:!0,force:!0})}try{await rm(plan.source,{recursive:!0})}catch(error){throw Error(`Relocation completed to ${plan.destination}, but the old copy remains at ${plan.source}. Remove it after checking the destination. ${error}`)}}var import_picocolors=__toESM(require_picocolors(),1);async function offerUpgradeBeforeInit(argv){if(process.env.VELLOO_DISABLE_UPDATE_CHECK==="1"||!process.stdin.isTTY)return!1;let status;try{status=await updateStatus({refresh:!0})}catch{return!1}if(!status.available||!status.upgradable||!status.latest)return!1;console.log(""),console.log(`${import_picocolors.default.yellow("A newer velloo is available:")} ${status.current} \u2192 ${import_picocolors.default.bold(status.latest)}`);let yes=await confirm({message:"Upgrade before setting up this design folder?",initialValue:!0});if(isCancel(yes)||!yes)return console.log(import_picocolors.default.dim(" Continuing on the current version.")),!1;try{if(!(await upgradeInstalledVelloo()).upgraded)return!1;let bin=installedVellooBin();if(!bin)return console.log(import_picocolors.default.dim(" Upgraded. Run `velloo init` again to continue on the new version.")),!0;let code=await Bun.spawn([bin,...argv],{stdin:"inherit",stdout:"inherit",stderr:"inherit",env:{...process.env,VELLOO_DISABLE_UPDATE_CHECK:"1"}}).exited;process.exit(code)}catch(error){return console.log(import_picocolors.default.yellow(` Could not upgrade (${error instanceof Error?error.message:String(error)}) \u2014 continuing on the current version.`)),!1}}import{resolve as resolve3}from"path";var START_TO_CONTENT={"redesign-screen":"redesign-screen","redesign-component":"component",custom:"custom",sample:"sample",blank:"blank",scratch:"sample",scan:"scan"};function isValidLibraryId(v){return LIBRARY_IDS.includes(v)}function isValidContent(v){return v==="sample"||v==="blank"||v==="scan"||v==="redesign-screen"||v==="component"||v==="custom"}function isValidStart(v){return v in START_TO_CONTENT}function shouldRunWizard(args,stdinIsTTY){if(args.nonInteractive)return!1;return stdinIsTTY}function answersFromArgs(args){if(args.library&&!isValidLibraryId(args.library))throw Error(`unknown --library ${JSON.stringify(args.library)}. Valid: ${LIBRARY_IDS.join(" | ")}.`);if(args.start&&!isValidStart(args.start))throw Error(`unknown --start ${JSON.stringify(args.start)}. Valid: redesign-screen | redesign-component | custom | sample | blank | scan.`);if(args.initialContent&&!isValidContent(args.initialContent))throw Error(`unknown --initial-content ${JSON.stringify(args.initialContent)}. Valid: sample | blank | scan | redesign-screen | component | custom.`);let themePreset=args.themePreset?.trim()||void 0;if(themePreset&&!isValidPreset(themePreset))throw Error(`unknown --theme-preset ${JSON.stringify(args.themePreset)}.`);let stack=args.stack?.trim()||void 0;if(stack&&!isValidStack(stack))throw Error(`unknown --stack ${JSON.stringify(args.stack)}. Valid: nextjs | vite | astro | remix.`);let appRoot=resolve3(args.folder??"."),folder=resolve3(appRoot,args.designFolder??"velloo"),library=args.library??DEFAULT_LIBRARY_ID,initialContent=args.initialContent??"sample";if(args.start)initialContent=START_TO_CONTENT[args.start]??initialContent;let screenName=args.screenName?.trim()||void 0,componentDescription=args.component?.trim()||void 0,customRequest=args.request?.trim()||void 0;if(initialContent==="component"&&!componentDescription)throw Error("--component is required for --start=redesign-component.");if(initialContent==="custom"&&!customRequest)throw Error("--request is required for --start=custom.");if(initialContent==="redesign-screen"&&!screenName&&args.start==="redesign-screen");let source=WIZARD_PROVIDERS[library].defaultSource;return{appRoot,scanRoot:appRoot,folder,library,source,componentsRelative:args.componentsDir??findComponentsDir(appRoot)??"src/components/ui",initialContent,themePreset,...args.designMd===!1?{useDesignMd:!1}:{},...stack?{stack}:{},...screenName?{screenName}:{},...componentDescription?{componentDescription}:{},...customRequest?{customRequest}:{}}}import{relative as relative3,sep as sep3}from"path";var SCREENS_PLACEHOLDER="{{screens}}";function appContext(answers){let appRels=[...new Set((answers.selectedRoutes??[]).map((r)=>r.appRel).filter(Boolean))];if(appRels.length>1)return[`It's a monorepo with ${appRels.length} apps (${appRels.map((r)=>`\`${r}\``).join(", ")}), one board each.`];let uiRel=relative3(answers.appRoot,answers.scanRoot).split(sep3).join("/");return uiRel&&!uiRel.startsWith("..")?[`The app lives in \`${uiRel}/\`.`]:[]}var SETUP="Set Velloo up for my app (theme, fonts, components).",RECREATE_BAR="keep fixing `compare_to_url`'s top mismatches and don't stop below 0.9. Start the app yourself.",ALTERNATIVES="Explore a few different directions beside it on the same board.";function steps(answers,...rest){return[...hasAppToMatch(answers)?[SETUP]:[],...rest].map((step,i)=>`${i+1}. ${step}`)}function wantsHandoff(answers){switch(answers.initialContent){case"scan":case"redesign-screen":case"component":case"custom":return!0;default:return!1}}function buildHandoffPrompt(answers,screens){return[...goalLines(answers,screens),...appContext(answers)].join(`
3
+ `)}function goalLines(answers,screens){switch(answers.initialContent){case"redesign-screen":return[`Use Velloo to redesign **${answers.screenName?.trim()||screens[0]?.name||screens[0]?.id||"the chosen screen"}**:`,...steps(answers,`Recreate the whole real page on its scaffolded screen \u2014 ${RECREATE_BAR}`,ALTERNATIVES)];case"component":return[`Use Velloo to redesign **${answers.componentDescription?.trim()||"the component"}**:`,...steps(answers,`Recreate it on the scaffolded board \u2014 ${RECREATE_BAR}`,ALTERNATIVES)];case"custom":return["Use Velloo to design this, with alternative directions side by side on the board:","",answers.customRequest?.trim()||"the design I described",...answers.captureUrl?["",`It's based on ${answers.captureUrl}: capture it with \`start_capture_session\` first \u2014 I'll sign in if needed.`]:hasAppToMatch(answers)?["",`First: ${SETUP}`]:[]];default:return[`Use Velloo to recreate my app's pages, ${screens.length>0?"one scaffolded screen each:":"one screen per route:"}`,...screens.length>0?[SCREENS_PLACEHOLDER]:[],...steps(answers,`Recreate each page top to bottom, the most important first \u2014 ${RECREATE_BAR}`,"Each screen has a desktop and a mobile frame; make both hold up.")]}}function expandHandoffPrompt(prompt,screens){if(!prompt.includes(SCREENS_PLACEHOLDER))return prompt;let list=screens.map((s)=>` - ${s.name||s.id}`).join(`
4
+ `);return prompt.split(SCREENS_PLACEHOLDER).join(list)}import{readFile as readFile3,rm as rm2,writeFile}from"fs/promises";import{tmpdir}from"os";import{join as join3}from"path";var import_picocolors2=__toESM(require_picocolors(),1);function detectEditor(){let env=(process.env.VISUAL||process.env.EDITOR||"").trim();if(env){let parts=env.split(/\s+/);if(parts[0]&&Bun.which(parts[0]))return parts}for(let cand of["nano","vim","vi"])if(Bun.which(cand))return[cand];return["vi"]}async function editPrompt(prompt){let file=join3(tmpdir(),`velloo-handoff-${process.pid}-${Date.now()}.md`);await writeFile(file,prompt,"utf8");let editor=detectEditor();try{return await Bun.spawn([...editor,file],{stdin:"inherit",stdout:"inherit",stderr:"inherit"}).exited,(await readFile3(file,"utf8")).trim()}catch{return null}finally{await rm2(file,{force:!0})}}var AGENT_LAUNCHERS=[{bin:"claude",label:"Claude Code",agentIds:["claude-code","claude-code-global"],argv:(p)=>["claude",p]},{bin:"cursor-agent",label:"Cursor CLI",agentIds:["cursor","cursor-global"],argv:(p)=>["cursor-agent",p]},{bin:"codex",label:"Codex CLI",agentIds:["codex","codex-global"],argv:(p)=>["codex",p]},{bin:"opencode",label:"opencode",agentIds:["opencode","opencode-global"],argv:(p)=>["opencode","--prompt",p]},{bin:"droid",label:"Droid",agentIds:["droid-global"],argv:(p)=>["droid",p]},{bin:"cline",label:"Cline",agentIds:["cline-global"],argv:(p)=>["cline",p]},{bin:"gemini",label:"Gemini CLI",agentIds:["gemini","gemini-global"],argv:(p)=>["gemini","-i",p]}];async function printAgentHandoff(answers,scaffold,interactive,wiredIds){if(!wantsHandoff(answers))return;let{screens}=scaffold,prompt=buildHandoffPrompt(answers,screens);console.log(import_picocolors2.default.bold(" Start your agent")),console.log(import_picocolors2.default.dim(" Paste this to your AI agent:")),console.log("");for(let line of prompt.split(`
5
+ `))console.log(import_picocolors2.default.cyan(` ${line}`));if(prompt.includes(SCREENS_PLACEHOLDER))console.log(""),console.log(import_picocolors2.default.dim(` ${SCREENS_PLACEHOLDER} is replaced with your selected screens when the prompt is sent (an agent can also discover them with list_screens).`));if(console.log(""),!interactive)return;let launchers=AGENT_LAUNCHERS.filter((l)=>Bun.which(l.bin)&&l.agentIds.some((id)=>wiredIds.includes(id))),first=launchers[0],action=await select({message:first?"Start velloo and launch your agent to do this now?":"No wired agent CLI to launch \u2014 what next?",options:[...launchers.map((l)=>({value:`launch:${l.bin}`,label:`Yes \u2014 launch ${l.label} with this prompt`})),...first?[{value:"edit",label:"Edit the prompt first",hint:`opens ${detectEditor()[0]??"your editor"}`}]:[],{value:"copy",label:"Copy the prompt to my clipboard"},{value:"skip",label:first?"No \u2014 I'll run it later":"Skip"}],initialValue:first?`launch:${first.bin}`:"copy"});if(isCancel(action)||action==="skip")return;if(action==="copy"){let copied=await copyToClipboard(expandHandoffPrompt(prompt,screens));console.log(copied?` ${import_picocolors2.default.green("\u2713")} Prompt copied \u2014 paste it into your agent.`:import_picocolors2.default.dim(" Couldn't reach a clipboard tool \u2014 copy the prompt printed above."));return}let finalPrompt=prompt,launcher=first;if(action.startsWith("launch:"))launcher=launchers.find((l)=>`launch:${l.bin}`===action);else{let edited=await editPrompt(prompt);if(edited===null){console.error(" Couldn't open an editor. Set $EDITOR and retry, or copy the prompt above.");return}if(edited===""){console.log(import_picocolors2.default.dim(" Prompt was emptied \u2014 nothing launched."));return}if(finalPrompt=edited,launchers.length>1){let pick=await select({message:"Launch which agent?",options:launchers.map((l)=>({value:l.bin,label:l.label})),...launchers[0]?{initialValue:launchers[0].bin}:{}});if(isCancel(pick))return;launcher=launchers.find((l)=>l.bin===pick)}}if(!launcher)return;finalPrompt=expandHandoffPrompt(finalPrompt,screens);let canvasUrl;try{canvasUrl=(await ensureDaemon(answers.folder)).canvasUrl}catch(err){console.error(` Couldn't start the canvas (${err.message}). Run \`velloo run ${answers.folder}\` yourself, then paste the prompt above.`);return}let openCanvas=await confirm({message:"Open the board in your browser to watch? (your agent runs here in this terminal and may ask for MCP approval first)",initialValue:!0});if(!isCancel(openCanvas)&&openCanvas)await openUrl(canvasUrl);console.log(""),console.log(` Canvas running at ${import_picocolors2.default.cyan(canvasUrl)}.`),console.log(import_picocolors2.default.dim(` Launching ${launcher.label} here \u2014 it may ask you to approve the velloo MCP server first.`)),await Bun.spawn(launcher.argv(finalPrompt),{stdout:"inherit",stderr:"inherit",stdin:"inherit"}).exited}var import_picocolors3=__toESM(require_picocolors(),1),RGB={amber:[255,171,31],coral:[255,111,77]},ANSI256={amber:214,coral:209},TAGLINE="Design like a developer. Build like a designer.",V=[" "," ","oooo ooo"," `88. .8' "," `88..8' "," `888' "," `8' "],E=[" "," "," .ooooo. ","d88' `88b","888ooo888","888 .o","`Y8bod8P'"],L=["oooo ","`888 "," 888 "," 888 "," 888 "," 888 ","o888o"],O=[" "," "," .ooooo. ","d88' `88b","888 888","888 888","`Y8bod8P'"],MARK=[" .o8888888o. ","d88 88b ","88 .o8888888o. ","88 d88 88 88b","88 88 88 88","Y88 88 88P 88"," `o8888888P' 88"," Y88 88P"," `o8888888P' "],MARK_OWN=[" ccccccccccc ","ccc ccc ","cc aaaaaccaaaa ","cc aaa cc aaa","cc aa cc aa","ccc aa ccc aa"," ccccaaccccc aa"," aaa aaa"," aaaaaaaaaaa "];function supportsTruecolor(){let colorterm=process.env.COLORTERM??"";if(/truecolor|24bit/i.test(colorterm))return!0;if(process.env.TERM_PROGRAM==="Apple_Terminal")return!1;let program=process.env.TERM_PROGRAM??"";if(["iTerm.app","vscode","ghostty","WarpTerminal","WezTerm"].includes(program))return!0;return/truecolor|-direct$/i.test(process.env.TERM??"")}function paint(frame,text){if(!text||!import_picocolors3.default.isColorSupported)return text;if(supportsTruecolor()){let[r,g,b]=RGB[frame];return`\x1B[38;2;${r};${g};${b}m${text}\x1B[39m`}return`\x1B[38;5;${ANSI256[frame]}m${text}\x1B[39m`}function paintMarkRow(chars,owners){let out="",i=0;while(i<chars.length){let who=owners[i],j=i+1;while(j<owners.length&&owners[j]===who)j++;let slice=chars.slice(i,j);out+=who==="c"?paint("coral",slice):who==="a"?paint("amber",slice):slice,i=j}return out}function renderLogo(){return[...MARK.map((chars,i)=>{let mark=paintMarkRow(chars,MARK_OWN[i]??""),k=i-1,v=V[k],o=O[k],right=v===void 0||o===void 0?"":` ${import_picocolors3.default.bold(`${v}${E[k]}${L[k]}${L[k]}`)}${paint("amber",o)} ${paint("coral",o)}`;return` ${mark}${right}`}),""," "+import_picocolors3.default.dim(TAGLINE)].join(`
6
+ `)}function printLogo(){console.log(""),console.log(renderLogo()),console.log("")}import{resolve as resolve4}from"path";var import_picocolors7=__toESM(require_picocolors(),1);import{join as join4,relative as relative5,sep as sep4}from"path";var import_picocolors6=__toESM(require_picocolors(),1);import{relative as relative4}from"path";var import_picocolors4=__toESM(require_picocolors(),1),DEFAULT_COMPONENTS_DIR="src/components/ui";function isAborted(value){return isCancel(value)}function subtitled(message,subtitle){return`${message}
7
+ ${import_picocolors4.default.dim(subtitle)}`}function subtitledText(message,subtitle){return`${message}
8
+ ${import_picocolors4.default.gray("\u2502")} ${import_picocolors4.default.dim(subtitle)}`}function noteSetup(appRoot,folder){note(import_picocolors4.default.dim(`App root: ${appRoot}
9
+ Design: ${folder}`),"Setup")}async function promptDesignMd(detected,appRoot,themePreset){let path=detected?.designMdPath;if(!path)return;let shown=relative4(appRoot,path)||path,stylesheet=detected.globalsCssPath,imported=importThemeFromDesignMd(path,themePreset);if(!imported){log.info(`${shown} names no color roles Velloo can map, so the theme comes from ${stylesheet?"your stylesheet":"a preset"}. Your design agents still follow its prose.`);return}let{semantic,semanticTotal}=imported.coverage,weak=semantic<semanticTotal/2,picked=await select({message:subtitled(`Theme your design from the "${imported.designSystem}" design system?`,`${shown} names ${semantic} of the ${semanticTotal} color roles Velloo themes with; the rest keep the preset's colors.`),options:[{value:!0,label:`Use ${shown}`,hint:`${semantic}/${semanticTotal} color roles`},{value:!1,label:stylesheet?`Use your stylesheet (${relative4(appRoot,stylesheet)})`:"Use a preset",hint:weak&&stylesheet?"recommended \u2014 the DESIGN.md maps few roles":"agents still follow the DESIGN.md's prose"}],initialValue:!(weak&&stylesheet)});return isAborted(picked)?null:picked}var import_picocolors5=__toESM(require_picocolors(),1);async function promptShareAndFeedback(appRoot){let cloudUrl=defaultCloudUrl(),signedIn=!1,answered=await readRepoFeedback(appRoot);if(answered)return log.info(`Feedback tool: ${answered.enabled?"on":"off"} ${import_picocolors5.default.dim("(already set for this repo)")}`),{};let existing=await loadCredential(cloudUrl),existingEmail=existing?await verifyCredential(cloudUrl,existing.token):null;if(existingEmail)note(`Signed in as ${existingEmail}.`,"Velloo cloud"),signedIn=!0;if(!signedIn){let ok=await promptSignIn(cloudUrl);if(ok===null)return null;signedIn=ok}if(!signedIn)return{};let details=["The `send_feedback` tool lets your agent send free-text product feedback","about Velloo itself \u2014 a confusing tool, a missing capability, something","that slowed it down. Never about your design or your project.","","How it behaves:"," - The agent always shows you the exact message and asks before sending."," - It is instructed to never include your design content, code, or"," file/repo paths \u2014 only a plain-prose description of the issue.",' - "Yes": anonymous by construction \u2014 the message is sent with a'," blind-signed token (RFC 9474) instead of your account, so the server"," can verify it came from a real signed-in user but cannot tell which"," one. The whole flow lives in velloo's open-source CLI, so you don't"," have to take the cloud's word for it.",' - "Yes \u2014 contact OK": sent from your account so we can reply by email.',` - "No": the tool is never registered, so the agent can't send anything.`].join(`
10
+ `),choice;for(;;){let picked=await select({message:"Enable the feedback tool? Your agent can send Velloo product feedback to improve it.",options:[{value:"yes",label:"Yes \u2014 anonymous feedback",hint:"agent always confirms with you before sending"},{value:"yes-contact",label:"Yes \u2014 and it's OK to contact me about it",hint:"we may follow up by email"},{value:"no",label:"No",hint:"the tool is disabled entirely"},{value:"details",label:"What exactly gets sent?",hint:"prints details, then re-asks"}],initialValue:"yes"});if(isAborted(picked))return null;if(picked!=="details"){choice=picked;break}note(details,"The feedback tool")}if(choice==="no")return{};if(choice==="yes"){let cred=await loadCredential(cloudUrl);if(cred){let spin=spinner();spin.start("Stocking anonymous feedback tokens"),await topUpTokens({url:cloudUrl,token:cred.token},10).then(()=>spin.stop("Anonymous feedback tokens ready")).catch(()=>spin.stop("Feedback enabled \u2014 tokens will be fetched on first send"))}}return{feedback:{enabled:!0,contactOk:choice==="yes-contact"}}}async function promptSignIn(cloudUrl){let wantShare=await confirm({message:"Share your designs for free? Sign up to publish branded share links.",initialValue:!0});if(isAborted(wantShare))return null;if(!wantShare)return!1;let spin=spinner(),signedIn=!1,controller=new AbortController,hadRaw=process.stdin.isRaw??!1;if(process.stdin.isTTY&&!hadRaw)process.stdin.setRawMode(!0),process.stdin.resume();let onKey=(buf)=>{if(buf[0]===27)controller.abort()};process.stdin.on("data",onKey);try{let cred=await performDeviceLogin(cloudUrl,({verificationUrl,userCode})=>{note(`Opening your browser to sign up (or sign in).
11
+ If it doesn't open, visit:
12
+ ${import_picocolors5.default.cyan(verificationUrl)}
13
+ and enter the code: ${import_picocolors5.default.bold(userCode)}
14
+
15
+ ${import_picocolors5.default.dim("Press Esc to skip and continue without signing in.")}`,"Sign up"),spin.start("Waiting for sign-in (Esc to skip)")},controller.signal);await saveCredential(cloudUrl,cred),spin.stop(`Signed in as ${cred.email}`),signedIn=!0}catch(err){if(controller.signal.aborted)spin.stop("Sign-in skipped \u2014 continuing without it.");else spin.stop("Sign-in failed"),note(`Couldn't sign in (${err instanceof Error?err.message:String(err)}).
16
+ You can run ${import_picocolors5.default.cyan("velloo login")} anytime later.`,"Heads up")}finally{if(process.stdin.off("data",onKey),controller.signal.aborted&&process.stdin.isTTY){let drain=()=>{};process.stdin.on("data",drain),await new Promise((r)=>setTimeout(r,150)),process.stdin.off("data",drain)}if(process.stdin.isTTY&&!hadRaw)process.stdin.setRawMode(!1),process.stdin.pause()}return signedIn}var UI_LIBRARY_NAMES={shadcn:"shadcn",html:"Server-rendered HTML",mui:"Material UI",antd:"Ant Design",chakra:"Chakra UI"};function describeDetected(d){let ui,canvas;if(d.uiLibrary==="shadcn")ui=`shadcn${d.shadcnStyle?` (${d.shadcnStyle})`:""}`,canvas="your app's own shadcn component files \u2014 Velloo's bundled copies stand in only where a file is missing, can't compile, or needs a canvas-safe adaptation (dialogs, menus, popovers)";else if(d.uiLibrary){let name=UI_LIBRARY_NAMES[d.uiLibrary];ui=name,canvas=Object.values(WIZARD_PROVIDERS).find((entry)=>entry.scanMatch?.(d))?.detectedCanvas??`real ${name} components bundled with Velloo`}else if(d.unsupportedUi)ui=`${d.unsupportedUi} (no Velloo adapter yet)`,canvas="Velloo's no-library primitives stand in";else ui="none detected",canvas="Velloo's primitives to start \u2014 the setup step finds the components your app has";return[`UI library: ${ui}`,`Canvas uses: ${canvas}`,`Tailwind: ${d.tailwindMajor?`v${d.tailwindMajor}`:"not detected"}`,`theme css: ${d.globalsCssPath??"not found \u2014 will use a preset"}`,...d.designMdPath?[`DESIGN.md: ${d.designMdPath} \u2014 your design agents follow it`]:[]].join(`
17
+ `)}function componentsDirFor(appRoot,scanRoot=appRoot,inherited){if(inherited)return inherited;let atRoot=findComponentsDir(appRoot);if(atRoot)return atRoot;let nested=scanRoot===appRoot?void 0:findComponentsDir(scanRoot);if(!nested)return DEFAULT_COMPONENTS_DIR;return join4(relative5(appRoot,scanRoot),nested).split(sep4).join("/")}async function resolveLibrary(ctx,initial=DEFAULT_LIBRARY_ID){if(ctx.pinnedLibrary){if(ctx.pinnedLibraryReason)log.info(`Component library: ${WIZARD_PROVIDERS[ctx.pinnedLibrary].label} ${import_picocolors6.default.dim(`(${ctx.pinnedLibraryReason})`)}`);return ctx.pinnedLibrary}let picked=await select({message:subtitled("Component library","What the canvas draws with, and what your emitted code imports."),options:interactiveLibraryChoices(),initialValue:initial});return isAborted(picked)?null:picked}async function tryAdoptLibraryFromApp(appRoot,scanDir,forSample=!1){let spin=spinner();spin.start("Detecting your app's UI library");try{let scanned=await scanApps(appRoot,scanDir),primary=scanned.apps[0],app=primary??scanned.roots[0],scanRoot=app?.dir??appRoot,detected=detectHost(scanRoot,appRoot),claimed=scanAdoption(detected),adopted=claimed??(app?(forSample?libraryForSample:libraryForApp)(detected):void 0);if(spin.stop(claimed?`Detected ${WIZARD_PROVIDERS[claimed.library].label}`:adopted?adopted.note:"No app found here \u2014 you'll pick a library next."),!adopted)return null;return{library:adopted.library,detected,scanRoot,stack:stackForFramework(primary?.framework)}}catch{return spin.stop("Couldn't scan the app \u2014 you'll pick a library next."),null}}async function promptLibraryThemePath(ctx,folder,agentWiring,initialContent,extra={},opts={}){let library=ctx.pinnedLibrary??DEFAULT_LIBRARY_ID;if(!opts.skipLibrary){let picked=await resolveLibrary(ctx);if(picked===null)return null;library=picked}let source=WIZARD_PROVIDERS[library].defaultSource,componentsRelative=componentsDirFor(ctx.appRoot,extra.scanRoot,ctx.inheritComponentsDir),themePreset=initialContent==="sample"?DEFAULT_THEME_PRESET:NEUTRAL_THEME_PRESET,useDesignMd=ctx.skipDesignMd?!1:await promptDesignMd(extra.detected,ctx.appRoot,themePreset);if(useDesignMd===null)return null;let share=await promptShareAndFeedback(ctx.appRoot);if(share===null)return null;return noteSetup(ctx.appRoot,folder),{appRoot:ctx.appRoot,scanRoot:extra.scanRoot??ctx.appRoot,folder,library,source,componentsRelative,initialContent,themePreset,...useDesignMd!==void 0?{useDesignMd}:{},stack:extra.stack??DEFAULT_STACK_ID,...agentWiring?{agentWiring}:{},...share,...extra}}async function promptRedesignScreen(ctx,folder,agentWiring){let how=await select({message:subtitled("Which screen should your agent redesign?","Scanning finds your real routes; typing a name works for a screen that doesn't exist yet."),options:[{value:"scan",label:"Pick from my app's routes",hint:"Scan routes and choose one"},{value:"type",label:"Type a screen name",hint:"e.g. Pricing, Settings, Checkout"}],initialValue:"scan"});if(isAborted(how))return null;let selectedRoutes,screenName,scanRoot=ctx.appRoot,detected,library=ctx.pinnedLibrary??DEFAULT_LIBRARY_ID,stack=DEFAULT_STACK_ID;if(how==="scan"){let spin=spinner();spin.start("Scanning your app's routes");let scanned=await scanApps(ctx.appRoot,ctx.scanDir),appsSuffix=scanned.apps.length>1?` across ${scanned.apps.length} apps`:"";if(spin.stop(scanned.routes.length>0?`Found ${scanned.routes.length} screen${scanned.routes.length===1?"":"s"}${appsSuffix}`:"No routes detected \u2014 type a screen name instead."),scanned.routes.length===0){let typed=await promptScreenName();if(typed===null)return null;screenName=typed}else{let rankPrimary=scanned.apps[0];if(scanned.apps.length>1){let lines=scanned.apps.map((a)=>`${import_picocolors7.default.cyan(a.rel||".")} \u2014 ${a.routes.length} screen${a.routes.length===1?"":"s"}`);note(lines.join(`
18
+ `),`Found ${scanned.apps.length} apps`)}let host=detectHost(rankPrimary?.dir??ctx.appRoot,ctx.appRoot);note(describeDetected(host),"Detected in your app");let picked=await pickOneScreen(scanned);if(picked===null)return null;selectedRoutes=[picked],screenName=picked.name;let primary=primaryApp(scanned.apps,[picked])??rankPrimary;if(scanRoot=primary?.dir??ctx.appRoot,primary&&primary!==rankPrimary)host=detectHost(primary.dir,ctx.appRoot);if(detected=host,stack=stackForFramework(primary?.framework),!ctx.pinnedLibrary)library=libraryForApp(host).library}}else{let typed=await promptScreenName();if(typed===null)return null;screenName=typed}if(!detected&&!ctx.pinnedLibrary){let adopted=await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir);if(adopted)note(describeDetected(adopted.detected),"Detected in your app"),detected=adopted.detected,scanRoot=adopted.scanRoot,library=adopted.library,stack=adopted.stack}let adoptedLibrary=detected?libraryForApp(detected).library:void 0,rest=await promptLibraryThemePath({...ctx,pinnedLibrary:ctx.pinnedLibrary??adoptedLibrary??library},folder,agentWiring,"redesign-screen",{screenName,selectedRoutes,detected,scanRoot,stack},{skipLibrary:Boolean(ctx.pinnedLibrary||adoptedLibrary)});if(!rest)return null;let finalLibrary=ctx.pinnedLibrary??adoptedLibrary??rest.library;return{...rest,library:finalLibrary,source:WIZARD_PROVIDERS[finalLibrary].defaultSource,scanRoot,...detected?{detected}:{},...selectedRoutes?{selectedRoutes}:{},...screenName?{screenName}:{}}}async function promptScreenName(){let typed=await text({message:"Screen name",placeholder:"e.g. Pricing",validate(value){if(!value?.trim())return"Enter a screen name.";return}});return isAborted(typed)?null:String(typed).trim()}async function pickOneScreen(scanned){let{routes}=scanned,choice=await select({message:"Which screen?",options:routes.map((r)=>({value:r.id,label:r.name,hint:r.routePath})),...routes[0]?{initialValue:routes[0].id}:{}});if(isAborted(choice))return null;return routes.find((r)=>r.id===choice)??null}async function promptSample(ctx,folder,agentWiring){let adopted=ctx.pinnedLibrary||!ctx.hasHostApp?null:await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir,!0),library=adopted?.library??await resolveLibrary(ctx);if(library===null)return null;let source=WIZARD_PROVIDERS[library].defaultSource,componentsRelative=componentsDirFor(ctx.appRoot,adopted?.scanRoot,ctx.inheritComponentsDir),share=await promptShareAndFeedback(ctx.appRoot);if(share===null)return null;return noteSetup(ctx.appRoot,folder),{appRoot:ctx.appRoot,scanRoot:adopted?.scanRoot??ctx.appRoot,folder,library,source,componentsRelative,initialContent:"sample",themePreset:DEFAULT_THEME_PRESET,stack:DEFAULT_STACK_ID,...agentWiring?{agentWiring}:{},...share}}async function buildBlankAnswers(ctx,folder,agentWiring,defaultLibrary="none"){let adopted=ctx.pinnedLibrary?null:await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir);if(adopted)note(describeDetected(adopted.detected),"Detected in your app"),note(`Using ${WIZARD_PROVIDERS[adopted.library].label}.`,"Library");let library=adopted?.library??await resolveLibrary(ctx,defaultLibrary);if(library===null)return null;let share=await promptShareAndFeedback(ctx.appRoot);if(share===null)return null;return noteSetup(ctx.appRoot,folder),{appRoot:ctx.appRoot,scanRoot:adopted?.scanRoot??ctx.appRoot,folder,library,source:WIZARD_PROVIDERS[library].defaultSource,componentsRelative:componentsDirFor(ctx.appRoot,adopted?.scanRoot,ctx.inheritComponentsDir),initialContent:"blank",themePreset:"zinc",stack:adopted?.stack??DEFAULT_STACK_ID,...adopted?{detected:adopted.detected}:{},...agentWiring?{agentWiring}:{},...share}}async function promptGoalWithAdoptedLibrary(ctx,folder,agentWiring,initialContent,extra={}){let adopted=ctx.pinnedLibrary?null:await tryAdoptLibraryFromApp(ctx.appRoot,ctx.scanDir);if(adopted)note(describeDetected(adopted.detected),"Detected in your app"),note(`Using ${WIZARD_PROVIDERS[adopted.library].label}.`,"Library");return promptLibraryThemePath({...ctx,pinnedLibrary:ctx.pinnedLibrary??adopted?.library},folder,agentWiring,initialContent,{...extra,...adopted?{detected:adopted.detected,scanRoot:adopted.scanRoot,stack:adopted.stack}:{}},{skipLibrary:Boolean(ctx.pinnedLibrary||adopted)})}function folderPathProblem(abs,shown){if(isDesignFolderSync(abs))return`${shown} is already a Velloo design folder \u2014 pick another path.`;if(!isEmptyOrMissingSync(abs))return`${shown} isn't empty \u2014 pick an empty path (or delete it first).`;return}function cancelled(){return cancel("Cancelled \u2014 no files were written."),{status:"abort"}}function outcome(answers){return answers?{status:"ok",answers}:cancelled()}function hostGoalOptions(hasHostApp){let selfContained=[{value:"sample",label:"Elsewhere welcome sample",hint:"Travel app with imagery, dark mode and three agentic trip explorations"},{value:"blank",label:"Blank",hint:"Empty canvas \u2014 you and your agent build it from nothing"}];if(!hasHostApp)return[{value:"capture-site",label:"Design from a live site",hint:"Open a browser, log in if needed, capture pages \u2014 then design from them"},...selfContained];return[{value:"redesign-screen",label:"Redesign a screen",hint:"Recreate one of your pages, then explore alternatives"},{value:"redesign-component",label:"Redesign a component",hint:"One region or widget \u2014 recreate it, then try variations"},{value:"custom",label:"Custom request",hint:"Describe any design you need and start there"},...selfContained]}async function promptBrief(opts){let answer=await text({message:subtitledText(opts.message,opts.subtitle),placeholder:opts.placeholder,validate:(value)=>opts.validate(value?.trim()??"")});return isAborted(answer)?null:String(answer).trim()}async function runInteractive(ctx){let folderDefault=ctx.secondFolder?"velloo-brand":"velloo",folderBase=ctx.folderBase??ctx.appRoot;if(ctx.presetFolder){let problem=folderPathProblem(resolve4(folderBase,ctx.presetFolder),ctx.presetFolder);if(problem)return cancel(problem),cancelled()}let folderInput=ctx.presetFolder??await text({message:subtitledText("Design folder name or path",ctx.secondFolder?"A second canvas in this repo \u2014 its own boards, theme, daemon and MCP endpoint.":"Your designs are plain files that live in this repo \u2014 commit them alongside your code."),placeholder:folderDefault,defaultValue:folderDefault,validate(value){let raw=(value||folderDefault).trim();if(raw==="")return"Path can't be empty.";return folderPathProblem(resolve4(folderBase,raw),raw)}});if(isAborted(folderInput))return cancelled();let folder=resolve4(folderBase,folderInput||folderDefault),root=folderBase,local=!isWithin(root,folder);if(local&&!ctx.presetFolder)log.info(`${folder} is outside ${root}, so it will be a local design: recorded only on this machine, not in velloo.json, and not version-controlled by this repo.`);let agentWiring;if(ctx.connectEnabled){let wiring=await askAgentWiring({skipWhenCovered:!0,projectRoot:root,globalOnly:local});if(wiring===null)return cancelled();agentWiring=wiring}let hasHostApp=(await discoverScanRoots(ctx.appRoot)).length>0,hostCtx={...ctx,hasHostApp},goal=await select({message:subtitled("How do you want to start your board?","Pick a real design task \u2014 your agent starts on it as soon as init finishes."),options:hostGoalOptions(hasHostApp),initialValue:hasHostApp?"redesign-screen":"sample"});if(isAborted(goal))return cancelled();if(goal==="redesign-screen")return outcome(await promptRedesignScreen(hostCtx,folder,agentWiring));if(goal==="redesign-component"){let desc=await promptBrief({message:"Component name or description",subtitle:"Whatever you'd call it in a code review \u2014 the agent finds it from this.",placeholder:"e.g. sidebar, pricing card, filter chip row",validate:(v)=>v?void 0:"Describe the component so the agent knows what to redesign."});if(desc===null)return cancelled();return outcome(await promptGoalWithAdoptedLibrary(hostCtx,folder,agentWiring,"component",{componentDescription:desc}))}if(goal==="custom"){let request=await promptBrief({message:"What design do you need?",subtitle:"A sentence is enough \u2014 it becomes the brief your agent works from.",placeholder:"e.g. a pricing page with three tiers and a FAQ",validate:(v)=>v?void 0:"Describe what you want designed."});if(request===null)return cancelled();return outcome(await promptGoalWithAdoptedLibrary(hostCtx,folder,agentWiring,"custom",{customRequest:request}))}if(goal==="capture-site"){let url=await promptBrief({message:"Site to design from",subtitle:"Init won't open it \u2014 your agent starts a capture session so you can log in first.",placeholder:"e.g. https://app.example.com/dashboard",validate(v){if(!v)return"Enter the URL of the site you want to design from.";try{let scheme=new URL(v).protocol;if(scheme!=="http:"&&scheme!=="https:")return"Use an http(s) URL."}catch{return"That doesn't look like a URL."}return}});if(url===null)return cancelled();return outcome(await promptGoalWithAdoptedLibrary(hostCtx,folder,agentWiring,"custom",{captureUrl:url,customRequest:`Recreate the pages I capture from ${url}, then explore alternatives.`}))}if(goal==="blank")return outcome(await buildBlankAnswers(ctx,folder,agentWiring));return outcome(await promptSample(hostCtx,folder,agentWiring))}var import_picocolors8=__toESM(require_picocolors(),1);var NOT_WIRED={wiredIds:[]};async function applyAgentWiring(folder,wiring){let result;if(wiring.agents.length>0)try{result=await connect({designFolder:folder,agents:wiring.agents,installSkill:!0})}catch{result=void 0}if(wiring.manual){console.log(""),console.log(import_picocolors8.default.bold(" Manual MCP setup"));for(let line of manualSetupText().split(`
19
+ `))console.log(` ${line}`)}return{connected:result,wiredIds:[...wiring.preWired,...result?.configs.map((c)=>c.agent)??[]]}}function printWired(outcome){let connected=outcome.connected;if(!connected||connected.configs.length===0)return;let wired=connected.configs.map((c)=>c.agent).join(" + ");if(console.log(""),console.log(import_picocolors8.default.bold(" Agents wired")),console.log(` ${import_picocolors8.default.green("\u2713")} ${wired} ${import_picocolors8.default.dim(`(MCP config under ${connected.projectRoot})`)}`),connected.plugin)console.log(import_picocolors8.default.dim(` + Claude Code plugin (skills \xB7 commands \xB7 subagents), enabled in ${connected.plugin.settingsPath}`));if(connected.skills?.length)console.log(import_picocolors8.default.dim(` + ${connected.skills.length} agent skill${connected.skills.length===1?"":"s"} (.agents/skills)`));if(connected.geminiExtension)console.log(import_picocolors8.default.dim(` + Gemini extension${connected.geminiExtension.linked?"":` (link it: gemini extensions link ${connected.geminiExtension.dir})`}`));if(connected.cursorRules?.installed)console.log(import_picocolors8.default.dim(" + Cursor rule"))}import{resolve as resolve6}from"path";var import_picocolors10=__toESM(require_picocolors(),1);import{mkdir as mkdir2,readdir as readdir2,readFile as readFile4,writeFile as writeFile2}from"fs/promises";import{join as join5,relative as relative6,resolve as resolve5}from"path";var import_picocolors9=__toESM(require_picocolors(),1);async function readConfig2(folder){return JSON.parse(await readFile4(join5(folder,".design","config.json"),"utf8"))??{}}async function readFolderFacts(folder,appRoot){let config=await readConfig2(folder),libraries=config.libraries??{},defaultLibrary=typeof config.defaultLibrary==="string"?config.defaultLibrary:"",library=libraries[defaultLibrary]?.id??Object.values(libraries)[0]?.id??"unknown",design;try{design=(await findDesigns(appRoot))?.designs.find((d)=>resolve5(d.root)===resolve5(folder))?.name}catch{}return{folder,library,schemaVersion:schemaVersionOf(config),pendingMigrations:planMigration(config).applied,toolVersionStale:config.toolVersion!==TOOL_VERSION,design}}function displayPath2(path){let rel=relative6(process.cwd(),path);return rel&&rel.length<path.length&&!rel.startsWith("../..")?rel:path}async function inheritedFromFolder(folder){try{let config=await readConfig2(folder),libraries=config.libraries??{},defaultLibrary=typeof config.defaultLibrary==="string"?config.defaultLibrary:"",codegen=config.codegen??{};return{library:libraries[defaultLibrary]?.id??Object.values(libraries)[0]?.id,componentsDir:codegen.componentsDir}}catch{return{library:void 0,componentsDir:void 0}}}function factsLine(facts,folder){let parts=[`${displayPath2(folder)}/`,facts.library,facts.pendingMigrations.length>0?`format v${facts.schemaVersion} \u2192 v${CURRENT_SCHEMA_VERSION}`:`format v${facts.schemaVersion} (current)`];if(facts.design)parts.push(`design "${facts.design}"`);return parts.join(" \xB7 ")}async function promptExistingFolderAction(facts,folder){let options=[];if(facts.pendingMigrations.length>0)options.push({value:"upgrade",label:"Upgrade folder format",hint:`v${facts.schemaVersion} \u2192 v${CURRENT_SCHEMA_VERSION}`});options.push({value:"another",label:"Create another design folder",hint:"a second canvas in this repo"},{value:"connect",label:"Connect agents",hint:"wire the MCP into Claude Code / Cursor"},{value:"scan",label:"Scan for new routes",hint:"add screens for routes you've since added"},{value:"theme",label:"Re-import theme from the app",hint:"pull the app's tokens again"},{value:"check",label:"Check setup",hint:"browser, agent wiring, velloo.json, host app"},{value:"open",label:"Open the canvas",hint:"velloo run"},{value:"cancel",label:"Cancel"}),log.info(import_picocolors9.default.dim(factsLine(facts,folder)));let action=await select({message:"Velloo is already set up here. What would you like to do?",options,initialValue:options[0]?.value??"cancel"});if(isCancel(action))return null;return action}async function runUpgrade(folder){let result=await upgradeFolder(folder);if(result.applied.length===0){console.log(import_picocolors9.default.dim(" Already on the current format \u2014 nothing to do."));return}console.log(`velloo: upgraded ${displayPath2(folder)} (v${result.from} \u2192 v${result.to})`);for(let step of result.applied)console.log(import_picocolors9.default.dim(` ${step}`));console.log(import_picocolors9.default.dim(` Refresh agent skills too with \`velloo upgrade ${displayPath2(folder)}\`.`))}async function runScan(folder,appRoot,scanDir){let scanned=await scanApps(appRoot,scanDir);if(scanned.routes.length===0){log.warn("No routes found \u2014 nothing to add.");return}let existing=[];try{existing=(await readdir2(join5(folder,"screens"))).filter((f)=>f.endsWith(".json")&&!f.endsWith(".annotations.json")).map((f)=>f.slice(0,-5))}catch{}let seen=new Set(existing),fresh=scanned.routes.filter((r)=>!seen.has(r.id));if(fresh.length===0){log.success(`All ${scanned.routes.length} routes already have screens \u2014 nothing to add.`);return}log.info(`${fresh.length} new route${fresh.length===1?"":"s"}: ${fresh.slice(0,8).map((r)=>r.routePath).join(", ")}${fresh.length>8?", \u2026":""}`);let go=await confirm({message:`Add ${fresh.length} placeholder screen(s) on a new board?`});if(isCancel(go)||!go){console.log(import_picocolors9.default.dim(" Nothing changed."));return}let libraries=(await readConfig2(folder)).libraries??{},libraryId=Object.values(libraries)[0]?.id??"shadcn-upstream",scanOpts=WIZARD_PROVIDERS[libraryId]?.scanScreenOpts??{hasBadge:!0},screens=buildScreensFromScan({routes:fresh,...scanOpts}),boards=buildBoardsFromScan({routes:fresh});await mkdir2(join5(folder,"screens"),{recursive:!0}),await mkdir2(join5(folder,"boards"),{recursive:!0});for(let screen of screens)await writeJson(join5(folder,"screens",`${screen.id}.json`),screen);let stamp=new Date().toISOString().slice(0,10),existingBoards=new Set((await readdir2(join5(folder,"boards")).catch(()=>[])).filter((f)=>f.endsWith(".json")&&!f.endsWith(".notes.json")).map((f)=>f.slice(0,-5)));for(let board of boards){let id=`${board.id}-${stamp}`,attempt=2;while(existingBoards.has(id))id=`${board.id}-${stamp}-${attempt++}`;existingBoards.add(id),await writeJson(join5(folder,"boards",`${id}.json`),{...board,id,name:`${board.name} \u2014 new routes ${stamp}`})}log.success(`Added ${screens.length} screen${screens.length===1?"":"s"} on ${boards.length} board${boards.length===1?"":"s"}.`)}async function runThemeReimport(folder,appRoot){let recorded=await recordedAppRoot(folder).catch(()=>null),scanRoot=recorded?.looksLikeApp?recorded.path:void 0;if(!scanRoot){let scanned=await scanApps(appRoot);scanRoot=(scanned.apps[0]??scanned.roots[0])?.dir??appRoot}let resolved=resolveTheme({appRoot,scanRoot,detected:detectHost(scanRoot,appRoot),initialContent:"blank"}),from=resolved.importedFrom??resolved.libraryDefaults;if(resolved.source.kind==="preset"||!from){log.warn("Couldn't find a theme to import \u2014 no stylesheet tokens, DESIGN.md, or MUI or Mantine theme in the app.");return}let shown=resolved.importedFrom?displayPath2(resolved.importedFrom):`${resolved.libraryDefaults}'s defaults (the app sets no theme of its own)`;log.info(`Found the app's theme in ${shown}.`);let go=await confirm({message:"Replace theme/default.json with the app's tokens? Custom edits to it are lost.",initialValue:!1});if(isCancel(go)||!go){console.log(import_picocolors9.default.dim(" Nothing changed."));return}await writeJson(join5(folder,"theme","default.json"),resolved.theme);let config=await readConfig2(folder);await writeJson(join5(folder,".design","config.json"),{...config,themeSource:recordThemeSource(recorded?.path??scanRoot,resolved.source)}),log.success(`Theme re-imported from ${shown}.`)}async function runCheckSetup(folder,appRoot){let facts=await readFolderFacts(folder,appRoot),config=await readConfig2(folder),ok=(s)=>console.log(` ${import_picocolors9.default.green("\u2713")} ${s}`),bad=(s)=>console.log(` ${import_picocolors9.default.yellow("!")} ${s}`);if(facts.pendingMigrations.length>0)bad(`folder format v${facts.schemaVersion} \u2014 v${CURRENT_SCHEMA_VERSION} available (\`velloo upgrade <design>\`)`);else ok(`folder format v${facts.schemaVersion} (current)`);if(facts.toolVersionStale)bad(`agent skills recorded for velloo ${String(config.toolVersion)} \u2014 refresh with \`velloo upgrade <design>\``);else ok(`agent skills current (velloo ${TOOL_VERSION})`);if(facts.design)ok(`listed as design "${facts.design}"`);else bad("not listed in velloo.json \u2014 commands must name the path");let app=await recordedAppRoot(folder).catch(()=>null);if(app)if(!app.exists)bad(`host app ${displayPath2(app.path)} no longer exists`);else if(!app.looksLikeApp)bad(`host app ${displayPath2(app.path)} holds no package.json`);else ok(`host app at ${displayPath2(app.path)}`);let wired=await globallyWiredAgents();if(wired.length>0)ok(`agents wired globally: ${wired.join(", ")}`);else bad('no globally wired agents \u2014 run init again and pick "Connect agents"');let browser=await chromiumExecutable();if(browser)ok("browser installed (screenshots + publish)");else bad(`no browser for screenshots \u2014 install with \`${CHROMIUM_INSTALL_CMD}\``);if(!facts.design){let go=await confirm({message:"List this design in velloo.json?"});if(!isCancel(go)&&go)try{let reg=await registerDesign(folder,appRoot);if(reg.created)log.success(`Listed design "${reg.name}" in velloo.json.`);else log.info("Already listed.")}catch(err){log.warn(err.message)}}if(app&&!app.looksLikeApp)await repairAppRoot(folder,app.path);if(!browser)await installChromiumInteractive()}async function repairAppRoot(folder,current){let go=await confirm({message:"Point this design at a different application?"});if(isCancel(go)||!go)return;let target=await promptAppRootChoice(current);if(!target){log.info("No other application found in this repo \u2014 `velloo design set-app-root --to <path>`.");return}let change=await planAppRootChange(folder,target);if(resolve5(change.to)===resolve5(change.from))return;await stopDaemon(daemonRoot(folder)),await applyAppRootChange(folder,change),log.success(`Application root is now ${displayPath2(change.to)}.`)}async function runOpenCanvas(folder){let rec=await ensureDaemon(folder);console.log(`velloo: canvas at ${rec.canvasUrl}`)}async function writeJson(path,value){await writeFile2(path,`${JSON.stringify(value,null,2)}
20
+ `,"utf8")}async function offerExistingFolderActions(appRoot,cliArgs){let designs=await findDesigns(appRoot),picked=designs?pickDesign(designs,appRoot):null,existing=(picked&&picked.reason!=="arbitrary"&&!cliArgs.designFolder?await resolveDesign(picked.design.root,"init",{cwd:appRoot,interactive:!0}):null)??(cliArgs.addFolder?await existingDesignFolder(appRoot)??resolve6(appRoot,"velloo"):resolve6(appRoot,cliArgs.designFolder??"velloo"));if(!await hasDesignConfig(existing))return{kind:"none"};let contextRoot=localDesignOf(existing)?.appRoot??appRoot,facts=await readFolderFacts(existing,contextRoot),action=cliArgs.addFolder?"another":await promptExistingFolderAction(facts,existing);if(action===null||action==="cancel")return console.log(import_picocolors10.default.dim(" Nothing changed.")),{kind:"handled"};if(action==="connect"){let wiring=await askAgentWiring({skipWhenCovered:!0,projectRoot:await resolveProjectRoot(existing),globalOnly:localDesignOf(existing)!==null}),wireOutcome=wiring?await applyAgentWiring(existing,wiring):NOT_WIRED;return printWired(wireOutcome),printExitInstructions(existing,wireOutcome),{kind:"handled"}}if(action!=="another"){if(action==="upgrade")await runUpgrade(existing);if(action==="scan")await runScan(existing,contextRoot,cliArgs.scanDir);if(action==="theme")await runThemeReimport(existing,contextRoot);if(action==="check")await runCheckSetup(existing,contextRoot);if(action==="open")await runOpenCanvas(existing);return{kind:"handled"}}return{kind:"another",inherited:await inheritedFromFolder(existing)}}var init_default=defineCommand({meta:{name:"init",description:"Scaffold a new Velloo design folder"},args:{folder:{type:"positional",required:!1,description:"Your app root \u2014 where Velloo installs (default: current directory)"},designFolder:{type:"string",description:"Design folder, relative to the app root (default: velloo)"},external:{type:"boolean",description:"Keep the design in Velloo-managed storage outside the application repository"},force:{type:"boolean",default:!1,description:"Allow scaffolding into a non-empty design folder"},nonInteractive:{type:"boolean",default:!1,description:"Skip the wizard and use defaults / flags"},connect:{type:"boolean",default:!0,description:"Wire your AI agents' MCP config + guidance \u2014 Claude Code / Cursor / Codex / Continue; non-interactive default wires Claude Code + Cursor (use --no-connect to skip)"},start:{type:"string",description:"Goal: redesign-screen | redesign-component | custom | sample | blank | scan (legacy multi-route)"},scanDir:{type:"string",description:"Subfolder to scan when your UI isn't at the root (e.g. web/frontend). Auto-detected if omitted."},library:{type:"string",description:`Component library: ${LIBRARY_IDS.join(" | ")} (default ${DEFAULT_LIBRARY_ID})`},componentsDir:{type:"string",description:"Upstream components subfolder inside your app (default src/components/ui)"},initialContent:{type:"string",description:"Initial content: sample | blank | redesign-screen | component | custom | scan"},screenName:{type:"string",description:"Screen name for --start=redesign-screen (optional if routes are scanned)"},component:{type:"string",description:"Component name or description for --start=redesign-component"},request:{type:"string",description:"Free-text design request for --start=custom"},themePreset:{type:"string",description:"Theme preset: elsewhere | indigo | violet | blue | emerald | rose | orange | amber | zinc"},designMd:{type:"boolean",default:!0,description:"Seed the theme from a DESIGN.md found at the app or repo root (use --no-design-md to keep the stylesheet / preset)"},stack:{type:"string",description:"Your app's stack \u2014 sets the emitted import alias: nextjs | vite | astro (@/components/ui) | remix (~/components/ui)"},name:{type:"string",description:"The design's name (default: derived from its folder, or the app it designs)"}},run:({args})=>runInit2(args)});async function runInit2(cliArgs){let appRoot=resolve7(cliArgs.folder??"."),launchRoot=appRoot,interactive=shouldRunWizard(cliArgs,Boolean(process.stdin.isTTY)),allowNonEmpty=cliArgs.force,secondFolder=!1,inherited={library:void 0,componentsDir:void 0};if(cliArgs.scanDir&&!await dirExists(resolve7(appRoot,cliArgs.scanDir)))fail("init",`--scan-dir "${cliArgs.scanDir}" doesn't exist under ${appRoot}.`);if(interactive&&await offerUpgradeBeforeInit(process.argv.slice(2)))return;if(interactive)printLogo();if(interactive&&!cliArgs.force&&!cliArgs.external){let existing=await offerExistingFolderActions(appRoot,cliArgs);if(existing.kind==="handled")return;if(existing.kind==="another")secondFolder=!0,inherited=existing.inherited}if(interactive&&!cliArgs.folder){let candidates=await appRootIsNotAnApp(appRoot).catch(()=>null);if(candidates){console.log(import_picocolors11.default.dim(` ${appRoot} holds ${candidates.length} app${candidates.length===1?"":"s"} but isn't one itself.`));let chosen=await promptAppRootChoice(appRoot,{currentHint:"this directory"});if(chosen)appRoot=chosen}}let external=cliArgs.external===!0,presetFolder=cliArgs.designFolder;if(external&&cliArgs.designFolder)fail("init","Choose --external or --design-folder, not both.");let candidateId=randomUUID2(),candidateFolder=managedDesignPath(candidateId);if(interactive&&cliArgs.external===void 0&&!cliArgs.designFolder){let storage=await select({message:"Where should the design live?",options:[{value:"repository",label:"Default in repo",hint:secondFolder?"./velloo-brand/":"./velloo/"},{value:"external",label:"Default out of repo",hint:`${displayPath(dirname2(candidateFolder))}/ \u2014 not version-controlled`},{value:"custom",label:"Custom name",hint:"Choose a design folder name or path"}]});if(isCancel(storage))return;if(external=storage==="external",storage==="repository")presetFolder=secondFolder?"velloo-brand":"velloo"}let managedId=external?candidateId:void 0,managedFolder=managedId?candidateFolder:void 0,promptedName;if(interactive&&managedFolder&&!cliArgs.name){if(promptedName=await promptDesignName(managedFolder,appRoot,launchRoot),promptedName===void 0)return}let answers;if(interactive){if(console.log(import_picocolors11.default.dim(` App root: ${appRoot} (the app this design targets)`)),managedFolder)console.log(import_picocolors11.default.dim(` Design: ${displayPath(managedFolder)} (outside the repo, not version-controlled)`));else if(presetFolder)console.log(import_picocolors11.default.dim(` Design: ${displayPath(resolve7(launchRoot,presetFolder))}`));if(launchRoot!==appRoot)console.log(import_picocolors11.default.dim(` Design folder and agent config go under ${launchRoot}.`));console.log("");let inheritedLibrary=inherited.library&&isValidLibraryId(inherited.library)?inherited.library:void 0,result=await runInteractive({appRoot,folderBase:launchRoot,secondFolder,...managedFolder||presetFolder?{presetFolder:managedFolder??presetFolder}:{},scanDir:cliArgs.scanDir,connectEnabled:cliArgs.connect!==!1,pinnedLibrary:cliArgs.library&&isValidLibraryId(cliArgs.library)?cliArgs.library:inheritedLibrary,...inheritedLibrary&&!cliArgs.library?{pinnedLibraryReason:"same as the design folder already in this repo"}:{},...inherited.componentsDir?{inheritComponentsDir:inherited.componentsDir}:{},...cliArgs.designMd===!1?{skipDesignMd:!0}:{}});if(result.status==="abort")printExitInstructions(void 0,NOT_WIRED),process.exit(1);answers=result.answers}else{try{answers=answersFromArgs(cliArgs)}catch(err){fail("init",err.message)}console.log(`velloo: app root ${answers.appRoot}`)}let sample=answers.initialContent==="sample",scansRoutes=answers.initialContent==="scan"||answers.initialContent==="redesign-screen";if(!answers.detected&&!(sample&&interactive)){let scanned=await scanApps(answers.appRoot,cliArgs.scanDir),primary=scanned.apps[0],app=primary??scanned.roots[0];if(app)answers.scanRoot=app.dir;if(scansRoutes&&scanned.apps.length>1)console.log(import_picocolors11.default.dim(` Found ${scanned.apps.length} apps (${scanned.apps.map((a)=>a.rel||".").join(", ")}) \u2014 one board per app.`));else if(scansRoutes&&primary?.rel&&primary.rel!==".")console.log(import_picocolors11.default.dim(` Scanning UI in ${primary.rel} (app root has no package.json).`));if(scansRoutes){if(answers.selectedRoutes=answers.initialContent==="redesign-screen"?scanned.routes.slice(0,1):scanned.routes,answers.initialContent==="redesign-screen"&&scanned.routes[0])answers.screenName=answers.screenName??scanned.routes[0].name}let detected=detectHost(answers.scanRoot,answers.appRoot);if(!sample)answers.detected=detected;let adopted=cliArgs.library?void 0:app?(sample?libraryForSample:libraryForApp)(detected):scanAdoption(detected);if(adopted)answers.library=adopted.library,answers.source=sample?WIZARD_PROVIDERS[adopted.library].defaultSource:"binary",console.log(import_picocolors11.default.dim(` ${adopted.note}`))}if(managedFolder)answers.folder=managedFolder;let folder=answers.folder;if(!allowNonEmpty&&!await isEmptyOrMissing(folder))fail("init",`design folder is not empty: ${folder}
21
+ Pick an empty path, or pass --force to scaffold over it.`);let plan;try{plan=planInstall(answers)}catch(err){fail("init",err.message)}if(interactive)console.log(import_picocolors11.default.dim(" Scaffolding your design folder\u2026"));let{theme,source:themeSource,importedFrom,importedVia,tokenlessStylesheet,designMd,libraryDefaults,fonts,fontsFrom,leftForSetup}=resolveTheme(answers),scaffold;try{scaffold=await buildScaffold(answers,theme)}catch(err){fail("init",err.message)}let root=launchRoot,localId=managedId??(isWithin(root,folder)?void 0:randomUUID2()),name;try{name=await chooseDesignName({folder,appRoot:answers.appRoot,storage:localId?managedId?"managed":"chosen":"repository",checkout:root,requested:cliArgs.name??promptedName})}catch(err){fail("init",err.message)}let hostStyles;try{if(hostStyles=await writeScaffold({folder,scaffold,plan,answers,name,local:localId!==void 0,...designMd?{designSystemPath:designMd.path}:{},themeSource}),localId)await rebaseDesignConfig(folder,folder,answers.appRoot,!0)}catch(error){if(localId)throw Error(`Could not finish the design at ${folder}. Existing content was retained. Check write permissions and free disk space before retrying. ${error instanceof Error?error.message:error}`);throw error}if(console.log(`velloo: scaffolded ${folder} (${plan.library.id} ${plan.library.version})`),hostStyles){let copied=hostStyles.stored.filter((path)=>path.endsWith(".css")).length;console.log(import_picocolors11.default.dim(copied>0?` Copied ${copied} of the app's stylesheets into the design, so it looks like the app without it running.`:" Found none of the app's stylesheets on disk (built CSS appears once the app is built). Your agent copies them from a captured page with store_host_files."))}try{if(localId)await registerLocalDesign({id:localId,root,appRoot:answers.appRoot,...managedId?{}:{designPath:folder}}),console.log(import_picocolors11.default.dim(` Recorded as local design "${name}" for ${displayPath(root)} \u2014 on this machine only; nothing was added to the repository.`));else{let reg=await registerDesign(folder,root);if(reg.created)console.log(import_picocolors11.default.dim(` Listed design "${reg.name}" in ${relative7(process.cwd(),reg.path)||reg.path}.`))}if(answers.feedback)await writeRepoFeedback(folder,answers.feedback),await writeFeedbackContactOk(answers.feedback.contactOk===!0)}catch(err){if(localId)fail("init",`Design retained at ${folder}, but registration failed: ${err.message}`);console.log(import_picocolors11.default.yellow(` Couldn't update the repo manifest: ${err.message}`))}if(printThemeImport(answers.appRoot,{importedFrom,importedVia,libraryDefaults,fonts,fontsFrom,leftForSetup}),tokenlessStylesheet)console.log(import_picocolors11.default.yellow(` Found ${relative7(answers.appRoot,tokenlessStylesheet)}, but no theme tokens in it or in the stylesheets it imports \u2014 your design starts on a preset instead.`)),console.log(import_picocolors11.default.dim(" Ask your agent to `import_theme` from the file that holds your colors (or `set_theme`, if the app is themed in JavaScript)."));if(designMd){let{coverage}=designMd;if(console.log(import_picocolors11.default.dim(` Read the "${designMd.name}" design system \u2014 ${coverage.semantic} of ${coverage.semanticTotal} color roles mapped, and the folder now follows that file (read live, never copied).`)),coverage.semantic<coverage.semanticTotal)console.log(import_picocolors11.default.dim(" The roles it didn't name kept the preset's colors \u2014 ask your agent to `import_theme` from your stylesheet if the canvas looks off."))}if(answers.initialContent==="scan"&&scaffold.screens.length===0)console.log(import_picocolors11.default.dim(" No routes detected \u2014 started you with a blank folder instead of a scan."));printSummary(folder,scaffold,plan,answers,{importedFrom,tokenlessStylesheet,libraryDefaults});let wireOutcome=NOT_WIRED;if(cliArgs.connect!==!1){let wiring=interactive?answers.agentWiring:localId?void 0:{agents:PROJECT_AGENT_IDS,manual:!1,preWired:[]};if(wiring)wireOutcome=await applyAgentWiring(folder,wiring);else if(localId&&!interactive)console.log(import_picocolors11.default.dim(" Agents not wired: a local design uses global configs \u2014 run `velloo connect`."))}printWired(wireOutcome),await printScreenshotReadiness(interactive),await promptShellCompletions(interactive),await printAgentHandoff(answers,scaffold,interactive,wireOutcome.wiredIds),printExitInstructions(folder,wireOutcome,{setup:hasAppToMatch(answers),handoff:wantsHandoff(answers)})}async function promptDesignName(folder,appRoot,checkout){let request={folder,appRoot,storage:"managed",checkout},suggestion=await chooseDesignName(request).catch(()=>{return});for(;;){let answer=await text({message:"Name this design",...suggestion?{placeholder:suggestion,initialValue:suggestion}:{},validate:(value)=>designNameIssue((value??"").trim())??void 0});if(isCancel(answer))return;try{return await chooseDesignName({...request,requested:answer.trim()})}catch(err){log.warn(err.message)}}}
22
+ export{recordedAppRoot,planAppRootChange,applyAppRootChange,promptAppRootChoice,planRelocation,relocateDesign,init_default,runInit2};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{COMMANDS}from"./chunk-acsv6m3n.js";var SHELLS=["zsh","bash","fish"],zshName=(name)=>name.replace(/\\/g,"\\\\").replace(/:/g,"\\:");function zshArguments(c,indent){let flagSpecs=c.flags.map((f)=>`${indent} '${f.flag}${f.takesValue?"=":""}[${f.description}]'`).join(" \\\n");return flagSpecs?`${indent}_arguments \\
2
+ import{COMMANDS}from"./chunk-seaar5na.js";import{existsSync}from"fs";import{appendFile,mkdir,readFile,writeFile}from"fs/promises";import{homedir}from"os";import{basename,dirname,join,sep}from"path";var SHELLS=["zsh","bash","fish"],zshName=(name)=>name.replace(/\\/g,"\\\\").replace(/:/g,"\\:");function zshArguments(c,indent){let flagSpecs=c.flags.map((f)=>`${indent} '${f.flag}${f.takesValue?"=":""}[${f.description}]'`).join(" \\\n");return flagSpecs?`${indent}_arguments \\
3
3
  ${flagSpecs} \\
4
4
  ${indent} '*:file:_files'`:`${indent}_files`}function zshScript(specs){let commandLines=specs.map((c)=>` '${zshName(c.name)}:${c.description}'`).join(`
5
5
  `),cases=specs.map((c)=>{if(c.subcommands.length===0)return` ${c.name})
@@ -79,7 +79,7 @@ complete -o default -F _velloo velloo
79
79
  `}function fishFlags(c,condition){return c.flags.map((f)=>{let long=f.flag.replace(/^--/,"");return`complete -c velloo -n "${condition}" -l ${long}${f.takesValue?" -r":""} -d "${f.description}"`})}function fishScript(specs){let lines=["# velloo shell completions (fish) \u2014 generated by `velloo completions`.","function __velloo_is"," set -l words"," for token in (commandline -opc)[2..-1]"," string match -q -- '-*' $token; or set -a words $token"," end",' test "$words[1]" = "$argv[1]"; or return 1'," test (count $argv) -lt 2; and return 0",' test "$words[2]" = "$argv[2]"',"end","function __velloo_words"," set -l words"," for token in (commandline -opc)[2..-1]"," string match -q -- '-*' $token; or set -a words $token"," end"," count $words","end"];for(let c of specs){if(lines.push(`complete -c velloo -f -n "__fish_use_subcommand" -a "${c.name}" -d "${c.description}"`),c.subcommands.length===0){lines.push(...fishFlags(c,`__velloo_is ${c.name}`));continue}for(let sub of c.subcommands)lines.push(`complete -c velloo -f -n "__velloo_is ${c.name}; and test (__velloo_words) -eq 1" -a "${sub.name}" -d "${sub.description}"`),lines.push(...fishFlags(sub,`__velloo_is ${c.name} ${sub.name}`));let notSub=c.subcommands.map((sub)=>`; and not __velloo_is ${c.name} ${sub.name}`).join("");lines.push(...fishFlags(c,`__velloo_is ${c.name}${notSub}`))}return`${lines.join(`
80
80
  `)}
81
81
  `}function completionScript(shell,specs){switch(shell){case"zsh":return zshScript(specs);case"bash":return bashScript(specs);case"fish":return fishScript(specs)}}async function resolvable(value){return typeof value==="function"?await value():value}var kebab=(name)=>name.replace(/[A-Z]/g,(c)=>`-${c.toLowerCase()}`);function sanitize(desc){return(desc??"").split(`
82
- `)[0]?.replace(/['"[\]:`$\\]/g,"").trim()??""}function flagSpecs(args){let flags=[];for(let[argName,def]of Object.entries(args)){if(def.type==="positional")continue;let isBool=def.type==="boolean",negated=isBool&&def.default===!0;flags.push({flag:negated?`--no-${kebab(argName)}`:`--${kebab(argName)}`,description:sanitize(def.description),takesValue:!isBool})}return flags}async function commandSpec(name,load,depth){let cmd,meta,args;try{cmd=await resolvable(load),meta=cmd.meta?await resolvable(cmd.meta):void 0,args=cmd.args?await resolvable(cmd.args):{}}catch{return null}if(meta?.hidden)return null;let subcommands=[];if(depth===0&&cmd.subCommands)for(let[child,loadChild]of Object.entries(await resolvable(cmd.subCommands))){let spec=await commandSpec(child,loadChild,depth+1);if(spec)subcommands.push(spec)}return{name,description:sanitize(meta?.description),flags:flagSpecs(args),subcommands}}async function commandSpecs(){let out=[];for(let[name,load]of Object.entries(COMMANDS)){if(name.startsWith("__"))continue;let spec=await commandSpec(name,load,0);if(spec)out.push(spec)}return out}import{existsSync}from"fs";import{appendFile,mkdir,readFile,writeFile}from"fs/promises";import{homedir}from"os";import{basename,dirname,join,sep}from"path";function detectShell(env=process.env){let name=basename(env.SHELL??"");return SHELLS.includes(name)?name:null}var RC_MARKER="# velloo completions";function targets(shell,homeDir){switch(shell){case"zsh":return{scriptPath:join(homeDir,".velloo","completions","velloo.zsh"),rcPath:join(homeDir,".zshrc")};case"bash":return{scriptPath:join(homeDir,".velloo","completions","velloo.bash"),rcPath:join(homeDir,".bashrc")};case"fish":return{scriptPath:join(homeDir,".config","fish","completions","velloo.fish")}}}function completionsInstalled(homeDir=homedir(),shell){return(shell?[shell]:SHELLS).some((s)=>existsSync(targets(s,homeDir).scriptPath))}async function installCompletions(shell,homeDir=homedir()){let{scriptPath,rcPath}=targets(shell,homeDir),script=completionScript(shell,await commandSpecs());await mkdir(dirname(scriptPath),{recursive:!0}),await writeFile(scriptPath,script);let rcUpdated=!1;if(rcPath){let rc=await readFile(rcPath,"utf8").catch(()=>"");if(!rc.includes(RC_MARKER)){let rel=scriptPath.slice(homeDir.length+1).split(sep).join("/"),line=`[ -f "$HOME/${rel}" ] && source "$HOME/${rel}" ${RC_MARKER}`;await appendFile(rcPath,`${rc.endsWith(`
82
+ `)[0]?.replace(/['"[\]:`$\\]/g,"").trim()??""}function flagSpecs(args){let flags=[];for(let[argName,def]of Object.entries(args)){if(def.type==="positional")continue;let isBool=def.type==="boolean",negated=isBool&&def.default===!0;flags.push({flag:negated?`--no-${kebab(argName)}`:`--${kebab(argName)}`,description:sanitize(def.description),takesValue:!isBool})}return flags}async function commandSpec(name,load,depth){let cmd,meta,args;try{cmd=await resolvable(load),meta=cmd.meta?await resolvable(cmd.meta):void 0,args=cmd.args?await resolvable(cmd.args):{}}catch{return null}if(meta?.hidden)return null;let subcommands=[];if(depth===0&&cmd.subCommands)for(let[child,loadChild]of Object.entries(await resolvable(cmd.subCommands))){let spec=await commandSpec(child,loadChild,depth+1);if(spec)subcommands.push(spec)}return{name,description:sanitize(meta?.description),flags:flagSpecs(args),subcommands}}async function commandSpecs(){let out=[];for(let[name,load]of Object.entries(COMMANDS)){if(name.startsWith("__"))continue;let spec=await commandSpec(name,load,0);if(spec)out.push(spec)}return out}function detectShell(env=process.env){let name=basename(env.SHELL??"");return SHELLS.includes(name)?name:null}var RC_MARKER="# velloo completions";function targets(shell,homeDir){switch(shell){case"zsh":return{scriptPath:join(homeDir,".velloo","completions","velloo.zsh"),rcPath:join(homeDir,".zshrc")};case"bash":return{scriptPath:join(homeDir,".velloo","completions","velloo.bash"),rcPath:join(homeDir,".bashrc")};case"fish":return{scriptPath:join(homeDir,".config","fish","completions","velloo.fish")}}}function completionsInstalled(homeDir=homedir(),shell){return(shell?[shell]:SHELLS).some((s)=>existsSync(targets(s,homeDir).scriptPath))}async function installCompletions(shell,homeDir=homedir()){let{scriptPath,rcPath}=targets(shell,homeDir),script=completionScript(shell,await commandSpecs());await mkdir(dirname(scriptPath),{recursive:!0}),await writeFile(scriptPath,script);let rcUpdated=!1;if(rcPath){let rc=await readFile(rcPath,"utf8").catch(()=>"");if(!rc.includes(RC_MARKER)){let rel=scriptPath.slice(homeDir.length+1).split(sep).join("/"),line=`[ -f "$HOME/${rel}" ] && source "$HOME/${rel}" ${RC_MARKER}`;await appendFile(rcPath,`${rc.endsWith(`
83
83
  `)||rc===""?"":`
84
84
  `}${line}
85
85
  `),rcUpdated=!0}}return{shell,scriptPath,rcPath,rcUpdated}}
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{recordedDesignName}from"./chunk-brnkprt5.js";import{displayPath}from"./chunk-mdgwdqnq.js";import{basename,relative,resolve}from"path";function designWithFolder(folder,name,opts={}){let shown=name??recordedDesignName(folder)??basename(folder),rel=relative(resolve("."),folder),where=rel!==""&&!rel.startsWith("..")&&!opts.absolute?`./${rel}`:displayPath(folder);return`"${shown}" (${where})`}
2
+ import{recordedDesignName}from"./chunk-yp39f93e.js";import{displayPath}from"./chunk-02gpgqj4.js";import{basename,relative,resolve}from"path";function designWithFolder(folder,name,opts={}){let shown=name??recordedDesignName(folder)??basename(folder),rel=relative(resolve("."),folder),where=rel!==""&&!rel.startsWith("..")&&!opts.absolute?`./${rel}`:displayPath(folder);return`"${shown}" (${where})`}
3
3
  export{designWithFolder};