@sugarcube-org/cli 0.0.0-alpha.8 → 0.0.0-alpha.9

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 +15 -15
  2. package/package.json +5 -1
package/dist/index.mjs CHANGED
@@ -1,30 +1,30 @@
1
1
  #!/usr/bin/env node
2
- var xe=Object.defineProperty;var l=(e,n)=>xe(e,"name",{value:n,configurable:!0});import{Command as M}from"commander";import{validationPipeline as Ce,generationPipeline as $e,getTokenPathsFromConfig as je,writeCSSFilesToDisk as Fe,validateConfig as ae,manageCSSIndex as Ee,loadConfig as G}from"@sugarcube-org/core";import{z as w}from"zod";import u from"picocolors";import{existsSync as T}from"fs";import{text as L,isCancel as S,select as W,multiselect as Z,confirm as U,log as v,spinner as ee,intro as J,note as V,cancel as Y,outro as z}from"@clack/prompts";import m from"path";import Ie from"node-fetch";import{readFile as ce,writeFile as _,mkdir as P}from"fs/promises";import le from"fast-glob";import{execa as De}from"execa";import{detect as Te}from"@antfu/ni";import te from"node:fs/promises";const $={error:u.red,warn:u.yellow,info:u.cyan,success:u.green,bold:u.bold,path:u.cyan},C={error(...e){console.log($.error(e.join(" ")))},warn(...e){console.log($.warn(e.join(" ")))},info(...e){console.log($.info(e.join(" ")))},success(...e){console.log($.success(e.join(" ")))},log(...e){console.log(e.join(" "))},break(){console.log("")}};class d extends Error{static{l(this,"CLIError")}constructor(n,t){super(n),this.name="CLIError",this.cause=t}}async function B(e,n={type:"files",paths:e}){const{trees:t,resolved:o,errors:s}=await Ce(e,{loader:n});if(s.load.length>0)throw new d(`Failed to load token files:
2
+ var Ce=Object.defineProperty;var l=(e,n)=>Ce(e,"name",{value:n,configurable:!0});var $e=(e,n)=>()=>(n||e((n={exports:{}}).exports,n),n.exports);import{Command as M}from"commander";import{validationPipeline as je,generationPipeline as Fe,getTokenPathsFromConfig as Ee,writeCSSFilesToDisk as Ie,validateConfig as ce,manageCSSIndex as De,loadConfig as G}from"@sugarcube-org/core";import{z as w}from"zod";import u from"picocolors";import{existsSync as T}from"fs";import{text as L,isCancel as S,select as W,multiselect as Z,confirm as U,log as v,spinner as ee,intro as J,note as V,cancel as Y,outro as z}from"@clack/prompts";import m from"path";import Te from"node-fetch";import{readFile as le,writeFile as _,mkdir as P}from"fs/promises";import pe from"fast-glob";import{execa as Ne}from"execa";import{detect as Pe}from"@antfu/ni";import te from"node:fs/promises";var $t=$e(ie=>{const $={error:u.red,warn:u.yellow,info:u.cyan,success:u.green,bold:u.bold,path:u.cyan},C={error(...e){console.log($.error(e.join(" ")))},warn(...e){console.log($.warn(e.join(" ")))},info(...e){console.log($.info(e.join(" ")))},success(...e){console.log($.success(e.join(" ")))},log(...e){console.log(e.join(" "))},break(){console.log("")}};class d extends Error{static{l(this,"CLIError")}constructor(n,t){super(n),this.name="CLIError",this.cause=t}}async function B(e,n={type:"files",paths:e}){const{trees:t,resolved:o,errors:s}=await je(e,{loader:n});if(s.load.length>0)throw new d(`Failed to load token files:
3
3
  ${s.load.map(i=>`${i.file}: ${i.message}`).join(`
4
- `)}`);if(s.validation.length>0||s.flatten.length>0||s.resolution.length>0){C.break();const i=[...s.flatten,...s.validation,...s.resolution],c=new Map;throw i.forEach(a=>{if(a.source?.sourcePath){const f=c.get(a.source.sourcePath)||[];f.push(a.message),c.set(a.source.sourcePath,f)}}),c.forEach((a,f)=>{C.error(`Error(s) in ${$.path(f)}:`),a.forEach(g=>{C.error(` - ${g}`)}),C.break()}),new d(`Token validation failed. See ${$.info("https://docs.sugarcube.sh/w3c-token-format")} for help`)}return{trees:t,resolved:o}}l(B,"validateTokens");async function pe(e="./src/styles"){const n=await L({message:"Save CSS to",placeholder:e,validate:l(t=>{if(t.trim().replace(/['"]/g,"").length===0)return"Output directory cannot be empty"},"validate")});return S(n)&&process.exit(0),n}l(pe,"promptCSSOutputDirectory");async function Ne(e="./src/design-tokens"){const n=await L({message:"Save tokens to",placeholder:e,validate:l(t=>{if(!t.trim())return"Please provide a path"},"validate")});return S(n)&&process.exit(0),n}l(Ne,"promptTokensDirectory");async function Pe(e){const t=e.filter(s=>s.type==="tokens"&&s.files[0]?.path.includes("starter-kits")).map(s=>({label:s.name,value:s.name})),o=await W({message:"Which starter kit?",options:t});return S(o)&&process.exit(0),o}l(Pe,"promptStarterKit");async function ue(e="./src/components"){const n=await L({message:"Save components to",placeholder:e,validate:l(t=>{if(t.trim().replace(/['"]/g,"").length===0)return"Output directory cannot be empty"},"validate")});return S(n)&&process.exit(0),n}l(ue,"promptComponentDirectory");async function fe(e=!0){const n=[{label:"React",value:"react",hint:".tsx"},{label:"Astro",value:"astro",hint:".astro"},{label:"Nunjucks",value:"nunjucks",hint:".njk"}];e&&n.push({label:"Skip",value:"skip",hint:"continue without components"});const t=await W({message:"Build with",options:n});return S(t)&&process.exit(0),t}l(fe,"promptComponentFramework");async function me(e,n){const t=e.filter(s=>s.type==="component"&&s.frameworks?.includes(n)),o=await Z({message:"Select components to add",options:t.map(s=>({label:s.name,value:s.name,hint:s.description})),required:!0});return S(o)&&process.exit(0),o}l(me,"promptComponentSelectionFiltered");async function Re(){const n=await W({message:"Set up tokens with",options:[{label:"Starter kit",value:"starter"},{label:"Own tokens",value:"existing"}]});return S(n)&&process.exit(0),n}l(Re,"promptTokenSetup");async function ne(e,n=!1){const t=await U({message:e,initialValue:n});return(!t||S(t))&&process.exit(0),!0}l(ne,"confirmOverwrite");async function Oe(){const e=await U({message:"Install CUBE CSS?",active:"Yes",inactive:"No",initialValue:!0});return S(e)&&process.exit(0),e}l(Oe,"promptInstallCube");async function Ae(){const e=await L({message:"Path to tokens?",placeholder:"./src/design-tokens",validate:l(n=>{if(n.trim().replace(/['"]/g,"").length===0)return"Path cannot be empty"},"validate")});return S(e)&&process.exit(0),e}l(Ae,"promptExistingTokensPath");async function Me(){const e=await U({message:"Generate separate CSS file for each token file?"});return S(e)&&process.exit(0),e}l(Me,"promptSeparateCSSFiles");async function Le(){const e=await W({message:"How would you like to organize your tokens?",options:[{value:"simple",label:"Simple (all tokens in one place)"},{value:"collections",label:"Collections (group related tokens together)"}]});return S(e)&&process.exit(0),e}l(Le,"promptCollectionOrganization");async function de(e,n=!1){if(e.length===0)return null;const t=await Z({message:`Select files for your ${n?"first":"next"} collection (including any theme files)`,options:e.map(o=>({label:o,value:o}))});return S(t)&&process.exit(0),t.length===0?null:t}l(de,"promptFilesForCollection");async function se(e){const n=e.map(o=>m.dirname(o).split(m.sep)).reduce((o,s)=>o?o.filter((i,c)=>i===s[c]):s).pop(),t=await L({message:"Name this collection:",placeholder:n||"collection"});return S(t)&&process.exit(0),t}l(se,"promptCollectionName");async function Ue(e){if(e.length<=1)return null;const n=await U({message:"Are any of these theme files?",initialValue:!1});if(S(n)&&process.exit(0),!n)return null;const t=[];let o=[...e];for(;o.length>0;){const s=await Z({message:t.length===0?"Select files for first theme:":"Select files for another theme (or Enter to finish):",options:o.map(c=>({label:c,value:c}))});if(S(s)&&process.exit(0),s.length===0)break;const i=await L({message:"Name this theme:",placeholder:"light"});if(S(i)&&process.exit(0),t.push({name:i,files:s}),o=o.filter(c=>!s.includes(c)),o.length>0){const c=await U({message:"Create another theme?",initialValue:!0});if(S(c)&&process.exit(0),!c)break}}return t.length>0?t:null}l(Ue,"promptIdentifyThemeFiles");async function ze(){const e=await U({message:"Allow sugarcube to manage your CSS index file?",initialValue:!1});return S(e)&&process.exit(0),e}l(ze,"promptManageIndex");async function ge(e,n,t){const{output:o}=await $e(e,n,t),s=o.map(i=>i.path).filter(i=>T(i));if(s.length>0){const i=s.map(c=>` - ${c}`).join(`
4
+ `)}`);if(s.validation.length>0||s.flatten.length>0||s.resolution.length>0){C.break();const i=[...s.flatten,...s.validation,...s.resolution],c=new Map;throw i.forEach(a=>{if(a.source?.sourcePath){const f=c.get(a.source.sourcePath)||[];f.push(a.message),c.set(a.source.sourcePath,f)}}),c.forEach((a,f)=>{C.error(`Error(s) in ${$.path(f)}:`),a.forEach(g=>{C.error(` - ${g}`)}),C.break()}),new d(`Token validation failed. See ${$.info("https://docs.sugarcube.sh/w3c-token-format")} for help`)}return{trees:t,resolved:o}}l(B,"validateTokens");async function ue(e="./src/styles"){const n=await L({message:"Save CSS to",placeholder:e,validate:l(t=>{if(t.trim().replace(/['"]/g,"").length===0)return"Output directory cannot be empty"},"validate")});return S(n)&&process.exit(0),n}l(ue,"promptCSSOutputDirectory");async function Re(e="./src/design-tokens"){const n=await L({message:"Save tokens to",placeholder:e,validate:l(t=>{if(!t.trim())return"Please provide a path"},"validate")});return S(n)&&process.exit(0),n}l(Re,"promptTokensDirectory");async function Oe(e){const t=e.filter(s=>s.type==="tokens"&&s.files[0]?.path.includes("starter-kits")).map(s=>({label:s.name,value:s.name})),o=await W({message:"Which starter kit?",options:t});return S(o)&&process.exit(0),o}l(Oe,"promptStarterKit");async function fe(e="./src/components"){const n=await L({message:"Save components to",placeholder:e,validate:l(t=>{if(t.trim().replace(/['"]/g,"").length===0)return"Output directory cannot be empty"},"validate")});return S(n)&&process.exit(0),n}l(fe,"promptComponentDirectory");async function me(e=!0){const n=[{label:"React",value:"react",hint:".tsx"},{label:"Astro",value:"astro",hint:".astro"},{label:"Nunjucks",value:"nunjucks",hint:".njk"}];e&&n.push({label:"Skip",value:"skip",hint:"continue without components"});const t=await W({message:"Build with",options:n});return S(t)&&process.exit(0),t}l(me,"promptComponentFramework");async function de(e,n){const t=e.filter(s=>s.type==="component"&&s.frameworks?.includes(n)),o=await Z({message:"Select components to add",options:t.map(s=>({label:s.name,value:s.name,hint:s.description})),required:!0});return S(o)&&process.exit(0),o}l(de,"promptComponentSelectionFiltered");async function Ae(){const n=await W({message:"Set up tokens with",options:[{label:"Starter kit",value:"starter"},{label:"Own tokens",value:"existing"}]});return S(n)&&process.exit(0),n}l(Ae,"promptTokenSetup");async function ne(e,n=!1){const t=await U({message:e,initialValue:n});return(!t||S(t))&&process.exit(0),!0}l(ne,"confirmOverwrite");async function Me(){const e=await U({message:"Install CUBE CSS?",active:"Yes",inactive:"No",initialValue:!0});return S(e)&&process.exit(0),e}l(Me,"promptInstallCube");async function Le(){const e=await L({message:"Path to tokens?",placeholder:"./src/design-tokens",validate:l(n=>{if(n.trim().replace(/['"]/g,"").length===0)return"Path cannot be empty"},"validate")});return S(e)&&process.exit(0),e}l(Le,"promptExistingTokensPath");async function Ue(){const e=await U({message:"Generate separate CSS file for each token file?"});return S(e)&&process.exit(0),e}l(Ue,"promptSeparateCSSFiles");async function ze(){const e=await W({message:"How would you like to organize your tokens?",options:[{value:"simple",label:"Simple (all tokens in one place)"},{value:"collections",label:"Collections (group related tokens together)"}]});return S(e)&&process.exit(0),e}l(ze,"promptCollectionOrganization");async function ge(e,n=!1){if(e.length===0)return null;const t=await Z({message:`Select files for your ${n?"first":"next"} collection (including any theme files)`,options:e.map(o=>({label:o,value:o}))});return S(t)&&process.exit(0),t.length===0?null:t}l(ge,"promptFilesForCollection");async function se(e){const n=e.map(o=>m.dirname(o).split(m.sep)).reduce((o,s)=>o?o.filter((i,c)=>i===s[c]):s).pop(),t=await L({message:"Name this collection:",placeholder:n||"collection"});return S(t)&&process.exit(0),t}l(se,"promptCollectionName");async function Be(e){if(e.length<=1)return null;const n=await U({message:"Are any of these theme files?",initialValue:!1});if(S(n)&&process.exit(0),!n)return null;const t=[];let o=[...e];for(;o.length>0;){const s=await Z({message:t.length===0?"Select files for first theme:":"Select files for another theme (or Enter to finish):",options:o.map(c=>({label:c,value:c}))});if(S(s)&&process.exit(0),s.length===0)break;const i=await L({message:"Name this theme:",placeholder:"light"});if(S(i)&&process.exit(0),t.push({name:i,files:s}),o=o.filter(c=>!s.includes(c)),o.length>0){const c=await U({message:"Create another theme?",initialValue:!0});if(S(c)&&process.exit(0),!c)break}}return t.length>0?t:null}l(Be,"promptIdentifyThemeFiles");async function Ge(){const e=await U({message:"Allow sugarcube to manage your CSS index file?",initialValue:!1});return S(e)&&process.exit(0),e}l(Ge,"promptManageIndex");async function he(e,n,t){const{output:o}=await Fe(e,n,t),s=o.map(i=>i.path).filter(i=>T(i));if(s.length>0){const i=s.map(c=>` - ${c}`).join(`
5
5
  `);v.warn(u.yellow(`The following files will be regenerated:
6
- ${u.dim(i)}`)),await ne("Continue?",!0)}try{const i=je(t);return await Fe(o,!0,i)}catch(i){throw new d(`Failed to write CSS files: ${i instanceof Error?i.message:"Unknown error"}`)}}l(ge,"generateAndWriteCSSVars");function H(e){const t=[...e.config?[e.config]:[],...e.tokens||[],...e.generated].map(s=>m.relative(process.cwd(),s)),o=ee();o.start(`Generating ${t.length} files:`),o.stop(`Generated ${t.length} files:`),t.forEach(s=>{C.log(` - ${s}`)}),C.break()}l(H,"showSummary");const oe=w.enum(["react","astro","nunjucks"]),he=w.object({path:w.string(),type:w.string()}),Be=he.extend({framework:oe});w.object({themes:w.record(w.string(),w.array(w.string())).optional()}).strict();const Ge=w.object({name:w.string(),type:w.string(),description:w.string().optional(),frameworks:w.array(w.string()).optional(),files:w.array(w.union([Be,he])),tokens:w.record(w.object({type:w.string(),mapping:w.string()})).optional(),dependencies:w.record(oe,w.array(w.string())).optional(),registryDependencies:w.record(oe,w.array(w.string())).optional(),tokenDependencies:w.array(w.string()).optional()}),We=w.array(Ge),Je=w.object({content:w.string()}),we=process.env.REGISTRY_URL??"https://registry.sugarcube.sh/registry";async function ye(e){try{const n=await Ie(e);if(!n.ok){if(n.status===401)throw new d(`Registry access denied: Authentication required
6
+ ${u.dim(i)}`)),await ne("Continue?",!0)}try{const i=Ee(t);return await Ie(o,!0,i)}catch(i){throw new d(`Failed to write CSS files: ${i instanceof Error?i.message:"Unknown error"}`)}}l(he,"generateAndWriteCSSVars");function H(e){const t=[...e.config?[e.config]:[],...e.tokens||[],...e.generated].map(s=>m.relative(process.cwd(),s)),o=ee();o.start(`Generating ${t.length} files:`),o.stop(`Generated ${t.length} files:`),t.forEach(s=>{C.log(` - ${s}`)}),C.break()}l(H,"showSummary");const oe=w.enum(["react","astro","nunjucks"]),we=w.object({path:w.string(),type:w.string()}),We=we.extend({framework:oe});w.object({themes:w.record(w.string(),w.array(w.string())).optional()}).strict();const Je=w.object({name:w.string(),type:w.string(),description:w.string().optional(),frameworks:w.array(w.string()).optional(),files:w.array(w.union([We,we])),tokens:w.record(w.object({type:w.string(),mapping:w.string()})).optional(),dependencies:w.record(oe,w.array(w.string())).optional(),registryDependencies:w.record(oe,w.array(w.string())).optional(),tokenDependencies:w.array(w.string()).optional()}),Ve=w.array(Je),_e=w.object({content:w.string()}),ye=process.env.REGISTRY_URL??"https://registry.sugarcube.sh/registry";async function ke(e){try{const n=await Te(e);if(!n.ok){if(n.status===401)throw new d(`Registry access denied: Authentication required
7
7
  URL: ${$.info(e)}`);if(n.status===403)throw new d(`Registry access denied: Invalid or missing token
8
8
  URL: ${$.info(e)}`);if(n.status===404)throw new d(`Registry resource not found
9
9
  URL: ${$.info(e)}`);const t=await n.json().catch(()=>null),o=t&&typeof t=="object"&&"error"in t?t.error:n.statusText;throw new d(`Registry request failed: ${o}
10
10
  URL: ${$.info(e)}`)}return n.json()}catch(n){throw n instanceof d?n:new d(`Failed to connect to registry
11
11
  URL: ${$.info(e)}
12
- Check your internet connection`)}}l(ye,"fetchRegistry");async function A(){const e=`${we}/index.json`,n=await ye(e);try{return We.parse(n)}catch{throw new d(`Invalid registry data received
12
+ Check your internet connection`)}}l(ke,"fetchRegistry");async function A(){const e=`${ye}/index.json`,n=await ke(e);try{return Ve.parse(n)}catch{throw new d(`Invalid registry data received
13
13
  URL: ${$.info(e)}`)}}l(A,"getRegistryIndex");async function Q({type:e,name:n,framework:t}){const o=await A(),s=o.find(a=>a.type===e&&a.name===n);if(!s){const a=o.filter(f=>f.type===e).map(f=>f.name);throw new d(`${e} '${$.info(n)}' not found in registry
14
- Available ${e}s: ${a.join(", ")}`)}let i=s.files;e==="component"&&t&&(i=s.files.filter(a=>"framework"in a&&a.framework===t));const c=await Promise.all(i.map(async a=>{const f=`${we}/${a.path}.json`,g=await ye(f);try{const y=Je.parse(g);return{path:a.path,type:a.type,framework:"framework"in a?a.framework:void 0,content:y.content}}catch{throw new d(`Invalid file content received
15
- File: ${$.info(a.path)}`)}}));return{item:s,files:c.filter(Boolean)}}l(Q,"getRegistryFiles");async function Ve(e,n,t){const o=[],s=new Set;async function i(c){if(s.has(c))return;s.add(c);const a=e.find(g=>g.name===c);if(!a){const g=e.filter(y=>y.type==="component").map(y=>y.name).join(", ");throw new d(`Component '${c}' not found in registry
16
- Available components: ${g}`)}const f=a.registryDependencies?.[t]||[];for(const g of f)await i(g);o.push(a)}l(i,"resolveComponent");for(const c of n)await i(c);return o}l(Ve,"resolveTree");const _e=l(async(e,n,t)=>{const o=await Q({type:"tokens",name:e});if(!o.files[0])throw new d(`Starter kit '${e}' does not contain any token files`);const s=m.resolve(process.cwd(),t),i=o.files.find(r=>m.basename(r.path)==="config.json");let c={};if(i)try{c=JSON.parse(i.content)}catch{console.warn(`Warning: Could not parse config.json for starter kit '${e}'`)}const a=o.files.filter(r=>m.basename(r.path)!=="config.json").map(r=>({path:m.join(s,m.basename(r.path)),content:r.content})),f=Object.fromEntries(a.map(r=>[m.basename(r.path),m.relative(process.cwd(),r.path)])),g={};if(c.themes)for(const[r,p]of Object.entries(c.themes))g[r]=p.map(h=>{const k=f[h];if(!k)throw new d(`Theme file '${h}' not found in starter kit '${e}'`);return k});const y={tokens:{source:a.map(r=>m.relative(process.cwd(),r.path)),type:"starter-kit",...Object.keys(g).length>0&&{themes:g}},options:{fluid:{min:320,max:1200}},output:{directories:{tokens:m.relative(process.cwd(),s),css:n},css:{separate:!1,manageIndex:!0}}};try{const r=ae(y),{trees:p,resolved:h}=await B(r,{type:"memory",data:Object.fromEntries(a.map(k=>[k.path,{collection:"default",content:k.content}]))});return{config:r,tokens:a.map(k=>m.basename(k.path)),trees:p,resolved:h,tokenFiles:a,tokensDir:s}}catch(r){throw r}},"initializeFromStarterKit"),qe=l(async e=>{const n=await Ae(),t=await le("**/*.json",{cwd:n,absolute:!0});if(t.length===0)throw new d(`No JSON files found in ${n}`);const o=[];for(const r of t)try{const p=await ce(r,"utf-8");JSON.parse(p),o.push(r)}catch{v.warn(u.yellow(`Skipping invalid JSON file: ${r}`));continue}if(o.length===0)throw new d(`No valid JSON files found in ${n}
17
- Ensure files contain valid JSON`);const s=o.map(r=>m.relative(process.cwd(),r)),i=m.resolve(process.cwd(),n),c=await pe();let a=await Le();const f=new Map;s.forEach(r=>{const p=m.basename(r),h=f.get(p)||[];f.set(p,[...h,r])});const g=Array.from(f.entries()).filter(([r,p])=>p.length>1).map(([r,p])=>({name:r,files:p}));if(a==="simple"&&g.length>0){const r=g.map(({name:p,files:h})=>{const k=h.map(b=>` - ${b}`).join(`
14
+ Available ${e}s: ${a.join(", ")}`)}let i=s.files;e==="component"&&t&&(i=s.files.filter(a=>"framework"in a&&a.framework===t));const c=await Promise.all(i.map(async a=>{const f=`${ye}/${a.path}.json`,g=await ke(f);try{const y=_e.parse(g);return{path:a.path,type:a.type,framework:"framework"in a?a.framework:void 0,content:y.content}}catch{throw new d(`Invalid file content received
15
+ File: ${$.info(a.path)}`)}}));return{item:s,files:c.filter(Boolean)}}l(Q,"getRegistryFiles");async function qe(e,n,t){const o=[],s=new Set;async function i(c){if(s.has(c))return;s.add(c);const a=e.find(g=>g.name===c);if(!a){const g=e.filter(y=>y.type==="component").map(y=>y.name).join(", ");throw new d(`Component '${c}' not found in registry
16
+ Available components: ${g}`)}const f=a.registryDependencies?.[t]||[];for(const g of f)await i(g);o.push(a)}l(i,"resolveComponent");for(const c of n)await i(c);return o}l(qe,"resolveTree");const Ke=l(async(e,n,t)=>{const o=await Q({type:"tokens",name:e});if(!o.files[0])throw new d(`Starter kit '${e}' does not contain any token files`);const s=m.resolve(process.cwd(),t),i=o.files.find(r=>m.basename(r.path)==="config.json");let c={};if(i)try{c=JSON.parse(i.content)}catch{console.warn(`Warning: Could not parse config.json for starter kit '${e}'`)}const a=o.files.filter(r=>m.basename(r.path)!=="config.json").map(r=>({path:m.join(s,m.basename(r.path)),content:r.content})),f=Object.fromEntries(a.map(r=>[m.basename(r.path),m.relative(process.cwd(),r.path)])),g={};if(c.themes)for(const[r,p]of Object.entries(c.themes))g[r]=p.map(h=>{const k=f[h];if(!k)throw new d(`Theme file '${h}' not found in starter kit '${e}'`);return k});const y={tokens:{source:a.map(r=>m.relative(process.cwd(),r.path)),type:"starter-kit",...Object.keys(g).length>0&&{themes:g}},options:{fluid:{min:320,max:1200}},output:{directories:{tokens:m.relative(process.cwd(),s),css:n},css:{separate:!1,manageIndex:!0}}};try{const r=ce(y),{trees:p,resolved:h}=await B(r,{type:"memory",data:Object.fromEntries(a.map(k=>[k.path,{collection:"default",content:k.content}]))});return{config:r,tokens:a.map(k=>m.basename(k.path)),trees:p,resolved:h,tokenFiles:a,tokensDir:s}}catch(r){throw r}},"initializeFromStarterKit"),Ye=l(async e=>{const n=await Le(),t=await pe("**/*.json",{cwd:n,absolute:!0});if(t.length===0)throw new d(`No JSON files found in ${n}`);const o=[];for(const r of t)try{const p=await le(r,"utf-8");JSON.parse(p),o.push(r)}catch{v.warn(u.yellow(`Skipping invalid JSON file: ${r}`));continue}if(o.length===0)throw new d(`No valid JSON files found in ${n}
17
+ Ensure files contain valid JSON`);const s=o.map(r=>m.relative(process.cwd(),r)),i=m.resolve(process.cwd(),n),c=await ue();let a=await ze();const f=new Map;s.forEach(r=>{const p=m.basename(r),h=f.get(p)||[];f.set(p,[...h,r])});const g=Array.from(f.entries()).filter(([r,p])=>p.length>1).map(([r,p])=>({name:r,files:p}));if(a==="simple"&&g.length>0){const r=g.map(({name:p,files:h})=>{const k=h.map(b=>` - ${b}`).join(`
18
18
  `);return`
19
19
  ${p} appears in:
20
20
  ${u.dim(k)}`}).join(`
21
21
  `);v.warn(u.yellow(`Simple organization cannot have duplicate filenames:
22
- ${r}`)),v.message(u.cyan("Switching to collections to help organize these files...")),a="collections"}if(a==="simple"){const r={type:"custom",source:s};e.tokens=r,v.message(u.cyan("Token organization complete"))}else{const r={},p=new Set;let h=[...s],k=!0;for(;h.length>0;){let b=await de(h,k);if(!b){v.message(u.cyan("No files selected, skipping collection creation..."));break}let x=await se(b);if(!x){v.message(u.cyan("No collection name provided, skipping collection creation..."));break}let D=!1;for(;!D;)try{if(p.has(x)){v.warn(u.yellow(`Collection name "${x}" is already in use.`));const F=await se(b);if(!F){v.message(u.cyan("No collection name provided, skipping collection creation..."));break}x=F;continue}const j={type:"custom",source:b};r[x]=j;const N=await Ue(b);if(N&&N.length>0){const F=N.flatMap(I=>I.files),E=new Set;let O=!1;for(const I of N){if(E.has(I.name)){v.warn(u.yellow(`Theme name "${I.name}" is already used in this collection.`)),v.message(u.cyan("Starting theme selection over to avoid conflicts...")),O=!0;break}E.add(I.name)}if(O)continue;j.source=b.filter(I=>!F.includes(I)),j.themes=N.reduce((I,K)=>({...I,[K.name]:K.files}),{})}const R=new Map;j.source.forEach(F=>{const E=m.basename(F),O=R.get(E)||[];R.set(E,[...O,F])});const ie=Array.from(R.entries()).filter(([F,E])=>E.length>1).map(([F,E])=>({name:F,files:E}));if(ie.length>0){const F=ie.map(({name:I,files:K})=>{const ve=K.map(Se=>` - ${Se}`).join(`
22
+ ${r}`)),v.message(u.cyan("Switching to collections to help organize these files...")),a="collections"}if(a==="simple"){const r={type:"custom",source:s};e.tokens=r,v.message(u.cyan("Token organization complete"))}else{const r={},p=new Set;let h=[...s],k=!0;for(;h.length>0;){let b=await ge(h,k);if(!b){v.message(u.cyan("No files selected, skipping collection creation..."));break}let x=await se(b);if(!x){v.message(u.cyan("No collection name provided, skipping collection creation..."));break}let D=!1;for(;!D;)try{if(p.has(x)){v.warn(u.yellow(`Collection name "${x}" is already in use.`));const F=await se(b);if(!F){v.message(u.cyan("No collection name provided, skipping collection creation..."));break}x=F;continue}const j={type:"custom",source:b};r[x]=j;const N=await Be(b);if(N&&N.length>0){const F=N.flatMap(I=>I.files),E=new Set;let O=!1;for(const I of N){if(E.has(I.name)){v.warn(u.yellow(`Theme name "${I.name}" is already used in this collection.`)),v.message(u.cyan("Starting theme selection over to avoid conflicts...")),O=!0;break}E.add(I.name)}if(O)continue;j.source=b.filter(I=>!F.includes(I)),j.themes=N.reduce((I,K)=>({...I,[K.name]:K.files}),{})}const R=new Map;j.source.forEach(F=>{const E=m.basename(F),O=R.get(E)||[];R.set(E,[...O,F])});const ae=Array.from(R.entries()).filter(([F,E])=>E.length>1).map(([F,E])=>({name:F,files:E}));if(ae.length>0){const F=ae.map(({name:I,files:K})=>{const Se=K.map(xe=>` - ${xe}`).join(`
23
23
  `);return`
24
24
  ${I} appears in:
25
- ${u.dim(ve)}`}).join(`
25
+ ${u.dim(Se)}`}).join(`
26
26
  `);v.warn(u.yellow(`Found duplicate filenames in collection "${x}":
27
- ${F}`)),v.message(u.cyan("Please either split these files into different collections or mark some as theme files."));const E=await de(h,k);if(!E){v.message(u.cyan("No files selected, skipping collection creation..."));break}b=E;const O=await se(b);if(!O){v.message(u.cyan("No collection name provided, skipping collection creation..."));break}x=O;continue}D=!0,p.add(x)}catch(j){if(j instanceof d){v.error(`${j.message}`),v.message(u.cyan("Let's try again..."));continue}throw j}if(!D){v.message(u.cyan("Skipping collection creation..."));break}h=h.filter(j=>!b.includes(j)),h.length>0&&v.message(u.cyan(`Remaining files to organize: ${h.length}`)),k=!1}h.length>0?v.warn(u.yellow(`Warning: ${h.length} files were not assigned to any collection`)):v.message(u.cyan("Token organization complete")),e.tokens=r}const y=s.length>1?await Me():!1;e.output={directories:{tokens:m.relative(process.cwd(),i),css:c},css:{separate:y,manageIndex:!0}},e.options={fluid:{min:320,max:1200}};try{if(typeof e.tokens=="object"&&!Array.isArray(e.tokens)){const b=e.tokens,x=new Set;for(const[D,j]of Object.entries(b)){if(x.has(D))throw new d(`Configuration Error: Duplicate collection name "${D}". Collection names must be unique.`);if(x.add(D),j.themes){const N=new Set;for(const R of Object.keys(j.themes)){if(N.has(R))throw new d(`Configuration Error: Duplicate theme name "${R}" in collection "${D}". Theme names must be unique within a collection.`);N.add(R)}}}}const r=await Promise.all(s.map(async b=>({path:m.resolve(process.cwd(),b),content:await ce(m.resolve(process.cwd(),b),"utf-8")}))),p=ae(e),{trees:h,resolved:k}=await B(p);return{config:p,tokens:s,trees:h,resolved:k,tokenPath:n,tokensDir:i,tokenFiles:r}}catch(r){throw r}},"initializeFromExistingTokens");async function Ke(){if(T("sugarcube.config.json")){const e=await W({message:"A sugarcube.config.json already exists in this project",options:[{label:"Overwrite existing config (start from scratch)",value:"overwrite"},{label:"Cancel initialization",value:"cancel"}]});return S(e)&&process.exit(0),{shouldProceed:e==="overwrite"}}return{shouldProceed:!0}}l(Ke,"preflightInit");async function re(e){const n={$schema:"https://sugarcube.style/schema.json",...e};try{const t=JSON.stringify(n,null,2);await _("sugarcube.config.json",t)}catch(t){const o=t instanceof Error?`: ${t.message}`:"";throw new d(`Failed to write config file${o}`)}}l(re,"writeConfig");const Ye=l(()=>{J(u.inverse(" Welcome to sugarcube. The toolkit for seriously sweet front ends "))},"welcome");async function He(e,{withFallback:n=!1}={}){const t=await Te({programmatic:!0,cwd:e});if(t?.startsWith("yarn@"))return"yarn";if(t?.startsWith("pnpm@"))return"pnpm";if(t==="bun")return"bun";if(!n)return t?.split("@")[0]??"npm";const o=process.env.npm_config_user_agent||"";return o.startsWith("yarn")?"yarn":o.startsWith("pnpm")?"pnpm":o.startsWith("bun")?"bun":"npm"}l(He,"getPackageManager");async function Qe(e,n){const t=await He(n,{withFallback:!0}),o=t==="npm"?"install":"add";try{await De(t,[o,...e],{cwd:n})}catch{const i=`Failed to install dependencies using ${t}.
27
+ ${F}`)),v.message(u.cyan("Please either split these files into different collections or mark some as theme files."));const E=await ge(h,k);if(!E){v.message(u.cyan("No files selected, skipping collection creation..."));break}b=E;const O=await se(b);if(!O){v.message(u.cyan("No collection name provided, skipping collection creation..."));break}x=O;continue}D=!0,p.add(x)}catch(j){if(j instanceof d){v.error(`${j.message}`),v.message(u.cyan("Let's try again..."));continue}throw j}if(!D){v.message(u.cyan("Skipping collection creation..."));break}h=h.filter(j=>!b.includes(j)),h.length>0&&v.message(u.cyan(`Remaining files to organize: ${h.length}`)),k=!1}h.length>0?v.warn(u.yellow(`Warning: ${h.length} files were not assigned to any collection`)):v.message(u.cyan("Token organization complete")),e.tokens=r}const y=s.length>1?await Ue():!1;e.output={directories:{tokens:m.relative(process.cwd(),i),css:c},css:{separate:y,manageIndex:!0}},e.options={fluid:{min:320,max:1200}};try{if(typeof e.tokens=="object"&&!Array.isArray(e.tokens)){const b=e.tokens,x=new Set;for(const[D,j]of Object.entries(b)){if(x.has(D))throw new d(`Configuration Error: Duplicate collection name "${D}". Collection names must be unique.`);if(x.add(D),j.themes){const N=new Set;for(const R of Object.keys(j.themes)){if(N.has(R))throw new d(`Configuration Error: Duplicate theme name "${R}" in collection "${D}". Theme names must be unique within a collection.`);N.add(R)}}}}const r=await Promise.all(s.map(async b=>({path:m.resolve(process.cwd(),b),content:await le(m.resolve(process.cwd(),b),"utf-8")}))),p=ce(e),{trees:h,resolved:k}=await B(p);return{config:p,tokens:s,trees:h,resolved:k,tokenPath:n,tokensDir:i,tokenFiles:r}}catch(r){throw r}},"initializeFromExistingTokens");async function He(){if(T("sugarcube.config.json")){const e=await W({message:"A sugarcube.config.json already exists in this project",options:[{label:"Overwrite existing config (start from scratch)",value:"overwrite"},{label:"Cancel initialization",value:"cancel"}]});return S(e)&&process.exit(0),{shouldProceed:e==="overwrite"}}return{shouldProceed:!0}}l(He,"preflightInit");async function re(e){const n={$schema:"https://sugarcube.style/schema.json",...e};try{const t=JSON.stringify(n,null,2);await _("sugarcube.config.json",t)}catch(t){const o=t instanceof Error?`: ${t.message}`:"";throw new d(`Failed to write config file${o}`)}}l(re,"writeConfig");const Qe=l(()=>{J(u.inverse(" Welcome to sugarcube. The toolkit for seriously sweet front ends "))},"welcome");async function Xe(e,{withFallback:n=!1}={}){const t=await Pe({programmatic:!0,cwd:e});if(t?.startsWith("yarn@"))return"yarn";if(t?.startsWith("pnpm@"))return"pnpm";if(t==="bun")return"bun";if(!n)return t?.split("@")[0]??"npm";const o=process.env.npm_config_user_agent||"";return o.startsWith("yarn")?"yarn":o.startsWith("pnpm")?"pnpm":o.startsWith("bun")?"bun":"npm"}l(Xe,"getPackageManager");async function Ze(e,n){const t=await Xe(n,{withFallback:!0}),o=t==="npm"?"install":"add";try{await Ne(t,[o,...e],{cwd:n})}catch{const i=`Failed to install dependencies using ${t}.
28
28
 
29
29
  This might be because you're using 'npx' with a pnpm project. Try:
30
30
  pnpm dlx @sugarcube-org/cli components
@@ -33,10 +33,10 @@ Or use the appropriate package runner for your project:
33
33
  npm: npx @sugarcube-org/cli components
34
34
  pnpm: pnpm dlx @sugarcube-org/cli components
35
35
  yarn: yarn dlx @sugarcube-org/cli components
36
- bun: bunx @sugarcube-org/cli components`;throw new Error(i)}}l(Qe,"installDependencies");async function ke({registryIndex:e,selectedComponents:n,componentType:t,componentsOutputDirectory:o,cssOutputDirectory:s}){const i=[],c=new Set;await P(o,{recursive:!0});const a=m.join(s,"global","variables");await P(m.join(s,"global"),{recursive:!0}),await P(a,{recursive:!0});const f=await Ve(e,n,t);for(const g of f){const y=await Q({type:"component",name:g.name,framework:t});for(const p of y.files)if(p)try{if(p.path.endsWith(".variables.css")){const h=m.join(a,`${g.name}.variables.css`);await _(h,p.content),i.push(h)}else{const h=m.join(o,g.name);await P(h,{recursive:!0});const k=m.join(h,m.basename(p.path));await _(k,p.content),i.push(k)}}catch(h){const k=h instanceof Error?`: ${h.message}`:"";throw new d(`Failed to write component file for "${g.name}"${k}`)}(g.dependencies?.[t]||[]).forEach(p=>c.add(p))}if(c.size>0)try{await Qe(Array.from(c),process.cwd())}catch(g){const y=g instanceof Error?`: ${g.message}`:"";throw new d(`Failed to install component dependencies${y}`)}return{createdFiles:i,npmDependencies:c}}l(ke,"installComponents");async function Xe(e){const n=[],t=m.resolve(process.cwd(),e);await P(t,{recursive:!0});const s=(await A()).filter(i=>i.type==="cube").map(i=>i.name);for(const i of s){const c=await Q({type:"cube",name:i});for(const a of c.files){if(!a)continue;const f=a.path.replace(/^styles\//,""),g=m.join(t,f),y=m.dirname(g);try{await P(y,{recursive:!0}),await _(g,a.content),n.push(g)}catch(r){const p=r instanceof Error?`: ${r.message}`:"";throw new d(`Failed to write CUBE module "${i}"${p}`)}}}return n}l(Xe,"installCUBE");function Ze(e){switch(e){case"react":return"tsx";case"astro":return"astro";case"nunjucks":return"njk";default:return"tsx"}}l(Ze,"getExtension");function be({components:e,componentType:n,componentsOutputDirectory:t}){return e.filter(o=>{const s=m.join(t,o,`${o}.${Ze(n)}`);return T(s)})}l(be,"checkComponentExists");async function X({cssOutputDirectory:e,files:n}){try{await Ee({cssOutputDirectory:e,files:n})}catch(t){const o=t instanceof Error?`: ${t.message}`:"";throw new d(`Failed to manage CSS index file ${o}`)}}l(X,"manageCSSIndexCLI");function q(e){if(C.break(),e instanceof d){const n=e.message.split(`
36
+ bun: bunx @sugarcube-org/cli components`;throw new Error(i)}}l(Ze,"installDependencies");async function be({registryIndex:e,selectedComponents:n,componentType:t,componentsOutputDirectory:o,cssOutputDirectory:s}){const i=[],c=new Set;await P(o,{recursive:!0});const a=m.join(s,"global","variables");await P(m.join(s,"global"),{recursive:!0}),await P(a,{recursive:!0});const f=await qe(e,n,t);for(const g of f){const y=await Q({type:"component",name:g.name,framework:t});for(const p of y.files)if(p)try{if(p.path.endsWith(".variables.css")){const h=m.join(a,`${g.name}.variables.css`);await _(h,p.content),i.push(h)}else{const h=m.join(o,g.name);await P(h,{recursive:!0});const k=m.join(h,m.basename(p.path));await _(k,p.content),i.push(k)}}catch(h){const k=h instanceof Error?`: ${h.message}`:"";throw new d(`Failed to write component file for "${g.name}"${k}`)}(g.dependencies?.[t]||[]).forEach(p=>c.add(p))}if(c.size>0)try{await Ze(Array.from(c),process.cwd())}catch(g){const y=g instanceof Error?`: ${g.message}`:"";throw new d(`Failed to install component dependencies${y}`)}return{createdFiles:i,npmDependencies:c}}l(be,"installComponents");async function et(e){const n=[],t=m.resolve(process.cwd(),e);await P(t,{recursive:!0});const s=(await A()).filter(i=>i.type==="cube").map(i=>i.name);for(const i of s){const c=await Q({type:"cube",name:i});for(const a of c.files){if(!a)continue;const f=a.path.replace(/^styles\//,""),g=m.join(t,f),y=m.dirname(g);try{await P(y,{recursive:!0}),await _(g,a.content),n.push(g)}catch(r){const p=r instanceof Error?`: ${r.message}`:"";throw new d(`Failed to write CUBE module "${i}"${p}`)}}}return n}l(et,"installCUBE");function tt(e){switch(e){case"react":return"tsx";case"astro":return"astro";case"nunjucks":return"njk";default:return"tsx"}}l(tt,"getExtension");function ve({components:e,componentType:n,componentsOutputDirectory:t}){return e.filter(o=>{const s=m.join(t,o,`${o}.${tt(n)}`);return T(s)})}l(ve,"checkComponentExists");async function X({cssOutputDirectory:e,files:n}){try{await De({cssOutputDirectory:e,files:n})}catch(t){const o=t instanceof Error?`: ${t.message}`:"";throw new d(`Failed to manage CSS index file ${o}`)}}l(X,"manageCSSIndexCLI");function q(e){if(C.break(),e instanceof d){const n=e.message.split(`
37
37
  `);n.length>1?(C.error(n[0]),C.break(),n.slice(1).forEach(t=>{C.error(` ${t.trim()}`)})):C.error(e.message),process.env.DEBUG&&e.cause&&C.info(`
38
38
  Caused by:`,e.cause)}else C.error(`An unexpected error occurred: ${e instanceof Error?e.message:String(e)}
39
39
  If this issue persists, please report it: ${u.cyanBright("https://github.com/sugarcube-org/sugarcube/issues")}`),process.env.DEBUG&&C.info(`
40
- Error details:`,e);C.break(),process.exit(0)}l(q,"handleError");const et=new M().name("init").description("Initialize a new project").action(async()=>{try{Ye(),(await Ke()).shouldProceed||process.exit(0),V("Step 1. Set up tokens");const n=await Re();let t;switch(n){case"starter":const r=await A();r||(Y("Failed to fetch starter kit list"),process.exit(1));const p=await Pe(r),h=await pe(),k=await Ne();try{t=await _e(p,h,k)}catch(b){Y(`Failed to initialize starter kit: ${b instanceof Error?b.message:"Unknown error"}`),process.exit(1)}break;case"existing":t=await qe({});break}V("Step 2. Add style system");const o=await Oe();V("Step 3. Add components");const s=await fe();let i=[];if(s!=="skip"){const r=await A();r||(Y("Failed to fetch component list"),process.exit(1));const p=await me(r,s),h=await ue(),k=await be({components:p,componentType:s,componentsOutputDirectory:h});if(k.length>0){const b=k.join(", ");await ne(`The following components already exist and will be overwritten: ${b}. Continue?`,!1)}if(p.length>0){const b=ee();b.start("Installing components...");try{const{createdFiles:x,npmDependencies:D}=await ke({registryIndex:r,selectedComponents:p,componentType:s,componentsOutputDirectory:h,cssOutputDirectory:t.config.output.directories.css});i=x,b.stop("Components installed successfully")}catch(x){throw b.stop("Installation failed"),x}}}V("Step 4. Set up index.css");const c=await ze();t.config.output.css.manageIndex=c,V("Step 5. Generating files");try{if(await te.mkdir(t.tokensDir,{recursive:!0}),await te.mkdir(t.config.output.directories.css,{recursive:!0}),n==="starter"){if(!t.tokenFiles||t.tokenFiles.length===0)throw new d("Failed to generate token content for starter kit");for(const r of t.tokenFiles)await te.writeFile(r.path,r.content)}}catch(r){const p=r instanceof Error?`: ${r.message}`:"";throw new d(`Failed to create project files${p}`)}let a=[];const{trees:f,resolved:g}=await B(t.config);a=await ge(f,g,t.config);let y=[];o&&(y=await Xe(t.config.output.directories.css)),t.config.output.css.manageIndex&&await X({cssOutputDirectory:t.config.output.directories.css,files:[...a.map(r=>r.path),...i.filter(r=>r.endsWith(".css")),...y]}),await re(t.config),H({config:"sugarcube.config.json",tokens:n==="starter"?t.tokens:[],generated:[...a.map(r=>r.path),...y,...i,...t.config.output.css.manageIndex?["index.css"]:[]]}),z(u.greenBright("Success! Project initialized \u2728"))}catch(e){q(e)}}),tt=new M().name("generate").description("Generate CSS from your design tokens").option("--force","Skip confirmation when deleting stale files").action(async e=>{try{if(J(u.inverse(" Generate CSS variables from your design tokens ")),!T("sugarcube.config.json"))throw new d("This command requires a sugarcube project. Run 'npx make-sugarcube init' first.");const n=await G(),{trees:t,resolved:o}=await B(n),s=await ge(t,o,n);n.output.css.manageIndex&&await X({cssOutputDirectory:n.output.directories.css,files:s.map(i=>i.path)}),H({generated:[...s.map(i=>i.path),...n.output.css.manageIndex?["index.css"]:[]]}),z(u.greenBright("Success! CSS variables generated successfully. \u2728"))}catch(n){q(n)}}),nt=new M().name("validate").description("Validate design token files").argument("[paths...]","Token files or directories to validate (e.g., tokens.json or ./tokens)").action(async e=>{try{if(J(u.inverse(" Validate design tokens ")),T("sugarcube.config.json")&&!e.length){const s=await G();await B(s),z(u.greenBright("All tokens are valid \u2728"));return}if(!e.length)throw new d("No paths specified. Please provide files/directories to validate, or run this in a Sugarcube project directory.");const n=e.map(s=>m.normalize(s));for(const s of n)if(!T(s))throw new d(`Path not found: ${s}
41
- Please check that the specified files or directories exist`);const t=await le(n.map(s=>s.endsWith(".json")?s:m.join(s,"**/*.json")));if(t.length===0)throw new d(`No JSON files found in the specified paths
42
- Please ensure the paths contain .json files`);const o=T("sugarcube.config.json")?await G():{output:{directories:{tokens:".",css:"."},css:{separate:!1}}};await B({...o,tokens:{type:"custom",source:t.map(s=>m.relative(process.cwd(),s))}}),z(u.greenBright("All tokens are valid \u2728"))}catch(n){q(n)}}),st=new M().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, astro, nunjucks)").option("-s, --silent","Suppress logs and prompts").action(async(e,n)=>{try{if(n.silent||J(u.inverse(" Add components ")),!T("sugarcube.config.json"))throw new d("This command requires a sugarcube project. Run 'npx make-sugarcube init' first.");let t=await G(),o,s=[],i;if(e.length>0){if(!n.framework)throw new d("Framework must be specified in non-interactive mode (--framework)");const f=["react","astro","nunjucks"];if(!f.includes(n.framework))throw new d(`Invalid framework. Must be one of: ${f.join(", ")}`);if(i=n.framework,s=e,!t.output.directories.components)throw new d("Components directory must be configured in non-interactive mode. Please run without arguments first.");o=m.resolve(process.cwd(),t.output.directories.components)}else{i=await fe(!1);const f=await A();if(f||(Y("Failed to fetch component list"),process.exit(1)),s=await me(f,i),t.output.directories.components)o=m.resolve(process.cwd(),t.output.directories.components);else{const g=await ue();o=m.resolve(process.cwd(),g),t.output.directories.components=m.relative(process.cwd(),o),await re(t)}}const c=await be({components:s,componentType:i,componentsOutputDirectory:o});if(c.length>0&&!n.silent){const f=c.join(", ");await ne(`The following components already exist and will be overwritten: ${f}. Continue?`,!1)}let a;n.silent||(a=ee(),a.start("Installing components..."));try{const f=await A(),{createdFiles:g,npmDependencies:y}=await ke({registryIndex:f,selectedComponents:s,componentType:i,componentsOutputDirectory:o,cssOutputDirectory:t.output.directories.css});t.output.css.manageIndex&&await X({cssOutputDirectory:t.output.directories.css,files:g}),n.silent||(a?.stop("Components installed successfully"),H({generated:g}),z(u.greenBright("Success! Components installed \u2728")))}catch(f){throw n.silent||a?.stop("Installation failed"),f}}catch(t){q(t)}}),ot=new M().name("cube").description("Add CUBE CSS to your project").option("-s, --silent","Suppress logs and prompts").action(async e=>{const n=[];try{if(!T("sugarcube.config.json"))throw new d("This command requires a sugarcube project. Run 'npx make-sugarcube init' first.");e.silent||J(u.inverse(" Add CUBE CSS "));const t=await G(),o=m.resolve(process.cwd(),t.output.directories.css);try{await P(o,{recursive:!0})}catch(c){const a=c instanceof Error?`: ${c.message}`:"";throw new d(`Failed to create output directory${a}`)}const i=(await A()).filter(c=>c.type==="cube").map(c=>c.name);for(const c of i){const a=await Q({type:"cube",name:c});for(const f of a.files){if(!f)continue;const g=f.path.replace(/^styles\//,""),y=m.join(o,g),r=m.dirname(y);try{await P(r,{recursive:!0}),await _(y,f.content),n.push(y)}catch(p){const h=p instanceof Error?`: ${p.message}`:"";throw new d(`Failed to write CUBE CSS file ${y}${h}`)}}}t.output.css.manageIndex&&await X({cssOutputDirectory:o,files:n}),await re(t),!e.silent&&n.length>0&&(H({generated:n}),z(u.greenBright("Success! CUBE CSS added successfully. \u2728")))}catch(t){q(t)}});var rt="@sugarcube-org/cli",it="0.0.0-alpha.8",at={access:"public"},ct="A CLI for scaffolding sugarcube applications",lt="AGPL-3.0",pt="Mark Tomlinson",ut={type:"git",url:"https://github.com/sugarcube-org/sugarcube"},ft={url:"https://github.com/sugarcube-org/sugarcube/issues"},mt=["cli","design-system","components","CUBE CSS","react","sugarcube"],dt=["dist","README.md","LICENSE.md"],gt="module",ht={sugarcube:"./dist/index.mjs"},wt={build:"pkgroll --minify",dev:"cross-env REGISTRY_URL=http://localhost:8787/registry tsx src/index.ts",test:"vitest","type-check":"tsc --noEmit",start:"cross-env REGISTRY_URL=https://sugarcube-registry.mark-tomlinson3.workers.dev/registry tsx src/index.ts",prepublishOnly:"pnpm build"},yt={"@antfu/ni":"^23.3.0","@clack/prompts":"^0.9.1","@sugarcube-org/core":"workspace:*",commander:"^12.1.0","cross-env":"^7.0.3",execa:"^9.5.2","fast-glob":"^3.3.2","fs-extra":"^11.2.0","lucide-react":"^0.468.0","node-fetch":"^3.3.0",picocolors:"^1.1.1",prompts:"^2.4.2",zod:"^3.23.8"},kt={"@types/fs-extra":"^11.0.4","@types/prompts":"^2.4.9",pkgroll:"^2.5.1",tsx:"^4.19.2"},bt={name:rt,version:it,publishConfig:at,description:ct,license:lt,author:pt,repository:ut,bugs:ft,keywords:mt,files:dt,type:gt,bin:ht,scripts:wt,dependencies:yt,devDependencies:kt};process.on("SIGINT",()=>process.exit(0)),process.on("SIGTERM",()=>process.exit(0));async function vt(){const e=new M().name("sugarcube").description("CLI for scaffolding sugarcube applications").version(bt.version,"-v, --version","display the version number");e.addCommand(et).addCommand(tt).addCommand(nt).addCommand(st).addCommand(ot),e.parse()}l(vt,"main"),vt();
40
+ Error details:`,e);C.break(),process.exit(0)}l(q,"handleError");const nt=new M().name("init").description("Initialize a new project").action(async()=>{try{Qe(),(await He()).shouldProceed||process.exit(0),V("Step 1. Set up tokens");const n=await Ae();let t;switch(n){case"starter":const r=await A();r||(Y("Failed to fetch starter kit list"),process.exit(1));const p=await Oe(r),h=await ue(),k=await Re();try{t=await Ke(p,h,k)}catch(b){Y(`Failed to initialize starter kit: ${b instanceof Error?b.message:"Unknown error"}`),process.exit(1)}break;case"existing":t=await Ye({});break}V("Step 2. Add style system");const o=await Me();V("Step 3. Add components");const s=await me();let i=[];if(s!=="skip"){const r=await A();r||(Y("Failed to fetch component list"),process.exit(1));const p=await de(r,s),h=await fe(),k=await ve({components:p,componentType:s,componentsOutputDirectory:h});if(k.length>0){const b=k.join(", ");await ne(`The following components already exist and will be overwritten: ${b}. Continue?`,!1)}if(p.length>0){const b=ee();b.start("Installing components...");try{const{createdFiles:x,npmDependencies:D}=await be({registryIndex:r,selectedComponents:p,componentType:s,componentsOutputDirectory:h,cssOutputDirectory:t.config.output.directories.css});i=x,b.stop("Components installed successfully")}catch(x){throw b.stop("Installation failed"),x}}}V("Step 4. Set up index.css");const c=await Ge();t.config.output.css.manageIndex=c,V("Step 5. Generating files");try{if(await te.mkdir(t.tokensDir,{recursive:!0}),await te.mkdir(t.config.output.directories.css,{recursive:!0}),n==="starter"){if(!t.tokenFiles||t.tokenFiles.length===0)throw new d("Failed to generate token content for starter kit");for(const r of t.tokenFiles)await te.writeFile(r.path,r.content)}}catch(r){const p=r instanceof Error?`: ${r.message}`:"";throw new d(`Failed to create project files${p}`)}let a=[];const{trees:f,resolved:g}=await B(t.config);a=await he(f,g,t.config);let y=[];o&&(y=await et(t.config.output.directories.css)),t.config.output.css.manageIndex&&await X({cssOutputDirectory:t.config.output.directories.css,files:[...a.map(r=>r.path),...i.filter(r=>r.endsWith(".css")),...y]}),await re(t.config),H({config:"sugarcube.config.json",tokens:n==="starter"?t.tokens:[],generated:[...a.map(r=>r.path),...y,...i,...t.config.output.css.manageIndex?["index.css"]:[]]}),z(u.greenBright("Success! Project initialized \u2728"))}catch(e){q(e)}}),st=new M().name("generate").description("Generate CSS from your design tokens").option("--force","Skip confirmation when deleting stale files").action(async e=>{try{if(J(u.inverse(" Generate CSS variables from your design tokens ")),!T("sugarcube.config.json"))throw new d("This command requires a sugarcube project. Run 'npx make-sugarcube init' first.");const n=await G(),{trees:t,resolved:o}=await B(n),s=await he(t,o,n);n.output.css.manageIndex&&await X({cssOutputDirectory:n.output.directories.css,files:s.map(i=>i.path)}),H({generated:[...s.map(i=>i.path),...n.output.css.manageIndex?["index.css"]:[]]}),z(u.greenBright("Success! CSS variables generated successfully. \u2728"))}catch(n){q(n)}}),ot=new M().name("validate").description("Validate design token files").argument("[paths...]","Token files or directories to validate (e.g., tokens.json or ./tokens)").action(async e=>{try{if(J(u.inverse(" Validate design tokens ")),T("sugarcube.config.json")&&!e.length){const s=await G();await B(s),z(u.greenBright("All tokens are valid \u2728"));return}if(!e.length)throw new d("No paths specified. Please provide files/directories to validate, or run this in a Sugarcube project directory.");const n=e.map(s=>m.normalize(s));for(const s of n)if(!T(s))throw new d(`Path not found: ${s}
41
+ Please check that the specified files or directories exist`);const t=await pe(n.map(s=>s.endsWith(".json")?s:m.join(s,"**/*.json")));if(t.length===0)throw new d(`No JSON files found in the specified paths
42
+ Please ensure the paths contain .json files`);const o=T("sugarcube.config.json")?await G():{output:{directories:{tokens:".",css:"."},css:{separate:!1}}};await B({...o,tokens:{type:"custom",source:t.map(s=>m.relative(process.cwd(),s))}}),z(u.greenBright("All tokens are valid \u2728"))}catch(n){q(n)}}),rt=new M().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, astro, nunjucks)").option("-s, --silent","Suppress logs and prompts").action(async(e,n)=>{try{if(n.silent||J(u.inverse(" Add components ")),!T("sugarcube.config.json"))throw new d("This command requires a sugarcube project. Run 'npx make-sugarcube init' first.");let t=await G(),o,s=[],i;if(e.length>0){if(!n.framework)throw new d("Framework must be specified in non-interactive mode (--framework)");const f=["react","astro","nunjucks"];if(!f.includes(n.framework))throw new d(`Invalid framework. Must be one of: ${f.join(", ")}`);if(i=n.framework,s=e,!t.output.directories.components)throw new d("Components directory must be configured in non-interactive mode. Please run without arguments first.");o=m.resolve(process.cwd(),t.output.directories.components)}else{i=await me(!1);const f=await A();if(f||(Y("Failed to fetch component list"),process.exit(1)),s=await de(f,i),t.output.directories.components)o=m.resolve(process.cwd(),t.output.directories.components);else{const g=await fe();o=m.resolve(process.cwd(),g),t.output.directories.components=m.relative(process.cwd(),o),await re(t)}}const c=await ve({components:s,componentType:i,componentsOutputDirectory:o});if(c.length>0&&!n.silent){const f=c.join(", ");await ne(`The following components already exist and will be overwritten: ${f}. Continue?`,!1)}let a;n.silent||(a=ee(),a.start("Installing components..."));try{const f=await A(),{createdFiles:g,npmDependencies:y}=await be({registryIndex:f,selectedComponents:s,componentType:i,componentsOutputDirectory:o,cssOutputDirectory:t.output.directories.css});t.output.css.manageIndex&&await X({cssOutputDirectory:t.output.directories.css,files:g}),n.silent||(a?.stop("Components installed successfully"),H({generated:g}),z(u.greenBright("Success! Components installed \u2728")))}catch(f){throw n.silent||a?.stop("Installation failed"),f}}catch(t){q(t)}}),it=new M().name("cube").description("Add CUBE CSS to your project").option("-s, --silent","Suppress logs and prompts").action(async e=>{const n=[];try{if(!T("sugarcube.config.json"))throw new d("This command requires a sugarcube project. Run 'npx make-sugarcube init' first.");e.silent||J(u.inverse(" Add CUBE CSS "));const t=await G(),o=m.resolve(process.cwd(),t.output.directories.css);try{await P(o,{recursive:!0})}catch(c){const a=c instanceof Error?`: ${c.message}`:"";throw new d(`Failed to create output directory${a}`)}const i=(await A()).filter(c=>c.type==="cube").map(c=>c.name);for(const c of i){const a=await Q({type:"cube",name:c});for(const f of a.files){if(!f)continue;const g=f.path.replace(/^styles\//,""),y=m.join(o,g),r=m.dirname(y);try{await P(r,{recursive:!0}),await _(y,f.content),n.push(y)}catch(p){const h=p instanceof Error?`: ${p.message}`:"";throw new d(`Failed to write CUBE CSS file ${y}${h}`)}}}t.output.css.manageIndex&&await X({cssOutputDirectory:o,files:n}),await re(t),!e.silent&&n.length>0&&(H({generated:n}),z(u.greenBright("Success! CUBE CSS added successfully. \u2728")))}catch(t){q(t)}});var at="@sugarcube-org/cli",ct="0.0.0-alpha.9",lt={access:"public"},pt="A CLI for scaffolding sugarcube applications",ut="AGPL-3.0",ft="Mark Tomlinson",mt={type:"git",url:"https://github.com/sugarcube-org/sugarcube"},dt={url:"https://github.com/sugarcube-org/sugarcube/issues"},gt=["cli","design-system","components","CUBE CSS","react","sugarcube"],ht=["dist","README.md","LICENSE.md"],wt="module",yt="./dist/index.mjs",ie={".":"./dist/index.mjs"},kt={sugarcube:"./dist/index.mjs"},bt={build:"pkgroll --minify",dev:"cross-env REGISTRY_URL=http://localhost:8787/registry tsx src/index.ts",test:"vitest","type-check":"tsc --noEmit",start:"cross-env REGISTRY_URL=https://sugarcube-registry.mark-tomlinson3.workers.dev/registry tsx src/index.ts",prepublishOnly:"pnpm build"},vt={"@antfu/ni":"^23.3.0","@clack/prompts":"^0.9.1","@sugarcube-org/core":"workspace:*",commander:"^12.1.0","cross-env":"^7.0.3",execa:"^9.5.2","fast-glob":"^3.3.2","fs-extra":"^11.2.0","lucide-react":"^0.468.0","node-fetch":"^3.3.0",picocolors:"^1.1.1",prompts:"^2.4.2",zod:"^3.23.8"},St={"@types/fs-extra":"^11.0.4","@types/prompts":"^2.4.9",pkgroll:"^2.5.1",tsx:"^4.19.2"},xt={name:at,version:ct,publishConfig:lt,description:pt,license:ut,author:ft,repository:mt,bugs:dt,keywords:gt,files:ht,type:wt,main:yt,exports:ie,bin:kt,scripts:bt,dependencies:vt,devDependencies:St};process.on("SIGINT",()=>process.exit(0)),process.on("SIGTERM",()=>process.exit(0));async function Ct(){const e=new M().name("sugarcube").description("CLI for scaffolding sugarcube applications").version(xt.version,"-v, --version","display the version number");e.addCommand(nt).addCommand(st).addCommand(ot).addCommand(rt).addCommand(it),e.parse()}l(Ct,"main"),Ct()});export default $t();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@sugarcube-org/cli",
3
- "version": "0.0.0-alpha.8",
3
+ "version": "0.0.0-alpha.9",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
@@ -28,6 +28,10 @@
28
28
  "LICENSE.md"
29
29
  ],
30
30
  "type": "module",
31
+ "main": "./dist/index.mjs",
32
+ "exports": {
33
+ ".": "./dist/index.mjs"
34
+ },
31
35
  "bin": {
32
36
  "sugarcube": "./dist/index.mjs"
33
37
  },