@sugarcube-org/cli 0.0.0-alpha.6 → 0.0.0-alpha.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.mjs +29 -46
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,46 +1,30 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var
|
|
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:
|
|
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){
|
|
5
|
-
`);
|
|
6
|
-
${
|
|
7
|
-
URL: ${
|
|
8
|
-
URL: ${
|
|
9
|
-
URL: ${
|
|
10
|
-
URL: ${
|
|
11
|
-
URL: ${
|
|
12
|
-
Check your internet connection`)}}
|
|
13
|
-
URL: ${
|
|
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
|
|
15
|
-
File: ${
|
|
16
|
-
Available components: ${
|
|
17
|
-
Ensure files contain valid JSON`);const s=o.map(m
|
|
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(`
|
|
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
|
|
7
|
+
URL: ${$.info(e)}`);if(n.status===403)throw new d(`Registry access denied: Invalid or missing token
|
|
8
|
+
URL: ${$.info(e)}`);if(n.status===404)throw new d(`Registry resource not found
|
|
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
|
+
URL: ${$.info(e)}`)}return n.json()}catch(n){throw n instanceof d?n:new d(`Failed to connect to registry
|
|
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
|
|
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(`
|
|
18
18
|
`);return`
|
|
19
|
-
${
|
|
20
|
-
${
|
|
21
|
-
`);
|
|
22
|
-
${
|
|
19
|
+
${p} appears in:
|
|
20
|
+
${u.dim(k)}`}).join(`
|
|
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(`
|
|
23
23
|
`);return`
|
|
24
24
|
${I} appears in:
|
|
25
|
-
${
|
|
26
|
-
`);
|
|
27
|
-
${F}`)),
|
|
28
|
-
`);throw new d(`Invalid configuration:
|
|
29
|
-
${o}
|
|
30
|
-
See ${v.info("https://docs.sugarcube.sh/configuration")} for help.`)}if(typeof t.data.tokens=="object")for(const[o,s]of Object.entries(t.data.tokens)){if(!s.source?.length)continue;const i=new Map;s.source.forEach(a=>{const r=h.basename(a),u=i.get(r)||[];i.set(r,[...u,a])});const c=Array.from(i.entries()).filter(([a,r])=>r.length>1).map(([a,r])=>({name:a,files:r}));if(c.length>0){const a=c.map(({name:r,files:u})=>{const f=u.map(m=>` - ${m}`).join(`
|
|
31
|
-
`);return`
|
|
32
|
-
${r} appears in:
|
|
33
|
-
${f}`}).join(`
|
|
34
|
-
`);throw new d(`Duplicate filenames found in collection "${o}":
|
|
35
|
-
${a}
|
|
36
|
-
|
|
37
|
-
To fix this:
|
|
38
|
-
1. Use unique filenames for source files
|
|
39
|
-
2. Or move some files to a different collection
|
|
40
|
-
3. Or mark some files as theme files
|
|
41
|
-
See ${v.info("https://docs.sugarcube.sh")} to learn more.`)}}return t.data}p(_,"validateAndLoadConfig");async function ae(e){const n={$schema:"https://sugarcube.style/schema.json",...e};try{const t=JSON.stringify(n,null,2);await A("sugarcube.config.json",t)}catch(t){const o=t instanceof Error?`: ${t.message}`:"";throw new d(`Failed to write config file${o}`)}}p(ae,"writeConfig");function Ke(e){const n=e.split("/"),t=n.findIndex(s=>s==="variables");if(t===-1||t===n.length-1)return"default";const o=n[t+1];return!o||o.endsWith(".css")?"default":o}p(Ke,"getCollectionFromPath");function ke(e,n){if(e.includes("/variables/")){const t=Ke(e),o=n.variables.get(t)??[];o.push(e),n.variables.set(t,o)}else e.startsWith("global/")?n.global.push(e):e.startsWith("compositions/")?n.compositions.push(e):e.startsWith("utilities/")&&n.utilities.push(e)}p(ke,"groupFile");async function Ye(e,n,t="merge"){const o={variables:new Map,global:[],compositions:[],utilities:[]},s=h.join(n,"index.css");t==="merge"&&D(s)&&(await le(s,"utf-8")).split(`
|
|
42
|
-
`).filter(f=>f.trim().startsWith("@import")).map(f=>f.match(/'([^']+)'/)?.[1]).filter(f=>f!==void 0).forEach(f=>ke(f,o)),e.filter(r=>r.endsWith(".css")).forEach(r=>{const u=h.relative(n,r).replace(/\\/g,"/");ke(u,o)});const i=["reset.css","fonts.css","global-styles.css"];o.global.sort((r,u)=>{const f=i.findIndex(w=>r.endsWith(w)),m=i.findIndex(w=>u.endsWith(w));return f-m});const c=Array.from(o.variables.entries()).sort(([r,u],[f,m])=>r==="default"?-1:f==="default"?1:r.localeCompare(f)).flatMap(([r,u])=>u.sort((f,m)=>f.endsWith("tokens.variables.css")?-1:m.endsWith("tokens.variables.css")?1:f.localeCompare(m))),a=[...new Set([...c,...o.global,...o.compositions.sort(),...o.utilities.sort()])].map(r=>`@import '${r}';`);return await A(s,a.join(`
|
|
43
|
-
`)),s}p(Ye,"generateIndexFile");const Ze=p(()=>{B(g.inverse(" Welcome to sugarcube. The toolkit for seriously sweet front ends "))},"welcome");async function He(e,{withFallback:n=!1}={}){const t=await De({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"}p(He,"getPackageManager");async function Qe(e,n){const t=await He(n,{withFallback:!0}),o=t==="npm"?"install":"add";try{await Ie(t,[o,...e],{cwd:n})}catch{const i=`Failed to install dependencies using ${t}.
|
|
25
|
+
${u.dim(ve)}`}).join(`
|
|
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}.
|
|
44
28
|
|
|
45
29
|
This might be because you're using 'npx' with a pnpm project. Try:
|
|
46
30
|
pnpm dlx @sugarcube-org/cli components
|
|
@@ -49,11 +33,10 @@ Or use the appropriate package runner for your project:
|
|
|
49
33
|
npm: npx @sugarcube-org/cli components
|
|
50
34
|
pnpm: pnpm dlx @sugarcube-org/cli components
|
|
51
35
|
yarn: yarn dlx @sugarcube-org/cli components
|
|
52
|
-
bun: bunx @sugarcube-org/cli components`;throw new Error(i)}}
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
Please
|
|
59
|
-
Please ensure the paths contain .json files`);const o=D("sugarcube.config.json")?await _():{output:{directories:{tokens:".",css:"."},css:{separate:!1}}};await G({...o,tokens:{type:"custom",source:t.map(s=>h.relative(process.cwd(),s))}}),L(g.greenBright("All tokens are valid \u2728"))}catch(n){J(n)}}),ot=new R().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||B(g.inverse(" Add components ")),!D("sugarcube.config.json"))throw new d("This command requires a sugarcube project. Run 'npx make-sugarcube init' first.");let t=await _(),o,s=[],i;if(e.length>0){if(!n.framework)throw new d("Framework must be specified in non-interactive mode (--framework)");const r=["react","astro","nunjucks"];if(!r.includes(n.framework))throw new d(`Invalid framework. Must be one of: ${r.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=h.resolve(process.cwd(),t.output.directories.components)}else{i=await de(!1);const r=await W();if(r||(ne("Failed to fetch component list"),process.exit(1)),s=await ge(r,i),t.output.directories.components)o=h.resolve(process.cwd(),t.output.directories.components);else{const u=await me();o=h.resolve(process.cwd(),u),t.output.directories.components=h.relative(process.cwd(),o),await ae(t)}}const c=await xe({components:s,componentType:i,componentsOutputDirectory:o});if(c.length>0&&!n.silent){const r=c.join(", ");await K(`The following components already exist and will be overwritten: ${r}. Continue?`,!1)}let a;n.silent||(a=te(),a.start("Installing components..."));try{const r=await W(),{createdFiles:u,npmDependencies:f}=await ve({registryIndex:r,selectedComponents:s,componentType:i,componentsOutputDirectory:o,cssOutputDirectory:t.output.directories.css});await H({mode:"merge",cssOutputDirectory:t.output.directories.css,files:u,config:t}),n.silent||(a?.stop("Components installed successfully"),Y({generated:u}),L(g.greenBright("Success! Components installed \u2728")))}catch(r){throw n.silent||a?.stop("Installation failed"),r}}catch(t){J(t)}}),rt=new R().name("cube").description("Add CUBE CSS to your project").option("-s, --silent","Suppress logs and prompts").action(async e=>{const n=[];try{if(!D("sugarcube.config.json"))throw new d("This command requires a sugarcube project. Run 'npx make-sugarcube init' first.");e.silent||B(g.inverse(" Add CUBE CSS "));const t=await _(),o=h.resolve(process.cwd(),t.output.directories.css);try{await T(o,{recursive:!0})}catch(c){const a=c instanceof Error?`: ${c.message}`:"";throw new d(`Failed to create output directory${a}`)}const i=(await W()).filter(c=>c.type==="cube").map(c=>c.name);for(const c of i){const a=await Z({type:"cube",name:c});for(const r of a.files){if(!r)continue;const u=r.path.replace(/^styles\//,""),f=h.join(o,u),m=h.dirname(f);try{await T(m,{recursive:!0}),await A(f,r.content),n.push(f)}catch(w){const y=w instanceof Error?`: ${w.message}`:"";throw new d(`Failed to write CUBE CSS file ${f}${y}`)}}}await H({mode:"merge",cssOutputDirectory:o,files:n,config:t}),await ae(t),!e.silent&&n.length>0&&(Y({generated:n}),L(g.greenBright("Success! CUBE CSS added successfully. \u2728")))}catch(t){J(t)}});var it="@sugarcube-org/cli",at="0.0.0-alpha.6",ct={access:"restricted"},lt="A CLI for scaffolding sugarcube applications",ut="UNLICENSED",pt="Mark Tomlinson",ft={type:"git",url:"https://github.com/sugarcube-org/sugarcube"},mt={url:"https://github.com/sugarcube-org/sugarcube/issues"},dt=["cli","design-system","components","CUBE CSS","react","sugarcube"],gt=["dist","README.md","LICENSE.md"],ht="module",wt={sugarcube:"./dist/index.mjs"},yt={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 up @sugarcube-org/core --filter @sugarcube-org/cli && pnpm build"},bt={"@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"},vt={name:it,version:at,publishConfig:ct,description:lt,license:ut,author:pt,repository:ft,bugs:mt,keywords:dt,files:gt,type:ht,bin:wt,scripts:yt,dependencies:bt,devDependencies:kt};process.on("SIGINT",()=>process.exit(0)),process.on("SIGTERM",()=>process.exit(0));async function xt(){const e=new R().name("sugarcube").description("CLI for scaffolding sugarcube applications").version(vt.version,"-v, --version","display the version number");e.addCommand(tt).addCommand(nt).addCommand(st).addCommand(ot).addCommand(rt),e.parse()}p(xt,"main"),xt();
|
|
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(`
|
|
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
|
+
Caused by:`,e.cause)}else C.error(`An unexpected error occurred: ${e instanceof Error?e.message:String(e)}
|
|
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();
|
package/package.json
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sugarcube-org/cli",
|
|
3
|
-
"version": "0.0.0-alpha.
|
|
3
|
+
"version": "0.0.0-alpha.8",
|
|
4
4
|
"publishConfig": {
|
|
5
|
-
"access": "
|
|
5
|
+
"access": "public"
|
|
6
6
|
},
|
|
7
7
|
"description": "A CLI for scaffolding sugarcube applications",
|
|
8
|
-
"license": "
|
|
8
|
+
"license": "AGPL-3.0",
|
|
9
9
|
"author": "Mark Tomlinson",
|
|
10
10
|
"repository": {
|
|
11
11
|
"type": "git",
|