@sugarcube-org/cli 0.0.0-alpha.21 → 0.0.0-alpha.22

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 (2) hide show
  1. package/dist/index.mjs +38 -38
  2. package/package.json +1 -1
package/dist/index.mjs CHANGED
@@ -1,18 +1,18 @@
1
1
  #!/usr/bin/env node
2
- var ze=Object.defineProperty;var o=(e,t)=>ze(e,"name",{value:t,configurable:!0});import{Command as j}from"commander";import{relative as $,join as R,basename as B,resolve as L,dirname as Ze,normalize as Qe}from"pathe";import c from"picocolors";import{existsSync as F,readFileSync as Se}from"node:fs";import Xe from"node-fetch";import{z as m}from"zod";import se,{mkdir as V,writeFile as X,readFile as et}from"node:fs/promises";import{execa as tt}from"execa";import{loadAndResolveTokens as nt,validateConfig as st,configFileExists as A,loadInternalConfig as ee,loadUserConfig as ot,processAndConvertTokens as oe,generateCSSVariables as Ie,writeCSSVariablesToDisk as Ee,writeCSSUtilitiesToDisk as ke,convertConfigToUnoRules as rt,DEFAULT_STYLES_PATH as it,DEFAULT_CONFIG as re,fillDefaults as at}from"@sugarcube-org/core";import ct from"is-unicode-supported";import ie,{resolve as lt}from"node:path";import{select as ut,isCancel as ae,log as ft,multiselect as pt,confirm as dt,cancel as be}from"@clack/prompts";import{getColumns as gt}from"@clack/core";import{wrapAnsi as mt}from"fast-wrap-ansi";import*as Ce from"node:readline";import $e from"node:readline";import{createLogUpdate as Re}from"log-update";import{detect as ht}from"@antfu/ni";import{getTsconfig as wt}from"get-tsconfig";import{createGenerator as yt}from"@unocss/core";import ce from"fast-glob";var Tt="0.0.0-alpha.21",St={version:Tt};const le="fluid",_e="**/*.json",ue="@sugarcube-org/vite",It=["node_modules",".git",".next","dist","build"],Et=5,v={INIT:"make-sugarcube init",COMPONENTS:"make-sugarcube components",GENERATE:"make-sugarcube generate",CUBE:"make-sugarcube cube"},De={INITIALIZATION:"https://sugarcube.sh/docs/setup",CONFIGURATION:"https://sugarcube.sh/docs/configuration"},w={PROJECT_REQUIRED:`No sugarcube project detected. Please run ${c.cyan(v.INIT)} first.
2
+ var Qe=Object.defineProperty;var o=(e,t)=>Qe(e,"name",{value:t,configurable:!0});import{Command as j}from"commander";import{relative as $,join as _,basename as W,resolve as L,dirname as Xe,normalize as et}from"pathe";import c from"picocolors";import{existsSync as F,readFileSync as Se}from"node:fs";import tt from"node-fetch";import{z as m}from"zod";import se,{mkdir as V,writeFile as X,readFile as nt}from"node:fs/promises";import{execa as st}from"execa";import{loadAndResolveTokens as ot,validateConfig as rt,configFileExists as A,loadInternalConfig as ee,loadUserConfig as it,processAndConvertTokens as oe,generateCSSVariables as Ie,writeCSSVariablesToDisk as Ee,writeCSSUtilitiesToDisk as ke,convertConfigToUnoRules as at,DEFAULT_STYLES_PATH as ct,DEFAULT_CONFIG as re,fillDefaults as lt}from"@sugarcube-org/core";import ut from"is-unicode-supported";import ie,{resolve as ft}from"node:path";import{select as dt,isCancel as ae,log as pt,multiselect as gt,confirm as mt,cancel as be}from"@clack/prompts";import{getColumns as ht}from"@clack/core";import{wrapAnsi as wt}from"fast-wrap-ansi";import*as Ce from"node:readline";import $e from"node:readline";import{createLogUpdate as _e}from"log-update";import{detect as yt}from"@antfu/ni";import{getTsconfig as Tt}from"get-tsconfig";import{createGenerator as St}from"@unocss/core";import ce from"fast-glob";var It="0.0.0-alpha.22",Et={version:It};const le="fluid",Re="**/*.json",ue="@sugarcube-org/vite",kt=["node_modules",".git",".next","dist","build"],bt=5,N={INIT:"make-sugarcube init",COMPONENTS:"make-sugarcube components",GENERATE:"make-sugarcube generate",CUBE:"make-sugarcube cube"},De={INITIALIZATION:"https://sugarcube.sh/docs/setup",CONFIGURATION:"https://sugarcube.sh/docs/configuration"},w={PROJECT_REQUIRED:`No sugarcube project detected. Please run ${c.cyan(N.INIT)} first.
3
3
 
4
4
  For more information, visit: ${c.cyan(De.INITIALIZATION)}`,CONFIG_EXISTS:o(()=>`A sugarcube config file already exists in this projct.
5
5
 
6
- To start over, remove it and run ${c.cyan(v.INIT)} again.`,"CONFIG_EXISTS"),PLUGIN_INSTALL_FAILED:o(e=>`Failed to install ${e.pluginToInstall} plugin.
6
+ To start over, remove it and run ${c.cyan(N.INIT)} again.`,"CONFIG_EXISTS"),PLUGIN_INSTALL_FAILED:o(e=>{const t=e.packageManager==="npm"?"install":"add";return`Failed to install ${e.pluginToInstall} plugin.
7
7
 
8
8
  This is usually a temporary issue. Try these steps:
9
9
 
10
10
  1. Run the command again
11
11
  2. Check your internet connection
12
- 3. Install manually: ${e.packageManager} add ${e.pluginToInstall}
12
+ 3. Install manually: ${e.packageManager} ${t} ${e.pluginToInstall}
13
13
 
14
14
  If the problem continues, please open an issue at:
15
- https://github.com/sugarcube-org/sugarcube/issues`,"PLUGIN_INSTALL_FAILED"),INITIALIZATION_INCOMPLETE:o(()=>`The initialization process was not completed properly.
15
+ https://github.com/sugarcube-org/sugarcube/issues`},"PLUGIN_INSTALL_FAILED"),INITIALIZATION_INCOMPLETE:o(()=>`The initialization process was not completed properly.
16
16
  This is an internal error that should not occur.
17
17
  Try running the \`init\` command again.
18
18
 
@@ -60,8 +60,8 @@ The 'generate' command is for manual generation without plugins. Since you have
60
60
 
61
61
  npm run dev # or your framework's dev command
62
62
 
63
- The plugin will automatically generate CSS with hot module replacement.`,"PLUGIN_DETECTED")};class g extends Error{static{o(this,"CLIError")}constructor(t,n){super(t),this.name="CLIError",this.cause=n}}const fe=m.enum(["react","web-components","css-only"]),Ae=m.object({path:m.string(),type:m.string()}),kt=Ae.extend({framework:fe});m.object({modes:m.record(m.string(),m.array(m.string())).optional(),themes:m.record(m.string(),m.array(m.string())).optional()}).strict();const bt=m.object({name:m.string(),type:m.string(),description:m.string().optional(),frameworks:m.array(m.string()).optional(),files:m.array(m.union([kt,Ae])),tokens:m.record(m.object({type:m.string(),mapping:m.string()})).optional(),dependencies:m.record(fe,m.array(m.string())).optional(),registryDependencies:m.record(fe,m.array(m.string())).optional(),tokenDependencies:m.array(m.string()).optional()}),Ct=m.array(bt),$t=m.object({content:m.string()}),ve=process.env.REGISTRY_URL??"https://sugarcube.sh/r";async function Ne(e){try{const t=await Xe(e);if(!t.ok){if(t.status===401)throw new g(w.REGISTRY_AUTH_REQUIRED(e));if(t.status===403)throw new g(w.REGISTRY_AUTH_INVALID(e));if(t.status===404)throw new g(w.REGISTRY_NOT_FOUND(e));const n=await t.json().catch(()=>null),s=n&&typeof n=="object"&&"error"in n?String(n.error):t.statusText;throw new g(w.REGISTRY_REQUEST_FAILED(s,e))}return t.json()}catch(t){throw t instanceof g?t:new g(w.REGISTRY_NETWORK_ERROR(e))}}o(Ne,"fetchRegistry");async function U(){const e=`${ve}/index.json`,t=await Ne(e);try{return Ct.parse(t)}catch{throw new g(w.REGISTRY_INVALID_DATA(e))}}o(U,"getRegistryIndex");async function pe({type:e,name:t,framework:n}){const s=await U(),r=s.find(a=>a.type===e&&a.name===t);if(!r){const a=s.filter(f=>f.type===e).map(f=>f.name);throw new g(w.REGISTRY_ITEM_NOT_FOUND(e,t,a))}let i=r.files;e==="component"&&n&&(i=r.files.filter(a=>"framework"in a&&a.framework===n));const l=await Promise.all(i.map(async a=>{const f=`${ve}/${a.path}.json`,u=await Ne(f);try{const p=$t.parse(u);return{path:a.path,type:a.type,framework:"framework"in a?a.framework:void 0,content:p.content}}catch{throw new g(w.REGISTRY_FILE_INVALID(a.path))}}));return{item:r,files:l}}o(pe,"getRegistryFiles");async function Rt(e){const t=await pe({type:"tokens",name:e});if(!t.files[0])throw new g(w.STARTER_KIT_UNAVAILABLE(e));return t}o(Rt,"fetchStarterKit");async function de(e,t,n){const s=[],r=new Set;async function i(l){if(r.has(l))return;r.add(l);const a=e.find(u=>u.name===l);if(!a){const u=e.filter(p=>p.type==="component").map(p=>p.name).join(", ");throw new g(`Component '${l}' not found in registry
64
- Available components: ${u}`)}const f=a.registryDependencies?.[n]||[];for(const u of f)await i(u);s.push(a)}o(i,"resolveComponent");for(const l of t)await i(l);return s}o(de,"resolveTree");async function _t({selectedComponents:e,componentType:t,componentsOutputDirectory:n}){const s={variableCSS:[],utilityCSS:[],componentFiles:[],componentCSS:[],cubeCSS:[],indexFiles:[]},r=await U(),l=(await de(r,e,t)).map(p=>p.name),a=r.filter(p=>p.type==="component").filter(p=>l.includes(p.name)),f=a.flatMap(p=>p.files.filter(d=>(d.type==="tsx"||d.type==="astro"||d.type==="njk")&&"framework"in d&&d.framework===t).map(d=>$(process.cwd(),R(n,p.name,`${p.name}.${d.type}`))));s.componentFiles=f.filter(p=>F(R(process.cwd(),p)));const u=a.map(p=>{const d=p.name;return $(process.cwd(),R(n,p.name,`${d}.css`))});return s.componentCSS=u.filter(p=>F(R(process.cwd(),p))),s}o(_t,"collectComponentOverwriteWarnings");async function Dt({cubeDirectory:e}){const t={variableCSS:[],utilityCSS:[],componentFiles:[],componentCSS:[],cubeCSS:[],indexFiles:[]},s=(await U()).filter(r=>r.type==="cube").flatMap(r=>r.files).map(r=>{const i=r.path.replace(/^styles\//,"");return $(process.cwd(),R(e,i))});return t.cubeCSS=s.filter(r=>F(R(process.cwd(),r))),t}o(Dt,"collectCubeOverwriteWarnings");function Fe(e){const t=[];if(e.variableCSS.length>0&&t.push(`CSS variables files:
63
+ The plugin will automatically generate CSS with hot module replacement.`,"PLUGIN_DETECTED")};class g extends Error{static{o(this,"CLIError")}constructor(t,n){super(t),this.name="CLIError",this.cause=n}}const fe=m.enum(["react","web-components","css-only"]),Ae=m.object({path:m.string(),type:m.string()}),Ct=Ae.extend({framework:fe});m.object({modes:m.record(m.string(),m.array(m.string())).optional(),themes:m.record(m.string(),m.array(m.string())).optional()}).strict();const $t=m.object({name:m.string(),type:m.string(),description:m.string().optional(),frameworks:m.array(m.string()).optional(),files:m.array(m.union([Ct,Ae])),tokens:m.record(m.object({type:m.string(),mapping:m.string()})).optional(),dependencies:m.record(fe,m.array(m.string())).optional(),registryDependencies:m.record(fe,m.array(m.string())).optional(),tokenDependencies:m.array(m.string()).optional()}),_t=m.array($t),Rt=m.object({content:m.string()}),Ne=process.env.REGISTRY_URL??"https://sugarcube.sh/r";async function ve(e){try{const t=await tt(e);if(!t.ok){if(t.status===401)throw new g(w.REGISTRY_AUTH_REQUIRED(e));if(t.status===403)throw new g(w.REGISTRY_AUTH_INVALID(e));if(t.status===404)throw new g(w.REGISTRY_NOT_FOUND(e));const n=await t.json().catch(()=>null),s=n&&typeof n=="object"&&"error"in n?String(n.error):t.statusText;throw new g(w.REGISTRY_REQUEST_FAILED(s,e))}return t.json()}catch(t){throw t instanceof g?t:new g(w.REGISTRY_NETWORK_ERROR(e))}}o(ve,"fetchRegistry");async function U(){const e=`${Ne}/index.json`,t=await ve(e);try{return _t.parse(t)}catch{throw new g(w.REGISTRY_INVALID_DATA(e))}}o(U,"getRegistryIndex");async function de({type:e,name:t,framework:n}){const s=await U(),r=s.find(a=>a.type===e&&a.name===t);if(!r){const a=s.filter(p=>p.type===e).map(p=>p.name);throw new g(w.REGISTRY_ITEM_NOT_FOUND(e,t,a))}let i=r.files;e==="component"&&n&&(i=r.files.filter(a=>"framework"in a&&a.framework===n));const l=await Promise.all(i.map(async a=>{const p=`${Ne}/${a.path}.json`,u=await ve(p);try{const f=Rt.parse(u);return{path:a.path,type:a.type,framework:"framework"in a?a.framework:void 0,content:f.content}}catch{throw new g(w.REGISTRY_FILE_INVALID(a.path))}}));return{item:r,files:l}}o(de,"getRegistryFiles");async function Dt(e){const t=await de({type:"tokens",name:e});if(!t.files[0])throw new g(w.STARTER_KIT_UNAVAILABLE(e));return t}o(Dt,"fetchStarterKit");async function pe(e,t,n){const s=[],r=new Set;async function i(l){if(r.has(l))return;r.add(l);const a=e.find(u=>u.name===l);if(!a){const u=e.filter(f=>f.type==="component").map(f=>f.name).join(", ");throw new g(`Component '${l}' not found in registry
64
+ Available components: ${u}`)}const p=a.registryDependencies?.[n]||[];for(const u of p)await i(u);s.push(a)}o(i,"resolveComponent");for(const l of t)await i(l);return s}o(pe,"resolveTree");async function At({selectedComponents:e,componentType:t,componentsOutputDirectory:n}){const s={variableCSS:[],utilityCSS:[],componentFiles:[],componentCSS:[],cubeCSS:[],indexFiles:[]},r=await U(),l=(await pe(r,e,t)).map(f=>f.name),a=r.filter(f=>f.type==="component").filter(f=>l.includes(f.name)),p=a.flatMap(f=>f.files.filter(d=>(d.type==="tsx"||d.type==="astro"||d.type==="njk")&&"framework"in d&&d.framework===t).map(d=>$(process.cwd(),_(n,f.name,`${f.name}.${d.type}`))));s.componentFiles=p.filter(f=>F(_(process.cwd(),f)));const u=a.map(f=>{const d=f.name;return $(process.cwd(),_(n,f.name,`${d}.css`))});return s.componentCSS=u.filter(f=>F(_(process.cwd(),f))),s}o(At,"collectComponentOverwriteWarnings");async function Nt({cubeDirectory:e}){const t={variableCSS:[],utilityCSS:[],componentFiles:[],componentCSS:[],cubeCSS:[],indexFiles:[]},s=(await U()).filter(r=>r.type==="cube").flatMap(r=>r.files).map(r=>{const i=r.path.replace(/^styles\//,"");return $(process.cwd(),_(e,i))});return t.cubeCSS=s.filter(r=>F(_(process.cwd(),r))),t}o(Nt,"collectCubeOverwriteWarnings");function Fe(e){const t=[];if(e.variableCSS.length>0&&t.push(`CSS variables files:
65
65
  ${e.variableCSS.map(s=>` - ${s}`).join(`
66
66
  `)}`),e.utilityCSS.length>0&&t.push(`CSS utility files:
67
67
  ${e.utilityCSS.map(s=>` - ${s}`).join(`
@@ -75,60 +75,60 @@ ${e.indexFiles.map(s=>` - ${s}`).join(`
75
75
 
76
76
  ${t.join(`
77
77
 
78
- `)}`}o(Fe,"formatOverwriteWarnings");async function ge(e,t,n){if(e.length===0)return;const s=n==="npm"?"install":"add";try{await tt(n,[s,...e],{cwd:t})}catch{throw new g(w.DEPENDENCY_INSTALL_FAILED(n))}}o(ge,"installDependencies");async function At(e,t,n){const s=R(n,t.name);if(await V(s,{recursive:!0}),e.path.endsWith(".css")){const i=R(s,`${t.name}.css`);return await X(i,e.content),i}const r=R(s,B(e.path));return await X(r,e.content),r}o(At,"writeComponentFile");async function vt({registryIndex:e,selectedComponents:t,componentType:n,componentsOutputDirectory:s,packageManager:r}){const i=[],l=new Set;await V(s,{recursive:!0});const a=await de(e,t,n);for(const f of a){const u=await pe({type:"component",name:f.name,framework:n});for(const d of u.files)if(d)try{const h=await At(d,f,s);h&&i.push(h)}catch(h){const k=h instanceof Error?`: ${h.message}`:"";throw new g(`Failed to write component file for "${f.name}"${k}`)}const p=f.dependencies?.[n]||[];for(const d of p)l.add(d)}if(l.size>0)try{await ge(Array.from(l),process.cwd(),r)}catch(f){const u=f instanceof Error?`: ${f.message}`:"";throw new g(`Failed to install component dependencies${u}`)}return{createdFiles:i,npmDependencies:l}}o(vt,"installComponents");function Nt(e,t){const n=L(e),s=L(t);return n.startsWith(`${s}/`)||n===s}o(Nt,"isWithinDirectory");async function Ft(e){const t=[],n=L(process.cwd(),e);await V(n,{recursive:!0});const r=(await U()).filter(i=>i.type==="cube").map(i=>i.name);for(const i of r){const l=await pe({type:"cube",name:i});for(const a of l.files){if(!a)continue;const f=a.path.replace(/^styles\//,""),u=L(n,f);if(!Nt(u,n))throw new g(`Invalid file path detected in CUBE module "${i}": path escapes target directory`);const p=Ze(u);try{await V(p,{recursive:!0}),await X(u,a.content),t.push(u)}catch(d){const h=d instanceof Error?`: ${d.message}`:"";throw new g(`Failed to write CUBE module "${i}"${h}`)}}}return t}o(Ft,"installCUBE");async function Ot(e,t){await se.mkdir(t,{recursive:!0});const n=[];for(const s of e)await se.writeFile(s.path,s.content),n.push(s.path);return n}o(Ot,"writeTokenFiles");async function K(e,t){const n={type:"files",config:e},{trees:s,resolved:r,errors:i}=await nt(n);if(i.load.length>0){const l=i.load.map(a=>{const f=a.file.split("/").pop()||"unknown file";let u=`File ${f}: `;return a.message.includes("Unexpected token")?u=w.TOKEN_FILE_INVALID_JSON(f):a.message.includes("Unexpected end")?u=w.TOKEN_FILE_INCOMPLETE_JSON(f):u=w.TOKEN_FILE_GENERIC_ERROR(f,a.message),u});throw new g(w.TOKEN_LOAD_FAILED(l))}if(i.validation.length>0||i.flatten.length>0||i.resolution.length>0){const l=[...i.flatten,...i.validation,...i.resolution],a=new Map;for(const f of l)if(f.source?.sourcePath){const u=a.get(f.source.sourcePath)||[];u.push(f.message),a.set(f.source.sourcePath,u)}throw new g(w.TOKEN_VALIDATION_FAILED(a))}return{trees:s,resolved:r}}o(K,"loadAndResolveTokensForCLI");function Pt(e,t){const n={...e},s=t.modes&&Object.keys(t.modes).length>0,r=t.themes&&Object.keys(t.themes).length>0;return(s||r)&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)&&"source"in n.tokens&&(s&&(n.tokens.modes=t.modes),r&&(n.tokens.themes=t.themes)),st(n)}o(Pt,"integrateVariantsIntoConfig");const{hidden:hs}=c,Lt=ct(),E=o((e,t)=>Lt?e:t,"unicodeOr"),Mt=E("\u25C7","o"),Oe=E("\u250C","T"),O=E("\u2502","|"),me=E("\u2514","\u2014"),jt=E("\u2510","T"),Ut=E("\u2518","\u2014"),te=E("\u2500","-"),xt=E("\u256E","+"),Gt=E("\u256F","+"),Wt=E("\u2570","+"),Bt=E("\u256D","+"),Vt=E("\u25CF","\u2022"),Kt=E("\u25C6","*"),Yt=E("\u25B2","!"),Ht=E("\u25A0","x"),Y=o((e,t=c.bgGreen,n=c.black)=>t(` ${n(e)} `),"label"),H=o(e=>{const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"].join("|"),n=new RegExp(t,"g");return typeof e=="string"?e.replace(n,""):e},"strip"),J=o((e="",t)=>{process.stdout.write(`
78
+ `)}`}o(Fe,"formatOverwriteWarnings");async function ge(e,t,n){if(e.length===0)return;const s=n==="npm"?"install":"add";try{await st(n,[s,...e],{cwd:t})}catch{throw new g(w.DEPENDENCY_INSTALL_FAILED(n))}}o(ge,"installDependencies");async function vt(e,t,n){const s=_(n,t.name);if(await V(s,{recursive:!0}),e.path.endsWith(".css")){const i=_(s,`${t.name}.css`);return await X(i,e.content),i}const r=_(s,W(e.path));return await X(r,e.content),r}o(vt,"writeComponentFile");async function Ft({registryIndex:e,selectedComponents:t,componentType:n,componentsOutputDirectory:s,packageManager:r}){const i=[],l=new Set;await V(s,{recursive:!0});const a=await pe(e,t,n);for(const p of a){const u=await de({type:"component",name:p.name,framework:n});for(const d of u.files)if(d)try{const h=await vt(d,p,s);h&&i.push(h)}catch(h){const k=h instanceof Error?`: ${h.message}`:"";throw new g(`Failed to write component file for "${p.name}"${k}`)}const f=p.dependencies?.[n]||[];for(const d of f)l.add(d)}if(l.size>0)try{await ge(Array.from(l),process.cwd(),r)}catch(p){const u=p instanceof Error?`: ${p.message}`:"";throw new g(`Failed to install component dependencies${u}`)}return{createdFiles:i,npmDependencies:l}}o(Ft,"installComponents");function Ot(e,t){const n=L(e),s=L(t);return n.startsWith(`${s}/`)||n===s}o(Ot,"isWithinDirectory");async function Pt(e){const t=[],n=L(process.cwd(),e);await V(n,{recursive:!0});const r=(await U()).filter(i=>i.type==="cube").map(i=>i.name);for(const i of r){const l=await de({type:"cube",name:i});for(const a of l.files){if(!a)continue;const p=a.path.replace(/^styles\//,""),u=L(n,p);if(!Ot(u,n))throw new g(`Invalid file path detected in CUBE module "${i}": path escapes target directory`);const f=Xe(u);try{await V(f,{recursive:!0}),await X(u,a.content),t.push(u)}catch(d){const h=d instanceof Error?`: ${d.message}`:"";throw new g(`Failed to write CUBE module "${i}"${h}`)}}}return t}o(Pt,"installCUBE");async function Lt(e,t){await se.mkdir(t,{recursive:!0});const n=[];for(const s of e)await se.writeFile(s.path,s.content),n.push(s.path);return n}o(Lt,"writeTokenFiles");async function K(e,t){const n={type:"files",config:e},{trees:s,resolved:r,errors:i}=await ot(n);if(i.load.length>0){const l=i.load.map(a=>{const p=a.file.split("/").pop()||"unknown file";let u=`File ${p}: `;return a.message.includes("Unexpected token")?u=w.TOKEN_FILE_INVALID_JSON(p):a.message.includes("Unexpected end")?u=w.TOKEN_FILE_INCOMPLETE_JSON(p):u=w.TOKEN_FILE_GENERIC_ERROR(p,a.message),u});throw new g(w.TOKEN_LOAD_FAILED(l))}if(i.validation.length>0||i.flatten.length>0||i.resolution.length>0){const l=[...i.flatten,...i.validation,...i.resolution],a=new Map;for(const p of l)if(p.source?.sourcePath){const u=a.get(p.source.sourcePath)||[];u.push(p.message),a.set(p.source.sourcePath,u)}throw new g(w.TOKEN_VALIDATION_FAILED(a))}return{trees:s,resolved:r}}o(K,"loadAndResolveTokensForCLI");function Mt(e,t){const n={...e},s=t.modes&&Object.keys(t.modes).length>0,r=t.themes&&Object.keys(t.themes).length>0;return(s||r)&&typeof n.tokens=="object"&&!Array.isArray(n.tokens)&&"source"in n.tokens&&(s&&(n.tokens.modes=t.modes),r&&(n.tokens.themes=t.themes)),rt(n)}o(Mt,"integrateVariantsIntoConfig");const{hidden:ys}=c,jt=ut(),E=o((e,t)=>jt?e:t,"unicodeOr"),Ut=E("\u25C7","o"),Oe=E("\u250C","T"),O=E("\u2502","|"),me=E("\u2514","\u2014"),xt=E("\u2510","T"),Gt=E("\u2518","\u2014"),te=E("\u2500","-"),Bt=E("\u256E","+"),Wt=E("\u256F","+"),Vt=E("\u2570","+"),Kt=E("\u256D","+"),Yt=E("\u25CF","\u2022"),Ht=E("\u25C6","*"),zt=E("\u25B2","!"),Jt=E("\u25A0","x"),Y=o((e,t=c.bgGreen,n=c.black)=>t(` ${n(e)} `),"label"),H=o(e=>{const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"].join("|"),n=new RegExp(t,"g");return typeof e=="string"?e.replace(n,""):e},"strip"),z=o((e="",t)=>{process.stdout.write(`
79
79
 
80
80
  ${c.gray(Oe)}${c.gray(te)} ${e}
81
81
  `)},"intro"),ne=o((e="",t)=>{process.stdout.write(`${c.gray(O)}
82
82
  ${c.gray(me)}${c.gray(te)} ${e}
83
83
 
84
- `)},"outro");function Jt(...e){process.env.DEBUG==="true"&&process.stderr.write(`[sugarcube:debug] ${e.map(String).join(" ")}
85
- `)}o(Jt,"debugLog");function x(e){return new Promise(t=>setTimeout(t,e))}o(x,"sleep");function qt(e,t){const n={},s={};if(e.modes)for(const[r,i]of Object.entries(e.modes))n[r]=i.map(l=>{const a=t[l];if(!a)throw new g(w.KIT_INCOMPLETE());return a});if(e.themes)for(const[r,i]of Object.entries(e.themes))s[r]=i.map(l=>{const a=t[l];if(!a)throw new g(w.KIT_INCOMPLETE());return a});return{modes:n,themes:s}}o(qt,"processKitVariants");const zt=o(async(e,t,n)=>{const s=await Rt(e),r=L(process.cwd(),t),i=s.files.find(d=>B(d.path)==="config.json");let l={};if(i)try{l=JSON.parse(i.content)}catch(d){Jt(`Could not parse config.json for starter kit '${e}':`,d)}const a=s.files.filter(d=>B(d.path)!=="config.json").map(d=>({path:R(r,B(d.path)),content:d.content})),f=Object.fromEntries(a.map(d=>[B(d.path),$(process.cwd(),d.path)])),u=qt(l,f);return{config:Pt(n,u),tokenFiles:a,tokensDir:r,createdTokenPaths:a.map(d=>$(process.cwd(),d.path))}},"prepareStarterKitForInstall");async function Zt(e){const t=await zt(e.starterKit??"",e.tokensDir,e.config),n=await Ot(t.tokenFiles,e.tokensDir),{trees:s,resolved:r}=await K(e.config);e.setupResult={config:t.config,createdTokenPaths:t.createdTokenPaths,trees:s,resolved:r,tokenFiles:t.tokenFiles,tokensDir:t.tokensDir},e.createdFiles.push(...n)}o(Zt,"installFromStarterKit");async function Pe(e=!0){const t=[{label:"React",value:"react",hint:".tsx"},{label:"CSS Only",value:"css-only",hint:".css"},{label:c.dim("Web components"),value:"web-components",hint:"Coming soon!"}];e&&t.push({label:"Skip",value:"skip",hint:"continue without components"});const n=await ut({message:"Build with",options:t});return ae(n)&&process.exit(0),n==="web-components"?(ft.info(c.blue("Web components are coming soon! Please choose React or CSS Only for now.")),Pe(e)):n}o(Pe,"promptComponentFramework");async function Qt(e,t){const n=e.filter(r=>r.type==="component"&&r.frameworks?.includes(t)),s=await pt({message:"Select components to add",options:n.map(r=>({label:r.name,value:r.name,hint:r.description})),required:!0});return ae(s)&&process.exit(0),s}o(Qt,"promptComponentSelectionFiltered");async function Le(e,t=!1){const n=await dt({message:e,initialValue:t});return(!n||ae(n))&&(be(),process.exit(0)),!0}o(Le,"confirmOverwrite");const Xt=[Bt,xt,Wt,Gt],en=[Oe,jt,me,Ut];function Me(e,t,n,s){let r=n,i=n;return s==="center"?r=Math.floor((t-e)/2):s==="right"&&(r=t-e-n),i=t-r-e,[r,i]}o(Me,"getPaddingForLine");const tn=o(e=>e,"defaultFormatBorder"),he=o((e="",t="",n)=>{const s=n?.output??process.stdout,r=gt(s),l=1*2,a=n?.titlePadding??1,f=n?.contentPadding??2,u=n?.width===void 0||n.width==="auto"?1:Math.min(1,n.width),p=n?.includePrefix?`${O} `:"",d=n?.formatBorder??tn,h=(n?.rounded?Xt:en).map(d),k=d(te),b=d(O),T=r-p.length;let C=Math.floor(r*u)-p.length;if(n?.width==="auto"){const Z=e.split(`
86
- `);let W=H(t).length+a*2;for(const qe of Z){const Te=H(qe).length+f*2;Te>W&&(W=Te)}const Q=W+l;Q<C&&(C=Q)}C%2!==0&&(C<T?C++:C--);const I=C-l,N=I-a*2,y=H(t).length>N?`${t.slice(0,N-3)}...`:t,[_,D]=Me(H(y).length,I,a,n?.titleAlign),P=mt(e,I-f*2,{hard:!0,trim:!1});s.write(`${p}${h[0]}${k.repeat(_)}${y}${k.repeat(D)}${h[1]}
87
- `);const z=P.split(`
88
- `);for(const Z of z){const[W,Q]=Me(H(Z).length,I,f,n?.contentAlign);s.write(`${p}${b}${" ".repeat(W)}${Z}${" ".repeat(Q)}${b}
89
- `)}s.write(`${p}${h[2]}${k.repeat(I)}${h[3]}
84
+ `)},"outro");function qt(...e){process.env.DEBUG==="true"&&process.stderr.write(`[sugarcube:debug] ${e.map(String).join(" ")}
85
+ `)}o(qt,"debugLog");function x(e){return new Promise(t=>setTimeout(t,e))}o(x,"sleep");function Zt(e,t){const n={},s={};if(e.modes)for(const[r,i]of Object.entries(e.modes))n[r]=i.map(l=>{const a=t[l];if(!a)throw new g(w.KIT_INCOMPLETE());return a});if(e.themes)for(const[r,i]of Object.entries(e.themes))s[r]=i.map(l=>{const a=t[l];if(!a)throw new g(w.KIT_INCOMPLETE());return a});return{modes:n,themes:s}}o(Zt,"processKitVariants");const Qt=o(async(e,t,n)=>{const s=await Dt(e),r=L(process.cwd(),t),i=s.files.find(d=>W(d.path)==="config.json");let l={};if(i)try{l=JSON.parse(i.content)}catch(d){qt(`Could not parse config.json for starter kit '${e}':`,d)}const a=s.files.filter(d=>W(d.path)!=="config.json").map(d=>({path:_(r,W(d.path)),content:d.content})),p=Object.fromEntries(a.map(d=>[W(d.path),$(process.cwd(),d.path)])),u=Zt(l,p);return{config:Mt(n,u),tokenFiles:a,tokensDir:r,createdTokenPaths:a.map(d=>$(process.cwd(),d.path))}},"prepareStarterKitForInstall");async function Xt(e){const t=await Qt(e.starterKit??"",e.tokensDir,e.config),n=await Lt(t.tokenFiles,e.tokensDir),{trees:s,resolved:r}=await K(e.config);e.setupResult={config:t.config,createdTokenPaths:t.createdTokenPaths,trees:s,resolved:r,tokenFiles:t.tokenFiles,tokensDir:t.tokensDir},e.createdFiles.push(...n)}o(Xt,"installFromStarterKit");async function Pe(e=!0){const t=[{label:"React",value:"react",hint:".tsx"},{label:"CSS Only",value:"css-only",hint:".css"},{label:c.dim("Web components"),value:"web-components",hint:"Coming soon!"}];e&&t.push({label:"Skip",value:"skip",hint:"continue without components"});const n=await dt({message:"Build with",options:t});return ae(n)&&process.exit(0),n==="web-components"?(pt.info(c.blue("Web components are coming soon! Please choose React or CSS Only for now.")),Pe(e)):n}o(Pe,"promptComponentFramework");async function en(e,t){const n=e.filter(r=>r.type==="component"&&r.frameworks?.includes(t)),s=await gt({message:"Select components to add",options:n.map(r=>({label:r.name,value:r.name,hint:r.description})),required:!0});return ae(s)&&process.exit(0),s}o(en,"promptComponentSelectionFiltered");async function Le(e,t=!1){const n=await mt({message:e,initialValue:t});return(!n||ae(n))&&(be(),process.exit(0)),!0}o(Le,"confirmOverwrite");const tn=[Kt,Bt,Vt,Wt],nn=[Oe,xt,me,Gt];function Me(e,t,n,s){let r=n,i=n;return s==="center"?r=Math.floor((t-e)/2):s==="right"&&(r=t-e-n),i=t-r-e,[r,i]}o(Me,"getPaddingForLine");const sn=o(e=>e,"defaultFormatBorder"),he=o((e="",t="",n)=>{const s=n?.output??process.stdout,r=ht(s),l=1*2,a=n?.titlePadding??1,p=n?.contentPadding??2,u=n?.width===void 0||n.width==="auto"?1:Math.min(1,n.width),f=n?.includePrefix?`${O} `:"",d=n?.formatBorder??sn,h=(n?.rounded?tn:nn).map(d),k=d(te),b=d(O),T=r-f.length;let C=Math.floor(r*u)-f.length;if(n?.width==="auto"){const Z=e.split(`
86
+ `);let B=H(t).length+a*2;for(const Ze of Z){const Te=H(Ze).length+p*2;Te>B&&(B=Te)}const Q=B+l;Q<C&&(C=Q)}C%2!==0&&(C<T?C++:C--);const I=C-l,v=I-a*2,y=H(t).length>v?`${t.slice(0,v-3)}...`:t,[R,D]=Me(H(y).length,I,a,n?.titleAlign),P=wt(e,I-p*2,{hard:!0,trim:!1});s.write(`${f}${h[0]}${k.repeat(R)}${y}${k.repeat(D)}${h[1]}
87
+ `);const q=P.split(`
88
+ `);for(const Z of q){const[B,Q]=Me(H(Z).length,I,p,n?.contentAlign);s.write(`${f}${b}${" ".repeat(B)}${Z}${" ".repeat(Q)}${b}
89
+ `)}s.write(`${f}${h[2]}${k.repeat(I)}${h[3]}
90
90
  `)},"box");function we(e,t={}){const n=`
91
91
  ${e}`;he(n,c.black(c.bgRed(" ERROR ")),{width:"auto",titlePadding:2,formatBorder:c.red,...t})}o(we,"errorBoxWithBadge");function je(e,t={}){const n=`
92
- ${e}`;he(n,c.black(c.bgYellow(" WARNING ")),{width:"auto",titlePadding:2,formatBorder:c.yellow,...t})}o(je,"warningBoxWithBadge");function nn(e,t={}){const n=`
93
- ${e}`;he(n,c.black(c.bgCyan(" INFO ")),{width:"auto",titlePadding:2,formatBorder:c.cyan,...t})}o(nn,"infoBoxWithBadge");const sn=o((e,t)=>{if(!(e.meta&&e.name!=="escape")){if(e.ctrl){if(e.name==="a")return"first";if(e.name==="c"||e.name==="d")return"abort";if(e.name==="e")return"last";if(e.name==="g")return"reset"}return e.name==="return"||e.name==="enter"?"submit":e.name==="backspace"?"delete":e.name==="delete"?"deleteForward":e.name==="abort"?"abort":e.name==="escape"?"exit":e.name==="tab"?"next":e.name==="pagedown"?"nextPage":e.name==="pageup"?"prevPage":e.name==="home"?"home":e.name==="end"?"end":e.name==="up"?"up":e.name==="down"?"down":e.name==="right"?"right":e.name==="left"?"left":!1}},"action"),on=o(async(e,t={})=>{const{sidebarSymbol:n=c.gray("\u2502"),clear:s=!1,stdin:r=process.stdin,stdout:i=process.stdout}=t,l=$e.createInterface({input:r,escapeCodeTimeout:50}),a=Re(i,{showCursor:!1});$e.emitKeypressEvents(r,l);let f=0,u=!1;const p=o(async()=>{r.off("keypress",d),r.isTTY&&r.setRawMode(!1),l.close(),u=!0,f<e.length-1||s?a.clear():a.done()},"done"),d=o((h,k)=>{r.isTTY&&r.setRawMode(!0);const b=sn(k);if(b==="abort")return p(),process.exit(0);["up","down","left","right"].includes(b)||p()},"handleKeyPress");r.isTTY&&r.setRawMode(!0),r.on("keypress",d);for(const h of e){const k=Array.isArray(h)?h:h.split(" "),b=[];for(const I of[""].concat(k)){I&&b.push(I);const N=b.join(" ").replace(/sugarcube/g,c.cyan("sugarcube")),y=`${n} ${N}`;a(y),u||await new Promise(_=>setTimeout(_,Math.floor(Math.random()*126)+75))}u||await new Promise(I=>setTimeout(I,100));const C=(await Promise.all(k).then(I=>I.join(" "))).replace(/sugarcube/g,c.cyan("sugarcube"));a(`${n} ${C}`),u||await new Promise(I=>setTimeout(I,Math.floor(Math.random()*201)+1200)),f++}r.off("keypress",d),await new Promise(h=>setTimeout(h,100)),p(),r.isTTY&&r.setRawMode(!1),r.removeAllListeners("keypress")},"sayAnimatedInSidebar");function rn(){return Math.floor(Math.random()*551)+200}o(rn,"getRandomTaskDuration");async function an(e,{sidebarSymbol:t="\u2502",spacing:n=1,stdin:s=process.stdin,stdout:r=process.stdout,initialDelayMs:i=200,minDurationMs:l,successPauseMs:a=300,successMessage:f,successAsOutro:u=!1}={}){const p=o((y,_)=>{let D="";switch(_){case"start":D=`${c.cyan(`\u25B6 ${y.start}`)}`;break;case"pending":D=`${c.dim(`\u25A1 ${y.pending}`)}`;break;case"success":D=`${c.green(`\u2714 ${y.end}`)}`;break;case"end":D=`${c.dim(`\u25A0 ${y.end}`)}`;break}return`${t} ${D}`},"formatWithSidebar"),d=Array.from({length:e.length},()=>"");e.forEach((y,_)=>{d[_]=p(y,"pending")});const h=Re(r),k=Ce.createInterface({input:s,escapeCodeTimeout:50});Ce.emitKeypressEvents(s,k);const b=o(y=>{y===""&&(h.clear(),k.close(),s.isTTY&&s.setRawMode(!1),process.exit(0)),s.isTTY&&s.setRawMode(!0)},"keypress");s.isTTY&&s.setRawMode(!0),s.on("keypress",b);const T=Array.from({length:Math.max(n,0)},()=>`${t}`),C=o(()=>[...T,...d].join(`
94
- `),"renderContent");h(C()),await x(i);let I=0;for(const y of e){d[I]=p(y,"start"),h(C());const _=Date.now(),D=y.while();try{await D;const P=Date.now()-_,z=typeof l=="number"?l:rn();P<z&&await x(z-P),d[I]=p(y,"success"),h(C()),await x(a)}catch(P){throw d[I]=`${t} ${c.red(`\u2717 ${y.end} (failed)`)}`,h(C()),y.onError?.(P),s.removeListener("keypress",b),k.close(),s.isTTY&&s.setRawMode(!1),P}I++}const N=e.map(y=>p(y,"end"));if(f)if(u){const y=`${c.gray(me)}${c.gray(te)} ${c.green(f)}`;h([...T,...N,`${t}`,y].join(`
95
- `))}else{const y=`${t} ${c.green(f)}`;h([...T,...N,`${t}`,y].join(`
96
- `))}else h([...T,...N].join(`
97
- `));await x(1e3),s.removeListener("keypress",b),s.isTTY&&s.setRawMode(!1),k.close(),h.done()}o(an,"executeTasksInSidebar");const cn=o(e=>process.stdout.write(`${e}
92
+ ${e}`;he(n,c.black(c.bgYellow(" WARNING ")),{width:"auto",titlePadding:2,formatBorder:c.yellow,...t})}o(je,"warningBoxWithBadge");function on(e,t={}){const n=`
93
+ ${e}`;he(n,c.black(c.bgCyan(" INFO ")),{width:"auto",titlePadding:2,formatBorder:c.cyan,...t})}o(on,"infoBoxWithBadge");const rn=o((e,t)=>{if(!(e.meta&&e.name!=="escape")){if(e.ctrl){if(e.name==="a")return"first";if(e.name==="c"||e.name==="d")return"abort";if(e.name==="e")return"last";if(e.name==="g")return"reset"}return e.name==="return"||e.name==="enter"?"submit":e.name==="backspace"?"delete":e.name==="delete"?"deleteForward":e.name==="abort"?"abort":e.name==="escape"?"exit":e.name==="tab"?"next":e.name==="pagedown"?"nextPage":e.name==="pageup"?"prevPage":e.name==="home"?"home":e.name==="end"?"end":e.name==="up"?"up":e.name==="down"?"down":e.name==="right"?"right":e.name==="left"?"left":!1}},"action"),an=o(async(e,t={})=>{const{sidebarSymbol:n=c.gray("\u2502"),clear:s=!1,stdin:r=process.stdin,stdout:i=process.stdout}=t,l=$e.createInterface({input:r,escapeCodeTimeout:50}),a=_e(i,{showCursor:!1});$e.emitKeypressEvents(r,l);let p=0,u=!1;const f=o(async()=>{r.off("keypress",d),r.isTTY&&r.setRawMode(!1),l.close(),u=!0,p<e.length-1||s?a.clear():a.done()},"done"),d=o((h,k)=>{r.isTTY&&r.setRawMode(!0);const b=rn(k);if(b==="abort")return f(),process.exit(0);["up","down","left","right"].includes(b)||f()},"handleKeyPress");r.isTTY&&r.setRawMode(!0),r.on("keypress",d);for(const h of e){const k=Array.isArray(h)?h:h.split(" "),b=[];for(const I of[""].concat(k)){I&&b.push(I);const v=b.join(" ").replace(/sugarcube/g,c.cyan("sugarcube")),y=`${n} ${v}`;a(y),u||await new Promise(R=>setTimeout(R,Math.floor(Math.random()*126)+75))}u||await new Promise(I=>setTimeout(I,100));const C=(await Promise.all(k).then(I=>I.join(" "))).replace(/sugarcube/g,c.cyan("sugarcube"));a(`${n} ${C}`),u||await new Promise(I=>setTimeout(I,Math.floor(Math.random()*201)+1200)),p++}r.off("keypress",d),await new Promise(h=>setTimeout(h,100)),f(),r.isTTY&&r.setRawMode(!1),r.removeAllListeners("keypress")},"sayAnimatedInSidebar");function cn(){return Math.floor(Math.random()*551)+200}o(cn,"getRandomTaskDuration");async function ln(e,{sidebarSymbol:t="\u2502",spacing:n=1,stdin:s=process.stdin,stdout:r=process.stdout,initialDelayMs:i=200,minDurationMs:l,successPauseMs:a=300,successMessage:p,successAsOutro:u=!1}={}){const f=o((y,R)=>{let D="";switch(R){case"start":D=`${c.cyan(`\u25B6 ${y.start}`)}`;break;case"pending":D=`${c.dim(`\u25A1 ${y.pending}`)}`;break;case"success":D=`${c.green(`\u2714 ${y.end}`)}`;break;case"end":D=`${c.dim(`\u25A0 ${y.end}`)}`;break}return`${t} ${D}`},"formatWithSidebar"),d=Array.from({length:e.length},()=>"");e.forEach((y,R)=>{d[R]=f(y,"pending")});const h=_e(r),k=Ce.createInterface({input:s,escapeCodeTimeout:50});Ce.emitKeypressEvents(s,k);const b=o(y=>{y===""&&(h.clear(),k.close(),s.isTTY&&s.setRawMode(!1),process.exit(0)),s.isTTY&&s.setRawMode(!0)},"keypress");s.isTTY&&s.setRawMode(!0),s.on("keypress",b);const T=Array.from({length:Math.max(n,0)},()=>`${t}`),C=o(()=>[...T,...d].join(`
94
+ `),"renderContent");h(C()),await x(i);let I=0;for(const y of e){d[I]=f(y,"start"),h(C());const R=Date.now(),D=y.while();try{await D;const P=Date.now()-R,q=typeof l=="number"?l:cn();P<q&&await x(q-P),d[I]=f(y,"success"),h(C()),await x(a)}catch(P){throw d[I]=`${t} ${c.red(`\u2717 ${y.end} (failed)`)}`,h(C()),y.onError?.(P),s.removeListener("keypress",b),k.close(),s.isTTY&&s.setRawMode(!1),P}I++}const v=e.map(y=>f(y,"end"));if(p)if(u){const y=`${c.gray(me)}${c.gray(te)} ${c.green(p)}`;h([...T,...v,`${t}`,y].join(`
95
+ `))}else{const y=`${t} ${c.green(p)}`;h([...T,...v,`${t}`,y].join(`
96
+ `))}else h([...T,...v].join(`
97
+ `));await x(1e3),s.removeListener("keypress",b),s.isTTY&&s.setRawMode(!1),k.close(),h.done()}o(ln,"executeTasksInSidebar");const un=o(e=>process.stdout.write(`${e}
98
98
  `),"rawLog"),S={message:o((e=[],{symbol:t=c.gray(O),secondarySymbol:n=c.gray(O),output:s=process.stdout,spacing:r=1}={})=>{const i=[];for(let a=0;a<r;a++)i.push(`${n}`);const l=Array.isArray(e)?e:e.split(`
99
- `);if(l.length>0){const[a,...f]=l;a&&a.length>0?i.push(`${t} ${a}`):i.push(t);for(const u of f)u.length>0?i.push(`${n} ${u}`):i.push(n)}s.write(`${i.join(`
99
+ `);if(l.length>0){const[a,...p]=l;a&&a.length>0?i.push(`${t} ${a}`):i.push(t);for(const u of p)u.length>0?i.push(`${n} ${u}`):i.push(n)}s.write(`${i.join(`
100
100
  `)}
101
- `)},"message"),info:o((e,t)=>{S.message(e,{...t,symbol:c.blue(Vt)})},"info"),success:o((e,t)=>{S.message(e,{...t,symbol:c.green(Kt)})},"success"),step:o((e,t)=>{S.message(e,{...t,symbol:c.green(Mt)})},"step"),warn:o((e,t)=>{S.message(e,{...t,symbol:c.yellow(Yt)})},"warn"),error:o((e,t)=>{S.message(e,{...t,symbol:c.red(Ht)})},"error"),animated:o(async(e,{secondarySymbol:t=c.gray(O),output:n=process.stdout,clear:s=!1,...r}={})=>on(e,{sidebarSymbol:t,stdout:n,clear:s,...r}),"animated"),tasks:o(async(e,{spacing:t=1,secondarySymbol:n=c.gray(O),output:s=process.stdout,...r}={})=>an(e,{sidebarSymbol:n,spacing:t,stdout:s,...r}),"tasks"),space:o((e=1)=>{for(let t=0;t<e;t++)process.stdout.write(`${c.gray(O)}
101
+ `)},"message"),info:o((e,t)=>{S.message(e,{...t,symbol:c.blue(Yt)})},"info"),success:o((e,t)=>{S.message(e,{...t,symbol:c.green(Ht)})},"success"),step:o((e,t)=>{S.message(e,{...t,symbol:c.green(Ut)})},"step"),warn:o((e,t)=>{S.message(e,{...t,symbol:c.yellow(zt)})},"warn"),error:o((e,t)=>{S.message(e,{...t,symbol:c.red(Jt)})},"error"),animated:o(async(e,{secondarySymbol:t=c.gray(O),output:n=process.stdout,clear:s=!1,...r}={})=>an(e,{sidebarSymbol:t,stdout:n,clear:s,...r}),"animated"),tasks:o(async(e,{spacing:t=1,secondarySymbol:n=c.gray(O),output:s=process.stdout,...r}={})=>ln(e,{sidebarSymbol:n,spacing:t,stdout:s,...r}),"tasks"),space:o((e=1)=>{for(let t=0;t<e;t++)process.stdout.write(`${c.gray(O)}
102
102
  `)},"space"),break:o((e=1)=>{for(let t=0;t<e;t++)process.stdout.write(`
103
- `)},"break")};function q(e){if(e instanceof g)S.space(1),we(e.message,{});else{const t=`An unexpected error occurred: ${e instanceof Error?e.message:String(e)}
103
+ `)},"break")};function J(e){if(e instanceof g)S.space(1),we(e.message,{});else{const t=`An unexpected error occurred: ${e instanceof Error?e.message:String(e)}
104
104
 
105
- If this issue persists, please report it: ${c.cyan("https://github.com/sugarcube-org/sugarcube/issues")}`;S.space(1),we(t,{})}process.exit(0)}o(q,"handleError");function Ue(e){return{absolute:L(process.cwd(),e)}}o(Ue,"resolveDirectoryFromFlag");async function xe(e){if(A())try{const{config:t}=await ee(),n=ln(t,e);return typeof n=="string"?L(process.cwd(),n):void 0}catch{return}}o(xe,"resolveDirectoryFromConfig");function ln(e,t){const n=t.split(".");let s=e;for(const r of n){if(s==null||typeof s!="object")return;s=s[r]}return s}o(ln,"getNestedValue");async function un(e){if(e){const{absolute:t}=Ue(e);return{directory:t,fromConfig:!1}}if(A())try{const t=await xe("output.css");if(t)return{directory:t,fromConfig:!0}}catch{}throw new g(`A sugarcube config file was not found.
105
+ If this issue persists, please report it: ${c.cyan("https://github.com/sugarcube-org/sugarcube/issues")}`;S.space(1),we(t,{})}process.exit(0)}o(J,"handleError");function Ue(e){return{absolute:L(process.cwd(),e)}}o(Ue,"resolveDirectoryFromFlag");async function xe(e){if(A())try{const{config:t}=await ee(),n=fn(t,e);return typeof n=="string"?L(process.cwd(),n):void 0}catch{return}}o(xe,"resolveDirectoryFromConfig");function fn(e,t){const n=t.split(".");let s=e;for(const r of n){if(s==null||typeof s!="object")return;s=s[r]}return s}o(fn,"getNestedValue");async function dn(e){if(e){const{absolute:t}=Ue(e);return{directory:t,fromConfig:!1}}if(A())try{const t=await xe("output.css");if(t)return{directory:t,fromConfig:!0}}catch{}throw new g(`A sugarcube config file was not found.
106
106
 
107
107
  Either a config file or --styles-dir is required to run this command.
108
108
 
109
109
  To use the cube command without a config file:
110
- e.g. ${c.cyan(`${v.CUBE} --styles-dir src/styles`)}
110
+ e.g. ${c.cyan(`${N.CUBE} --styles-dir src/styles`)}
111
111
 
112
112
  To create a config file:
113
- ${c.cyan(v.INIT)}
113
+ ${c.cyan(N.INIT)}
114
114
 
115
- Stuck? ${c.cyan("https://sugarcube.sh")}`)}o(un,"getCssDir");async function fn(e){if(e){const{absolute:t}=Ue(e);return{directory:t,fromConfig:!1}}if(A())try{const t=await xe("output.components");if(t)return{directory:t,fromConfig:!0}}catch{}throw new g(`A sugarcube config file was not found.
115
+ Stuck? ${c.cyan("https://sugarcube.sh")}`)}o(dn,"getCssDir");async function pn(e){if(e){const{absolute:t}=Ue(e);return{directory:t,fromConfig:!1}}if(A())try{const t=await xe("output.components");if(t)return{directory:t,fromConfig:!0}}catch{}throw new g(`A sugarcube config file was not found.
116
116
 
117
117
  Either a config file or --components-dir is required to run this command.
118
118
 
119
119
  To use the components command without a config file:
120
- e.g. ${c.cyan(`${v.COMPONENTS} --components-dir src/components/ui`)}
120
+ e.g. ${c.cyan(`${N.COMPONENTS} --components-dir src/components/ui`)}
121
121
 
122
122
  To create a config file:
123
- ${c.cyan(v.INIT)}
123
+ ${c.cyan(N.INIT)}
124
124
 
125
- Stuck? ${c.cyan("https://sugarcube.sh")}`)}o(fn,"getComponentsDir");function G(e,t=process.cwd()){try{const n=lt(t,"package.json");if(!F(n))return!1;const s=Se(n,"utf-8"),r=JSON.parse(s),i={...r.dependencies,...r.devDependencies,...r.peerDependencies};return e in i}catch{return!1}}o(G,"isPackageInstalled");async function Ge(e,{withFallback:t=!1}={}){const n=await ht({programmatic:!0,cwd:e});if(n?.startsWith("yarn@"))return"yarn";if(n?.startsWith("pnpm@"))return"pnpm";if(n==="bun")return"bun";if(!t)return n?.split("@")[0]??"npm";const s=process.env.npm_config_user_agent||"";return s.startsWith("yarn")?"yarn":s.startsWith("pnpm")?"pnpm":s.startsWith("bun")?"bun":"npm"}o(Ge,"getPackageManager");function pn(e=process.cwd()){return wt(e)!==null}o(pn,"isTypeScriptProject");async function We(e=process.cwd()){return pn(e)?"sugarcube.config.ts":"sugarcube.config.js"}o(We,"getConfigFileName");function dn(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)}o(dn,"isValidIdentifier");function ye(e,t=0){const n=" ".repeat(t);if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.length===0?"[]":`[
125
+ Stuck? ${c.cyan("https://sugarcube.sh")}`)}o(pn,"getComponentsDir");function G(e,t=process.cwd()){try{const n=ft(t,"package.json");if(!F(n))return!1;const s=Se(n,"utf-8"),r=JSON.parse(s),i={...r.dependencies,...r.devDependencies,...r.peerDependencies};return e in i}catch{return!1}}o(G,"isPackageInstalled");async function Ge(e,{withFallback:t=!1}={}){const n=await yt({programmatic:!0,cwd:e});if(n?.includes("yarn"))return"yarn";if(n?.includes("pnpm"))return"pnpm";if(n?.includes("bun"))return"bun";if(n?.includes("npm"))return"npm";if(t){const s=process.env.npm_config_user_agent||"";if(s.includes("yarn"))return"yarn";if(s.includes("pnpm"))return"pnpm";if(s.includes("bun"))return"bun"}return"npm"}o(Ge,"getPackageManager");function gn(e=process.cwd()){return Tt(e)!==null}o(gn,"isTypeScriptProject");async function Be(e=process.cwd()){return gn(e)?"sugarcube.config.ts":"sugarcube.config.js"}o(Be,"getConfigFileName");function mn(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)}o(mn,"isValidIdentifier");function ye(e,t=0){const n=" ".repeat(t);if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.length===0?"[]":`[
126
126
  ${e.map(r=>`${n} ${ye(r,t+1)}`).join(`,
127
127
  `)}
128
128
  ${n}]`;if(typeof e=="object"){const s=Object.entries(e);return s.length===0?"{}":`{
129
- ${s.map(([i,l])=>{const a=dn(i)?i:JSON.stringify(i);return`${n} ${a}: ${ye(l,t+1)}`}).join(`,
129
+ ${s.map(([i,l])=>{const a=mn(i)?i:JSON.stringify(i);return`${n} ${a}: ${ye(l,t+1)}`}).join(`,
130
130
  `)}
131
- ${n}}`}return JSON.stringify(e)}o(ye,"formatValue");function gn(e,t,n){const s=ye(e,0);let r;return n?r=t?`import type { UserConfig } from "@sugarcube-org/vite";
131
+ ${n}}`}return JSON.stringify(e)}o(ye,"formatValue");function hn(e,t,n){const s=ye(e,0);let r;return n?r=t?`import type { UserConfig } from "@sugarcube-org/vite";
132
132
 
133
133
  const config: UserConfig = `:`/**
134
134
  * @type {import('@sugarcube-org/vite').UserConfig}
@@ -137,12 +137,12 @@ const config = `:r=`// Configuration reference: ${De.CONFIGURATION}
137
137
  const config = `,`${r}${s};
138
138
 
139
139
  export default config;
140
- `}o(gn,"formatConfigAsCode");async function Be(e,t){try{const n=await We(),s=n.endsWith(".ts"),r=gn(e,s,t);await X(n,r,"utf-8")}catch(n){const s=n instanceof Error?`: ${n.message}`:"";throw new g(`Failed to write config file${s}`)}}o(Be,"writeUserConfig");function mn(e,t){return{...e,...t,output:{...e.output??{},...t.output??{}},transforms:{...e.transforms??{},...t.transforms??{}}}}o(mn,"mergeUserConfig");async function Ve(e){const{config:t}=await ot(),n=mn(t,e),s=G(ue);await Be(n,s)}o(Ve,"mergeConfigIntoFile");const hn=new j().name("components").description("Add components to your project").argument("[components...]","Components to add (e.g., button card)").option("-f, --framework <type>","Framework to use (react, css-only)").option("--components-dir <dir>","Components output directory (e.g., 'src/components')").option("-s, --silent","Suppress logs and prompts").option("-o, --overwrite","Overwrite existing files").action(async(e,t)=>{try{t.silent||J(Y(c.bgGreen(c.black("Components"))));const{directory:n,fromConfig:s}=await fn(t.componentsDir);let r=[],i;if(e.length>0||t.framework){if(!t.framework)throw new g(w.COMPONENTS_FRAMEWORK_REQUIRED());if(!["react","css-only"].includes(t.framework))throw new g(w.COMPONENTS_INVALID_FRAMEWORK());i=t.framework,r=e}else{i=await Pe(!1);const T=await U();T||(be("Failed to fetch component list"),process.exit(1)),r=await Qt(T,i)}const l=await Ge(process.cwd(),{withFallback:!0}),a=await U(),f=await de(a,r,i),u=await _t({selectedComponents:r,componentType:i,componentsOutputDirectory:n}),p=Fe(u);if(p&&!t.force&&!t.silent){const T=je(p,{});S.space(1),await Le("Continue?",!1)}const d=[],h=[],k=new Set;for(const T of f){const C=T.dependencies?.[i]||[];for(const I of C)k.add(I)}const b=Array.from(k).filter(T=>!G(T,process.cwd()));b.length>0&&d.push({pending:`Install ${b.length} dependencies`,start:`Installing ${b.join(", ")}...`,end:`Installed ${b.join(", ")}`,while:o(async()=>{await ge(b,process.cwd(),l)},"while")});for(const T of f)d.push({pending:`Write component files for ${T.name}`,start:`Writing component files for ${T.name}...`,end:`Wrote component files for ${T.name}`,while:o(async()=>{const C=await vt({registryIndex:a,selectedComponents:[T.name],componentType:i,componentsOutputDirectory:n,overwrite:t.overwrite||!1,packageManager:l});h.push(...C.createdFiles)},"while")});if(await S.tasks(d,{successMessage:"Components added successfully! \u{1F389} ",minDurationMs:0,successAsOutro:!0}),cn(""),!s&&A()){const T=$(process.cwd(),n);await Ve({output:{components:T}})}}catch(n){q(n)}}),wn=new j().name("cube").description("Add CUBE CSS to your project").option("-s, --silent","Suppress logs and prompts").option("-f, --force","Skip overwrite confirmation").option("--styles-dir <dir>","CSS output directory (e.g., 'src/styles')").action(async e=>{try{e.silent||J(Y("CUBE CSS"));const{directory:t,fromConfig:n}=await un(e.stylesDir);try{await V(t,{recursive:!0})}catch(l){const a=l instanceof Error?`: ${l.message}`:"";throw new g(`Failed to create output directory${a}`)}const s=await Dt({cubeDirectory:t}),r=Fe(s);if(r&&!e.force&&!e.silent){S.space(1);const l=je(r,{});await Le("Continue?",!1)}const i=await Ft(t);if(!e.silent){S.space(1);const l=i,u=[...new Set(l)].map(p=>$(process.cwd(),p)).map(p=>({pending:`Write ${p}`,start:`Writing ${p}`,end:`Wrote ${p}`,while:o(async()=>{},"while")}));await S.tasks(u,{spacing:0,minDurationMs:0,successPauseMs:100,successMessage:"\u{1F389} Files written!"}),ne(c.green("CUBE added successfully."))}if(!n&&A()){const l=$(process.cwd(),t);await Ve({output:{css:l}})}}catch(t){q(t)}});function yn(){return["**/*.{html,htm,js,ts,jsx,tsx,vue,svelte,astro,php,njk,liquid,pug,hbs,handlebars,twig,erb,ejs}","!node_modules/**","!dist/**","!build/**","!.next/**","!.nuxt/**","!.astro/**","!.git/**","!coverage/**","!*.config.{js,ts,mjs}"]}o(yn,"getDefaultScanPatterns");function Tn(){return yn()}o(Tn,"getScanPatterns");async function Ke(e,t){const n={name:"sugarcube",rules:rt(t.utilities??{},e),preflights:[]},s=await yt({presets:[n]}),r=Tn(),i=await ce(r,{dot:!0});if(i.length===0)return[];const a=(await Promise.all(i.map(u=>et(u,"utf8")))).join(`
141
- `),{css:f}=await s.generate(a,{preflights:!1});return f?.trim()?[{path:`${t.output?.css||it}/utilities/utilities.gen.css`,css:f,collection:"default"}]:[]}o(Ke,"generateSugarcubeUtilities");async function Sn(e,t,n){const s=[],r=await oe(e,t,n),i=await Ie(r,n);await Ee(i),s.push(...i);const l=await Ke(r,n);return await ke(l),s.push(...l),s}o(Sn,"generateAllCSS");const In=new j().name("generate").description("Generate CSS from your design tokens").option("--force","Skip overwrite confirmation").option("-s, --silent","Suppress logs and prompts").action(async e=>{try{if(e.silent||J(Y("Generate CSS")),G("@sugarcube-org/vite"))throw new g("Sugarcube vite plugin detected. When using the plugin, CSS is generated automatically during your build process. Remove the plugin to use CLI generation instead.");if(!A())throw new g(`A sugarcube config file was not found. This command requires one.
140
+ `}o(hn,"formatConfigAsCode");async function We(e,t){try{const n=await Be(),s=n.endsWith(".ts"),r=hn(e,s,t);await X(n,r,"utf-8")}catch(n){const s=n instanceof Error?`: ${n.message}`:"";throw new g(`Failed to write config file${s}`)}}o(We,"writeUserConfig");function wn(e,t){return{...e,...t,output:{...e.output??{},...t.output??{}},transforms:{...e.transforms??{},...t.transforms??{}}}}o(wn,"mergeUserConfig");async function Ve(e){const{config:t}=await it(),n=wn(t,e),s=G(ue);await We(n,s)}o(Ve,"mergeConfigIntoFile");const yn=new j().name("components").description("Add components to your project").argument("[components...]","Components to add (e.g., button card)").option("-f, --framework <type>","Framework to use (react, css-only)").option("--components-dir <dir>","Components output directory (e.g., 'src/components')").option("-s, --silent","Suppress logs and prompts").option("-o, --overwrite","Overwrite existing files").action(async(e,t)=>{try{t.silent||z(Y(c.bgGreen(c.black("Components"))));const{directory:n,fromConfig:s}=await pn(t.componentsDir);let r=[],i;if(e.length>0||t.framework){if(!t.framework)throw new g(w.COMPONENTS_FRAMEWORK_REQUIRED());if(!["react","css-only"].includes(t.framework))throw new g(w.COMPONENTS_INVALID_FRAMEWORK());i=t.framework,r=e}else{i=await Pe(!1);const T=await U();T||(be("Failed to fetch component list"),process.exit(1)),r=await en(T,i)}const l=await Ge(process.cwd(),{withFallback:!0}),a=await U(),p=await pe(a,r,i),u=await At({selectedComponents:r,componentType:i,componentsOutputDirectory:n}),f=Fe(u);if(f&&!t.force&&!t.silent){const T=je(f,{});S.space(1),await Le("Continue?",!1)}const d=[],h=[],k=new Set;for(const T of p){const C=T.dependencies?.[i]||[];for(const I of C)k.add(I)}const b=Array.from(k).filter(T=>!G(T,process.cwd()));b.length>0&&d.push({pending:`Install ${b.length} dependencies`,start:`Installing ${b.join(", ")}...`,end:`Installed ${b.join(", ")}`,while:o(async()=>{await ge(b,process.cwd(),l)},"while")});for(const T of p)d.push({pending:`Write component files for ${T.name}`,start:`Writing component files for ${T.name}...`,end:`Wrote component files for ${T.name}`,while:o(async()=>{const C=await Ft({registryIndex:a,selectedComponents:[T.name],componentType:i,componentsOutputDirectory:n,overwrite:t.overwrite||!1,packageManager:l});h.push(...C.createdFiles)},"while")});if(await S.tasks(d,{successMessage:"Components added successfully! \u{1F389} ",minDurationMs:0,successAsOutro:!0}),un(""),!s&&A()){const T=$(process.cwd(),n);await Ve({output:{components:T}})}}catch(n){J(n)}}),Tn=new j().name("cube").description("Add CUBE CSS to your project").option("-s, --silent","Suppress logs and prompts").option("-f, --force","Skip overwrite confirmation").option("--styles-dir <dir>","CSS output directory (e.g., 'src/styles')").action(async e=>{try{e.silent||z(Y("CUBE CSS"));const{directory:t,fromConfig:n}=await dn(e.stylesDir);try{await V(t,{recursive:!0})}catch(l){const a=l instanceof Error?`: ${l.message}`:"";throw new g(`Failed to create output directory${a}`)}const s=await Nt({cubeDirectory:t}),r=Fe(s);if(r&&!e.force&&!e.silent){S.space(1);const l=je(r,{});await Le("Continue?",!1)}const i=await Pt(t);if(!e.silent){S.space(1);const l=i,u=[...new Set(l)].map(f=>$(process.cwd(),f)).map(f=>({pending:`Write ${f}`,start:`Writing ${f}`,end:`Wrote ${f}`,while:o(async()=>{},"while")}));await S.tasks(u,{spacing:0,minDurationMs:0,successPauseMs:100,successMessage:"\u{1F389} Files written!"}),ne(c.green("CUBE added successfully."))}if(!n&&A()){const l=$(process.cwd(),t);await Ve({output:{css:l}})}}catch(t){J(t)}}),Sn="**/*.{html,htm,js,ts,jsx,tsx,vue,svelte,astro,php,njk,liquid,pug,hbs,handlebars,twig,erb,ejs}",In=["**/node_modules/**","**/dist/**","**/build/**","**/.next/**","**/.nuxt/**","**/.astro/**","**/.git/**","**/coverage/**","**/.pnpm/**","**/.pnpm-store/**","**/.npm/**","**/.cache/**","**/.turbo/**","**/.vercel/**","**/.svelte-kit/**","**/out/**","**/__snapshots__/**","**/*.config.{js,ts,mjs}","**/*.min.js","**/*.bundle.js","**/*.d.ts"],Ke=1e4,Ye=100;async function He(e,t){const n={name:"sugarcube",rules:at(t.utilities??{},e),preflights:[]},s=await St({presets:[n]}),r=await ce(Sn,{ignore:In,dot:!1,onlyFiles:!0,absolute:!1});if(r.length===0)return[];if(r.length>Ke)throw new g(`Found ${r.length} files to scan (limit: ${Ke}). Are you running this from a monorepo root or a directory containing multiple projects? Run the command from within a single project directory instead.`);const i=[];let l=0;const a=Ye*1024*1024;for(const f of r){const d=await nt(f,"utf8");if(l+=d.length,l>a)throw new g(`Total source size exceeds ${Ye}MB. Are you running this from a monorepo root or a directory containing multiple projects? Run the command from within a single project directory instead.`);i.push(d)}const p=i.join(`
141
+ `),{css:u}=await s.generate(p,{preflights:!1});return u?.trim()?[{path:`${t.output?.css||ct}/utilities/utilities.gen.css`,css:u,collection:"default"}]:[]}o(He,"generateSugarcubeUtilities");async function En(e,t,n){const s=[],r=await oe(e,t,n),i=await Ie(r,n);await Ee(i),s.push(...i);const l=await He(r,n);return await ke(l),s.push(...l),s}o(En,"generateAllCSS");const kn=new j().name("generate").description("Generate CSS from your design tokens").option("--force","Skip overwrite confirmation").option("-s, --silent","Suppress logs and prompts").action(async e=>{try{if(e.silent||z(Y("Generate CSS")),G("@sugarcube-org/vite"))throw new g("Sugarcube vite plugin detected. When using the plugin, CSS is generated automatically during your build process. Remove the plugin to use CLI generation instead.");if(!A())throw new g(`A sugarcube config file was not found. This command requires one.
142
142
 
143
- Please run ${c.cyan(v.INIT)} (or manually create a config file).
143
+ Please run ${c.cyan(N.INIT)} (or manually create a config file).
144
144
 
145
- Stuck? ${c.cyan("https://sugarcube.sh")}`);const{config:t}=await ee(),{trees:n,resolved:s}=await K(t),r=await Sn(n,s,t);if(!e.silent){const i=r.map(u=>u.path),f=[...new Set(i)].map(u=>$(process.cwd(),u)).map(u=>({pending:`Write ${u}`,start:`Writing ${u}`,end:`Wrote ${u}`,while:o(async()=>{},"while")}));await S.tasks(f,{spacing:1,minDurationMs:0,successPauseMs:100,successMessage:"\u{1F389} Files written!"}),S.space(1),ne(c.green("CSS generated successfully."))}}catch(t){q(t)}});function En(e){return{source:[R($(process.cwd(),e.actualTokensDir),_e)]}}o(En,"createSingleTokenCollection");async function kn(e){return En(e)}o(kn,"buildTokensConfig");async function bn(e){const t=await kn({actualTokensDir:e.actualTokensDir}),n=$(process.cwd(),e.actualStylesDir),s=e.isSrcDir?re.output.components:re.output.components.replace(/^src\//,"");return{tokens:t,output:{css:n,components:s,separate:re.output.separate}}}o(bn,"buildUserConfig");function Ye(e,t=0){if(typeof e!="object"||e===null||t>Et)return!1;for(const[n,s]of Object.entries(e))if(!n.startsWith("$")&&typeof s=="object"&&s!==null&&("$value"in s||Ye(s,t+1)))return!0;return!1}o(Ye,"hasAnyToken");async function Cn(e){try{const t=await ce(_e,{cwd:e,absolute:!0});for(const n of t)try{const s=await se.readFile(n,"utf-8"),r=JSON.parse(s);if(Ye(r))return!0}catch{}return!1}catch{return!1}}o(Cn,"detectExistingTokens");function He(e){try{const t=ie.resolve(e,"package.json");if(!F(t))return null;const n=Se(t,"utf-8");return JSON.parse(n)}catch{return null}}o(He,"getPackageJson");function M(e,t){if(!e)return!1;const n=e.dependencies,s=e.devDependencies;return!!(n?.[t]||s?.[t])}o(M,"hasDependency");function $n(e,t){if(!e)return!1;const n=e.dependencies,s=e.devDependencies,r={...n,...s};return Object.keys(r).some(i=>i.startsWith(t))}o($n,"hasDependencyStartingWith");function Rn(e){const t=F(ie.resolve(e,"src")),n=He(e),s=t?"src/design-tokens":"design-tokens",r=t?"src/styles":"styles",i=t?"src/components":"components";let l="none";return M(n,"next")?l=F(ie.resolve(e,`${t?"src/":""}app`))?"next-app":"next-pages":M(n,"astro")?l="astro":M(n,"nuxt")?l="nuxt":M(n,"@sveltejs/kit")?l="sveltekit":$n(n,"@remix-run/")?l="remix":M(n,"@11ty/eleventy")?l="eleventy":M(n,"vite")&&(l="vite"),{framework:l,isSrcDir:t,tokensDir:s,stylesDir:r,componentDir:i}}o(Rn,"getProjectInfo");function _n(e,t){if(["vite","astro","nuxt","sveltekit","remix"].includes(e))return!0;if(e==="eleventy"){const s=He(t);return M(s,"vite")}return!1}o(_n,"shouldInstallVitePlugin");const Dn=o(async e=>{S.space(2),await x(200);let t="Next steps";if(e.pluginToInstall===ue)t+=`
145
+ Stuck? ${c.cyan("https://sugarcube.sh")}`);const{config:t}=await ee(),{trees:n,resolved:s}=await K(t),r=await En(n,s,t);if(!e.silent){const i=r.map(u=>u.path),p=[...new Set(i)].map(u=>$(process.cwd(),u)).map(u=>({pending:`Write ${u}`,start:`Writing ${u}`,end:`Wrote ${u}`,while:o(async()=>{},"while")}));await S.tasks(p,{spacing:1,minDurationMs:0,successPauseMs:100,successMessage:"\u{1F389} Files written!"}),S.space(1),ne(c.green("CSS generated successfully."))}}catch(t){J(t)}});function bn(e){return{source:[_($(process.cwd(),e.actualTokensDir),Re)]}}o(bn,"createSingleTokenCollection");async function Cn(e){return bn(e)}o(Cn,"buildTokensConfig");async function $n(e){const t=await Cn({actualTokensDir:e.actualTokensDir}),n=$(process.cwd(),e.actualStylesDir),s=e.isSrcDir?re.output.components:re.output.components.replace(/^src\//,"");return{tokens:t,output:{css:n,components:s,separate:re.output.separate}}}o($n,"buildUserConfig");function ze(e,t=0){if(typeof e!="object"||e===null||t>bt)return!1;for(const[n,s]of Object.entries(e))if(!n.startsWith("$")&&typeof s=="object"&&s!==null&&("$value"in s||ze(s,t+1)))return!0;return!1}o(ze,"hasAnyToken");async function _n(e){try{const t=await ce(Re,{cwd:e,absolute:!0});for(const n of t)try{const s=await se.readFile(n,"utf-8"),r=JSON.parse(s);if(ze(r))return!0}catch{}return!1}catch{return!1}}o(_n,"detectExistingTokens");function Je(e){try{const t=ie.resolve(e,"package.json");if(!F(t))return null;const n=Se(t,"utf-8");return JSON.parse(n)}catch{return null}}o(Je,"getPackageJson");function M(e,t){if(!e)return!1;const n=e.dependencies,s=e.devDependencies;return!!(n?.[t]||s?.[t])}o(M,"hasDependency");function Rn(e,t){if(!e)return!1;const n=e.dependencies,s=e.devDependencies,r={...n,...s};return Object.keys(r).some(i=>i.startsWith(t))}o(Rn,"hasDependencyStartingWith");function Dn(e){const t=F(ie.resolve(e,"src")),n=Je(e),s=t?"src/design-tokens":"design-tokens",r=t?"src/styles":"styles",i=t?"src/components":"components";let l="none";return M(n,"next")?l=F(ie.resolve(e,`${t?"src/":""}app`))?"next-app":"next-pages":M(n,"astro")?l="astro":M(n,"nuxt")?l="nuxt":M(n,"@sveltejs/kit")?l="sveltekit":Rn(n,"@remix-run/")?l="remix":M(n,"@11ty/eleventy")?l="eleventy":M(n,"vite")&&(l="vite"),{framework:l,isSrcDir:t,tokensDir:s,stylesDir:r,componentDir:i}}o(Dn,"getProjectInfo");function An(e,t){if(["vite","astro","nuxt","sveltekit","remix"].includes(e))return!0;if(e==="eleventy"){const s=Je(t);return M(s,"vite")}return!1}o(An,"shouldInstallVitePlugin");const Nn=o(async e=>{S.space(2),await x(200);let t="Next steps";if(e.pluginToInstall===ue)t+=`
146
146
 
147
147
  `,t+=`1. Import the generated CSS
148
148
  `,t+=` ${c.cyan("import 'virtual:sugarcube.css'")}`;else{const n=`${e.stylesDir}/global/tokens.variables.gen.css`;t+=`
@@ -151,9 +151,9 @@ Stuck? ${c.cyan("https://sugarcube.sh")}`);const{config:t}=await ee(),{trees:n,r
151
151
  `,t+=` ${c.cyan(`import './${n}'`)}`}t+=`
152
152
 
153
153
  `,t+=`2. (Optional) Add CUBE CSS
154
- `,t+=` ${c.cyan(v.CUBE)}`,t+=`
154
+ `,t+=` ${c.cyan(N.CUBE)}`,t+=`
155
155
 
156
156
  `,t+=`3. (Optional) Add components
157
- `,t+=` ${c.cyan(v.COMPONENTS)}`,t+=`
157
+ `,t+=` ${c.cyan(N.COMPONENTS)}`,t+=`
158
158
 
159
- `,t+=`Docs: ${c.cyan("https://sugarcube.sh")}`,nn(t,{width:.75}),await x(200),S.break(1)},"nextSteps");async function An(e){await Dn(e)}o(An,"next");const vn=o(async()=>{const e=["Welcome to sugarcube \u2014 the toolkit for seriously sweet frontends!"];S.space(1),await S.animated(e,{clear:!1})},"welcome");function Je(e,t){if(!e||e.trim()==="")throw new g(w.DIRECTORY_PATH_EMPTY(t));const s=Qe(e).split("/")[0];if(s&&It.includes(s))throw new g(w.DIRECTORY_PATH_RESERVED(t,e))}o(Je,"validateDirectoryPath");function Nn(e){e.tokensDir&&Je(e.tokensDir,"tokens-dir"),e.stylesDir&&Je(e.stylesDir,"styles-dir")}o(Nn,"validateOptions");async function Fn(){A()&&(we(w.CONFIG_EXISTS(),{}),process.exit(0))}o(Fn,"preflightInit");async function On(e){const t=Rn(process.cwd()),n=e.tokensDir||t.tokensDir,s=e.stylesDir||t.stylesDir,r=await Cn(n);return{tokensDir:n,stylesDir:s,isSrcDir:t.isSrcDir,hasExistingTokens:r,framework:t.framework}}o(On,"initializeProjectContext");function Pn(e,t,n){const s=t?null:e.kit||le;if((e.skip||[]).includes("plugin"))return{starterKit:s,pluginToInstall:null};const i=Ln(n,process.cwd());return{starterKit:s,pluginToInstall:i}}o(Pn,"determineInstallationTargets");function Ln(e,t){return _n(e,t)?ue:null}o(Ln,"determinePlugin");async function Mn(e,t,n,s,r){const i=await Ge(process.cwd(),{withFallback:!0});return{options:e,...t,isSrcDir:t.isSrcDir,config:n,userConfig:s,...r,packageManager:i,createdFiles:[],createdDirectories:[],installedDependencies:[],tasks:[]}}o(Mn,"buildInitContext");async function jn(e){const{trees:t,resolved:n}=await K(e.config);e.setupResult={config:e.config,createdTokenPaths:[],trees:t,resolved:n,tokenFiles:[],tokensDir:e.tokensDir}}o(jn,"processExistingTokens");async function Un(e){!e.hasExistingTokens&&e.starterKit?await Zt(e):await jn(e)}o(Un,"setupDesignTokens");async function xn(e){if(!e.setupResult)throw new g(w.INITIALIZATION_INCOMPLETE());const{trees:t,resolved:n}=e.setupResult,s=await oe(t,n,e.config),r=await Ie(s,e.config);await Ee(r)}o(xn,"writeCSSVariables");async function Gn(e){if(!e.setupResult)throw new g(w.INITIALIZATION_INCOMPLETE());const{trees:t,resolved:n}=e.setupResult,s=await oe(t,n,e.config),r=await Ke(s,e.config);r.length&&await ke(r)}o(Gn,"writeCSSUtilities");async function Wn(e){if(e.pluginToInstall&&!G(e.pluginToInstall))try{await ge([e.pluginToInstall],process.cwd(),e.packageManager),e.installedDependencies.push(e.pluginToInstall)}catch{throw new g(w.PLUGIN_INSTALL_FAILED({pluginToInstall:e.pluginToInstall,packageManager:e.packageManager}))}}o(Wn,"installPlugins");async function Bn(e){try{const t=!!e.pluginToInstall;await Be(e.userConfig,t);const n=await We();e.createdFiles.push(n)}catch{throw new g(w.CONFIG_WRITE_FAILED())}}o(Bn,"finalize");function Vn(e){const t=[];if(e.hasExistingTokens?t.push({pending:"Looking for existing tokens",start:"Looking for existing tokens...",end:`Existing tokens found at ${e.tokensDir} ${E("\u2192","->")} using them`,while:o(async()=>{},"while")}):e.starterKit&&t.push({pending:"Looking for existing tokens",start:"Looking for existing tokens...",end:`No existing tokens detected ${E("\u2192","->")} adding starter kit`,while:o(async()=>{},"while")}),e.pluginToInstall){const n="Vite";G(e.pluginToInstall)?t.push({pending:`Checking for ${n} compatibility`,start:`Checking for ${n} compatibility...`,end:`${n} plugin already installed ${E("\u2192","->")} skipping plugin installation`,while:o(async()=>{},"while")}):t.push({pending:"Checking for Vite compatibility",start:"Checking for Vite compatibility...",end:`Vite detected ${E("\u2192","->")} plugin will be installed`,while:o(async()=>{},"while")})}else{const n=e.options.skip?.includes("plugin");t.push({pending:"Checking for Vite compatibility",start:"Checking for Vite compatibility...",end:n?`Plugin skipped ${E("\u2192","->")} CSS will be generated as file(s)`:`No Vite detected ${E("\u2192","->")} CSS will be generated as file(s)`,while:o(async()=>{},"while")})}return t}o(Vn,"buildDetectionTasks");async function Kn(e){if(e.tasks.push({pending:e.hasExistingTokens?"Process existing design tokens":"Add design tokens",start:e.hasExistingTokens?"Processing existing design tokens...":"Adding design tokens...",end:e.hasExistingTokens?"Design tokens processed":"Design tokens added",while:o(async()=>{await Un(e)},"while")}),!e.pluginToInstall)e.tasks.push({pending:"Generate CSS variables",start:"Generating CSS variables...",end:"CSS variables generated",while:o(async()=>{await xn(e)},"while")}),e.tasks.push({pending:"Generate CSS utilities",start:"Generating CSS utilities...",end:"CSS utilities generated",while:o(async()=>{await Gn(e)},"while")});else if(e.pluginToInstall&&!G(e.pluginToInstall)){const t="Vite";e.tasks.push({pending:`Install ${t} plugin`,start:`Installing ${t} plugin...`,end:`${t} plugin installed`,while:o(async()=>{await Wn(e)},"while")})}e.tasks.push({pending:"Write configuration file",start:"Writing configuration file...",end:"Configuration file written",while:o(async()=>{await Bn(e)},"while")})}o(Kn,"buildExecutionTasks");const Yn=new j().name("init").description("Initialize a new sugarcube project").option("--kit <kit>",`Starter kit to use (default: ${le})`,le).option("--tokens-dir <dir>","Design tokens directory (e.g., 'src/design-tokens')").option("--styles-dir <dir>","Styles output directory (e.g., 'src/styles')").option("--with <items...>","Install optional items").option("--skip <items...>","Skip installation of specific items (e.g., plugin)").action(async e=>{let t;try{Nn(e),await Fn();const n=await On(e),s=await bn({actualTokensDir:n.tokensDir,actualStylesDir:n.stylesDir,isSrcDir:n.isSrcDir}),r=at(s),i=Pn(e,n.hasExistingTokens,n.framework);t=await Mn(e,n,r,s,i),J(Y("sugarcube")),await vn();const l=Vn(t);l.length>0&&(S.message("Detecting project\u2026"),await S.tasks(l,{minDurationMs:1e3})),t.tasks=[],await Kn(t),t.tasks.length>0&&(S.message("Setting things up\u2026"),await S.tasks(t.tasks,{successMessage:"\u{1F389} Tasks completed successfully!"})),await An(t)}catch(n){q(n)}}),Hn=new j().name("validate").description("Validate design token files").argument("[paths...]","Token files or directories to validate (e.g., src/design-tokens)").action(async e=>{try{if(J(Y("Validate")),A()&&!e.length){const{config:s}=await ee();await K(s),ne(c.greenBright("All tokens valid \u2728"));return}if(!e.length)throw new g(w.VALIDATE_NO_PATH_SPECIFIED());for(const s of e)if(!F(s))throw new g(w.VALIDATE_PATH_NOT_FOUND(s));const t=await ce(e.map(s=>s.endsWith(".json")?s:R(s,"**/*.json")));if(t.length===0)throw new g(w.VALIDATE_NO_TOKEN_FILES());const n=A()?(await ee()).config:{tokens:{source:[]},output:{css:".",separate:!1,modeAttribute:"data-mode",themeAttribute:"data-theme"},transforms:{fluid:{min:320,max:1200},colorFallbackStrategy:"native"}};await K({...n,tokens:{source:t.map(s=>$(process.cwd(),s))}}),ne(c.greenBright("All tokens valid \u2728"))}catch(t){q(t)}});process.on("SIGINT",()=>process.exit(0)),process.on("SIGTERM",()=>process.exit(0));async function Jn(){const e=new j().name("sugarcube").description("CLI for scaffolding sugarcube projects").version(St.version,"-v, --version","display the version number");e.addCommand(Yn).addCommand(In).addCommand(Hn).addCommand(hn).addCommand(wn),e.parse()}o(Jn,"main"),Jn();
159
+ `,t+=`Docs: ${c.cyan("https://sugarcube.sh")}`,on(t,{width:.75}),await x(200),S.break(1)},"nextSteps");async function vn(e){await Nn(e)}o(vn,"next");const Fn=o(async()=>{const e=["Welcome to sugarcube \u2014 the toolkit for seriously sweet frontends!"];S.space(1),await S.animated(e,{clear:!1})},"welcome");function qe(e,t){if(!e||e.trim()==="")throw new g(w.DIRECTORY_PATH_EMPTY(t));const s=et(e).split("/")[0];if(s&&kt.includes(s))throw new g(w.DIRECTORY_PATH_RESERVED(t,e))}o(qe,"validateDirectoryPath");function On(e){e.tokensDir&&qe(e.tokensDir,"tokens-dir"),e.stylesDir&&qe(e.stylesDir,"styles-dir")}o(On,"validateOptions");async function Pn(){A()&&(we(w.CONFIG_EXISTS(),{}),process.exit(0))}o(Pn,"preflightInit");async function Ln(e){const t=Dn(process.cwd()),n=e.tokensDir||t.tokensDir,s=e.stylesDir||t.stylesDir,r=await _n(n);return{tokensDir:n,stylesDir:s,isSrcDir:t.isSrcDir,hasExistingTokens:r,framework:t.framework}}o(Ln,"initializeProjectContext");function Mn(e,t,n){const s=t?null:e.kit||le;if((e.skip||[]).includes("plugin"))return{starterKit:s,pluginToInstall:null};const i=jn(n,process.cwd());return{starterKit:s,pluginToInstall:i}}o(Mn,"determineInstallationTargets");function jn(e,t){return An(e,t)?ue:null}o(jn,"determinePlugin");async function Un(e,t,n,s,r){const i=await Ge(process.cwd(),{withFallback:!0});return{options:e,...t,isSrcDir:t.isSrcDir,config:n,userConfig:s,...r,packageManager:i,createdFiles:[],createdDirectories:[],installedDependencies:[],tasks:[]}}o(Un,"buildInitContext");async function xn(e){const{trees:t,resolved:n}=await K(e.config);e.setupResult={config:e.config,createdTokenPaths:[],trees:t,resolved:n,tokenFiles:[],tokensDir:e.tokensDir}}o(xn,"processExistingTokens");async function Gn(e){!e.hasExistingTokens&&e.starterKit?await Xt(e):await xn(e)}o(Gn,"setupDesignTokens");async function Bn(e){if(!e.setupResult)throw new g(w.INITIALIZATION_INCOMPLETE());const{trees:t,resolved:n}=e.setupResult,s=await oe(t,n,e.config),r=await Ie(s,e.config);await Ee(r)}o(Bn,"writeCSSVariables");async function Wn(e){if(!e.setupResult)throw new g(w.INITIALIZATION_INCOMPLETE());const{trees:t,resolved:n}=e.setupResult,s=await oe(t,n,e.config),r=await He(s,e.config);r.length&&await ke(r)}o(Wn,"writeCSSUtilities");async function Vn(e){if(e.pluginToInstall&&!G(e.pluginToInstall))try{await ge([e.pluginToInstall],process.cwd(),e.packageManager),e.installedDependencies.push(e.pluginToInstall)}catch{throw new g(w.PLUGIN_INSTALL_FAILED({pluginToInstall:e.pluginToInstall,packageManager:e.packageManager}))}}o(Vn,"installPlugins");async function Kn(e){try{const t=!!e.pluginToInstall;await We(e.userConfig,t);const n=await Be();e.createdFiles.push(n)}catch{throw new g(w.CONFIG_WRITE_FAILED())}}o(Kn,"finalize");function Yn(e){const t=[];if(e.hasExistingTokens?t.push({pending:"Looking for existing tokens",start:"Looking for existing tokens...",end:`Existing tokens found at ${e.tokensDir} ${E("\u2192","->")} using them`,while:o(async()=>{},"while")}):e.starterKit&&t.push({pending:"Looking for existing tokens",start:"Looking for existing tokens...",end:`No existing tokens detected ${E("\u2192","->")} adding starter kit`,while:o(async()=>{},"while")}),e.pluginToInstall){const n="Vite";G(e.pluginToInstall)?t.push({pending:`Checking for ${n} compatibility`,start:`Checking for ${n} compatibility...`,end:`${n} plugin already installed ${E("\u2192","->")} skipping plugin installation`,while:o(async()=>{},"while")}):t.push({pending:"Checking for Vite compatibility",start:"Checking for Vite compatibility...",end:`Vite detected ${E("\u2192","->")} plugin will be installed`,while:o(async()=>{},"while")})}else{const n=e.options.skip?.includes("plugin");t.push({pending:"Checking for Vite compatibility",start:"Checking for Vite compatibility...",end:n?`Plugin skipped ${E("\u2192","->")} CSS will be generated as file(s)`:`No Vite detected ${E("\u2192","->")} CSS will be generated as file(s)`,while:o(async()=>{},"while")})}return t}o(Yn,"buildDetectionTasks");async function Hn(e){if(e.tasks.push({pending:e.hasExistingTokens?"Process existing design tokens":"Add design tokens",start:e.hasExistingTokens?"Processing existing design tokens...":"Adding design tokens...",end:e.hasExistingTokens?"Design tokens processed":"Design tokens added",while:o(async()=>{await Gn(e)},"while")}),!e.pluginToInstall)e.tasks.push({pending:"Generate CSS variables",start:"Generating CSS variables...",end:"CSS variables generated",while:o(async()=>{await Bn(e)},"while")}),e.tasks.push({pending:"Generate CSS utilities",start:"Generating CSS utilities...",end:"CSS utilities generated",while:o(async()=>{await Wn(e)},"while")});else if(e.pluginToInstall&&!G(e.pluginToInstall)){const t="Vite";e.tasks.push({pending:`Install ${t} plugin`,start:`Installing ${t} plugin...`,end:`${t} plugin installed`,while:o(async()=>{await Vn(e)},"while")})}e.tasks.push({pending:"Write configuration file",start:"Writing configuration file...",end:"Configuration file written",while:o(async()=>{await Kn(e)},"while")})}o(Hn,"buildExecutionTasks");const zn=new j().name("init").description("Initialize a new sugarcube project").option("--kit <kit>",`Starter kit to use (default: ${le})`,le).option("--tokens-dir <dir>","Design tokens directory (e.g., 'src/design-tokens')").option("--styles-dir <dir>","Styles output directory (e.g., 'src/styles')").option("--with <items...>","Install optional items").option("--skip <items...>","Skip installation of specific items (e.g., plugin)").action(async e=>{let t;try{On(e),await Pn();const n=await Ln(e),s=await $n({actualTokensDir:n.tokensDir,actualStylesDir:n.stylesDir,isSrcDir:n.isSrcDir}),r=lt(s),i=Mn(e,n.hasExistingTokens,n.framework);t=await Un(e,n,r,s,i),z(Y("sugarcube")),await Fn();const l=Yn(t);l.length>0&&(S.message("Detecting project\u2026"),await S.tasks(l,{minDurationMs:1e3})),t.tasks=[],await Hn(t),t.tasks.length>0&&(S.message("Setting things up\u2026"),await S.tasks(t.tasks,{successMessage:"\u{1F389} Tasks completed successfully!"})),await vn(t)}catch(n){J(n)}}),Jn=new j().name("validate").description("Validate design token files").argument("[paths...]","Token files or directories to validate (e.g., src/design-tokens)").action(async e=>{try{if(z(Y("Validate")),A()&&!e.length){const{config:s}=await ee();await K(s),ne(c.greenBright("All tokens valid \u2728"));return}if(!e.length)throw new g(w.VALIDATE_NO_PATH_SPECIFIED());for(const s of e)if(!F(s))throw new g(w.VALIDATE_PATH_NOT_FOUND(s));const t=await ce(e.map(s=>s.endsWith(".json")?s:_(s,"**/*.json")));if(t.length===0)throw new g(w.VALIDATE_NO_TOKEN_FILES());const n=A()?(await ee()).config:{tokens:{source:[]},output:{css:".",separate:!1,modeAttribute:"data-mode",themeAttribute:"data-theme"},transforms:{fluid:{min:320,max:1200},colorFallbackStrategy:"native"}};await K({...n,tokens:{source:t.map(s=>$(process.cwd(),s))}}),ne(c.greenBright("All tokens valid \u2728"))}catch(t){J(t)}});process.on("SIGINT",()=>process.exit(0)),process.on("SIGTERM",()=>process.exit(0));async function qn(){const e=new j().name("sugarcube").description("CLI for scaffolding sugarcube projects").version(Et.version,"-v, --version","display the version number");e.addCommand(zn).addCommand(kn).addCommand(Jn).addCommand(yn).addCommand(Tn),e.parse()}o(qn,"main"),qn();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sugarcube-org/cli",
3
- "version": "0.0.0-alpha.21",
3
+ "version": "0.0.0-alpha.22",
4
4
  "publishConfig": {
5
5
  "access": "public",
6
6
  "provenance": false