@sugarcube-org/cli 0.0.0-alpha.35 → 0.0.0-alpha.36
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 +69 -90
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var et=Object.defineProperty;var
|
|
2
|
+
var et=Object.defineProperty;var r=(e,t)=>et(e,"name",{value:t,configurable:!0});import{Command as M}from"commander";import{relative as N,join as R,basename as ye,resolve as L,dirname as tt,isAbsolute as nt,normalize as st}from"pathe";import c from"picocolors";import{existsSync as D,readFileSync as Te}from"node:fs";import{z as y}from"zod";import ne,{mkdir as B,writeFile as Q,readFile as Se}from"node:fs/promises";import{execa as rt}from"execa";import{loadAndResolveTokens as ot,findResolverDocument as se,loadInternalConfig as X,isNoConfigError as be,configFileExists as Ee,processAndConvertTokens as re,generateCSSVariables as Ie,writeCSSVariablesToDisk as ve,writeCSSUtilitiesToDisk as ke,fillDefaults as Re,convertConfigToUnoRules as it,DEFAULT_CONFIG as _e}from"@sugarcube-org/core";import{select as at,isCancel as oe,log as ct,multiselect as lt,confirm as ut,cancel as $e}from"@clack/prompts";import{getColumns as dt}from"@clack/core";import{wrapAnsi as ft}from"fast-wrap-ansi";import pt from"is-unicode-supported";import*as Ce from"node:readline";import Ne from"node:readline";import{createLogUpdate as De}from"log-update";import ie,{resolve as mt}from"node:path";import{detect as gt}from"@antfu/ni";import{createGenerator as ht}from"@unocss/core";import{glob as ae}from"tinyglobby";import{getTsconfig as wt}from"get-tsconfig";var yt="0.0.0-alpha.36",Tt={version:yt};const ce="fluid",St="**/*.json",Fe="@sugarcube-org/vite",bt=["node_modules",".git",".next","dist","build"],Et=5,F={INIT:"make-sugarcube init",COMPONENTS:"make-sugarcube components",CUBE:"make-sugarcube cube"},Oe={INITIALIZATION:"https://sugarcube.sh/docs/setup",CONFIGURATION:"https://sugarcube.sh/docs/configuration"},g={PROJECT_REQUIRED:`No sugarcube project detected. Please run ${c.cyan(F.INIT)} first.
|
|
3
3
|
|
|
4
|
-
For more information, visit: ${c.cyan(
|
|
4
|
+
For more information, visit: ${c.cyan(Oe.INITIALIZATION)}`,CONFIG_EXISTS:r(()=>`A sugarcube config file already exists in this project.
|
|
5
5
|
|
|
6
|
-
To start over, remove it and run ${c.cyan(
|
|
6
|
+
To start over, remove it and run ${c.cyan(F.INIT)} again.`,"CONFIG_EXISTS"),PLUGIN_INSTALL_FAILED:r(e=>{const t=e.packageManager==="npm"?"install":"add";return`Failed to install ${e.pluginToInstall} plugin.
|
|
7
7
|
|
|
8
8
|
This is usually a temporary issue. Try these steps:
|
|
9
9
|
|
|
@@ -12,30 +12,30 @@ This is usually a temporary issue. Try these steps:
|
|
|
12
12
|
3. Install manually: ${e.packageManager} ${t} ${e.pluginToInstall}
|
|
13
13
|
|
|
14
14
|
If the problem continues, please open an issue at:
|
|
15
|
-
https://github.com/sugarcube-org/sugarcube/issues`},"PLUGIN_INSTALL_FAILED"),INITIALIZATION_INCOMPLETE:
|
|
15
|
+
https://github.com/sugarcube-org/sugarcube/issues`},"PLUGIN_INSTALL_FAILED"),INITIALIZATION_INCOMPLETE:r(()=>`The initialization process was not completed properly.
|
|
16
16
|
This is an internal error that should not occur.
|
|
17
17
|
Try running the \`init\` command again.
|
|
18
18
|
|
|
19
19
|
If the problem persists, please report this issue at
|
|
20
|
-
https://github.com/sugarcube-org/sugarcube/issues`,"INITIALIZATION_INCOMPLETE"),CONFIG_WRITE_FAILED:
|
|
20
|
+
https://github.com/sugarcube-org/sugarcube/issues`,"INITIALIZATION_INCOMPLETE"),CONFIG_WRITE_FAILED:r(()=>"Failed to write configuration file. Check permissions and try again.","CONFIG_WRITE_FAILED"),DIRECTORY_PATH_EMPTY:r(e=>`${e} cannot be empty. Please provide a valid directory path.`,"DIRECTORY_PATH_EMPTY"),DIRECTORY_PATH_RESERVED:r((e,t)=>`Option: ${e}
|
|
21
21
|
Value: "${t}"
|
|
22
22
|
|
|
23
|
-
${e} cannot be in a reserved directory`,"DIRECTORY_PATH_RESERVED"),KIT_INCOMPLETE:
|
|
23
|
+
${e} cannot be in a reserved directory`,"DIRECTORY_PATH_RESERVED"),KIT_INCOMPLETE:r(()=>`The starter kit appears to be incomplete or corrupted.
|
|
24
24
|
|
|
25
|
-
This is likely a temporary issue. Please try running the command again or choose a different starter kit.`,"KIT_INCOMPLETE"),REGISTRY_AUTH_REQUIRED:
|
|
26
|
-
URL: ${c.cyan(e)}`,"REGISTRY_AUTH_REQUIRED"),REGISTRY_AUTH_INVALID:
|
|
27
|
-
URL: ${c.cyan(e)}`,"REGISTRY_AUTH_INVALID"),REGISTRY_NOT_FOUND:
|
|
28
|
-
URL: ${c.cyan(e)}`,"REGISTRY_NOT_FOUND"),REGISTRY_REQUEST_FAILED:
|
|
29
|
-
URL: ${c.cyan(t)}`,"REGISTRY_REQUEST_FAILED"),REGISTRY_NETWORK_ERROR:
|
|
25
|
+
This is likely a temporary issue. Please try running the command again or choose a different starter kit.`,"KIT_INCOMPLETE"),REGISTRY_AUTH_REQUIRED:r(e=>`Registry access denied: Authentication required
|
|
26
|
+
URL: ${c.cyan(e)}`,"REGISTRY_AUTH_REQUIRED"),REGISTRY_AUTH_INVALID:r(e=>`Registry access denied: Invalid or missing token
|
|
27
|
+
URL: ${c.cyan(e)}`,"REGISTRY_AUTH_INVALID"),REGISTRY_NOT_FOUND:r(e=>`Registry resource not found
|
|
28
|
+
URL: ${c.cyan(e)}`,"REGISTRY_NOT_FOUND"),REGISTRY_REQUEST_FAILED:r((e,t)=>`Registry request failed: ${e}
|
|
29
|
+
URL: ${c.cyan(t)}`,"REGISTRY_REQUEST_FAILED"),REGISTRY_NETWORK_ERROR:r(e=>`Failed to connect to registry
|
|
30
30
|
|
|
31
31
|
URL: ${c.cyan(e)}
|
|
32
32
|
|
|
33
|
-
The registry server may be temporarily unavailable or there might be network connectivity issues. Please try again in a few minutes.`,"REGISTRY_NETWORK_ERROR"),REGISTRY_INVALID_DATA:
|
|
34
|
-
URL: ${c.cyan(e)}`,"REGISTRY_INVALID_DATA"),REGISTRY_ITEM_NOT_FOUND:
|
|
35
|
-
Available ${e==="tokens"?"starter kit":e}s: ${n.join(", ")}`,"REGISTRY_ITEM_NOT_FOUND"),REGISTRY_FILE_INVALID:
|
|
36
|
-
File: ${c.cyan(e)}`,"REGISTRY_FILE_INVALID"),STARTER_KIT_UNAVAILABLE:
|
|
33
|
+
The registry server may be temporarily unavailable or there might be network connectivity issues. Please try again in a few minutes.`,"REGISTRY_NETWORK_ERROR"),REGISTRY_INVALID_DATA:r(e=>`Invalid registry data received
|
|
34
|
+
URL: ${c.cyan(e)}`,"REGISTRY_INVALID_DATA"),REGISTRY_ITEM_NOT_FOUND:r((e,t,n)=>`${e==="tokens"?"Starter kit":e}'${c.cyan(t)} ' not found in registry
|
|
35
|
+
Available ${e==="tokens"?"starter kit":e}s: ${n.join(", ")}`,"REGISTRY_ITEM_NOT_FOUND"),REGISTRY_FILE_INVALID:r(e=>`Invalid file content received
|
|
36
|
+
File: ${c.cyan(e)}`,"REGISTRY_FILE_INVALID"),STARTER_KIT_UNAVAILABLE:r(e=>`Starter kit '${c.cyan(e)}' is currently unavailable.
|
|
37
37
|
|
|
38
|
-
Please try a different starter kit or run the command again in a few minutes.`,"STARTER_KIT_UNAVAILABLE"),RESOLVER_NOT_CONFIGURED:
|
|
38
|
+
Please try a different starter kit or run the command again in a few minutes.`,"STARTER_KIT_UNAVAILABLE"),RESOLVER_NOT_CONFIGURED:r(()=>`No resolver path configured.
|
|
39
39
|
|
|
40
40
|
Add a resolver path to your sugarcube config:
|
|
41
41
|
|
|
@@ -44,131 +44,108 @@ ${c.cyan(`export default {
|
|
|
44
44
|
// ...
|
|
45
45
|
}`)}
|
|
46
46
|
|
|
47
|
-
See ${c.cyan("https://sugarcube.sh/docs/resolver")} for more information.`,"RESOLVER_NOT_CONFIGURED"),RESOLVER_NOT_FOUND:
|
|
47
|
+
See ${c.cyan("https://sugarcube.sh/docs/resolver")} for more information.`,"RESOLVER_NOT_CONFIGURED"),RESOLVER_NOT_FOUND:r(e=>`No resolver document found in ${c.cyan(e)}.
|
|
48
48
|
|
|
49
49
|
A resolver document (*.resolver.json) is required to define how your tokens are loaded.
|
|
50
50
|
|
|
51
|
-
See ${c.cyan("https://sugarcube.sh/docs/resolver")} to learn how to create one.`,"RESOLVER_NOT_FOUND"),RESOLVER_MULTIPLE_FOUND:
|
|
51
|
+
See ${c.cyan("https://sugarcube.sh/docs/resolver")} to learn how to create one.`,"RESOLVER_NOT_FOUND"),RESOLVER_MULTIPLE_FOUND:r(e=>`Multiple resolver documents found:
|
|
52
52
|
${e.map(t=>` - ${c.cyan(t)}`).join(`
|
|
53
53
|
`)}
|
|
54
54
|
|
|
55
|
-
A project should have only one resolver document. Please remove the extras or consolidate them.`,"RESOLVER_MULTIPLE_FOUND"),TOKEN_LOAD_FAILED:
|
|
55
|
+
A project should have only one resolver document. Please remove the extras or consolidate them.`,"RESOLVER_MULTIPLE_FOUND"),TOKEN_LOAD_FAILED:r(e=>`Failed to load token files:
|
|
56
56
|
|
|
57
57
|
${e.join(`
|
|
58
58
|
`)}
|
|
59
59
|
|
|
60
|
-
Please check your token files and try again.`,"TOKEN_LOAD_FAILED"),TOKEN_VALIDATION_FAILED:
|
|
60
|
+
Please check your token files and try again.`,"TOKEN_LOAD_FAILED"),TOKEN_VALIDATION_FAILED:r(e=>{let t=`Token validation failed:
|
|
61
61
|
|
|
62
62
|
`;for(const[n,s]of e){t+=`Error(s) in ${c.cyan(n)}:
|
|
63
|
-
`;for(const
|
|
63
|
+
`;for(const o of s)t+=` - ${o}
|
|
64
64
|
`;t+=`
|
|
65
|
-
`}return t+=`See ${c.cyan("https://sugarcube.sh/docs/design-tokens")} for valid token formats`,t},"TOKEN_VALIDATION_FAILED"),TOKEN_FILE_INVALID_JSON:
|
|
66
|
-
Please check your package manager configuration and try again.`,"DEPENDENCY_INSTALL_FAILED"),VALIDATE_NO_PATH_SPECIFIED:
|
|
65
|
+
`}return t+=`See ${c.cyan("https://sugarcube.sh/docs/design-tokens")} for valid token formats`,t},"TOKEN_VALIDATION_FAILED"),TOKEN_FILE_INVALID_JSON:r(e=>`File ${e}: Invalid JSON syntax`,"TOKEN_FILE_INVALID_JSON"),TOKEN_FILE_INCOMPLETE_JSON:r(e=>`File ${e}: Incomplete JSON file`,"TOKEN_FILE_INCOMPLETE_JSON"),TOKEN_FILE_GENERIC_ERROR:r((e,t)=>`File ${e}: ${t}`,"TOKEN_FILE_GENERIC_ERROR"),DEPENDENCY_INSTALL_FAILED:r(e=>`Failed to install dependencies using ${e}.
|
|
66
|
+
Please check your package manager configuration and try again.`,"DEPENDENCY_INSTALL_FAILED"),VALIDATE_NO_PATH_SPECIFIED:r(()=>`No path specified.
|
|
67
67
|
|
|
68
|
-
Run ${c.cyan("make-sugarcube validate --help")} for more information.`,"VALIDATE_NO_PATH_SPECIFIED"),VALIDATE_PATH_NOT_FOUND:
|
|
68
|
+
Run ${c.cyan("make-sugarcube validate --help")} for more information.`,"VALIDATE_NO_PATH_SPECIFIED"),VALIDATE_PATH_NOT_FOUND:r(e=>`Path not found: ${e}
|
|
69
69
|
|
|
70
|
-
Please check that the specified path exists`,"VALIDATE_PATH_NOT_FOUND"),VALIDATE_NO_TOKEN_FILES:
|
|
70
|
+
Please check that the specified path exists`,"VALIDATE_PATH_NOT_FOUND"),VALIDATE_NO_TOKEN_FILES:r(()=>`No token files found.
|
|
71
71
|
|
|
72
|
-
Please ensure the path contains .json token files`,"VALIDATE_NO_TOKEN_FILES"),COMPONENTS_FRAMEWORK_REQUIRED:
|
|
72
|
+
Please ensure the path contains .json token files`,"VALIDATE_NO_TOKEN_FILES"),COMPONENTS_FRAMEWORK_REQUIRED:r(()=>`Framework is required when specifying components. Use --framework to specify a framework (react, css-only) or run without arguments for interactive mode.
|
|
73
73
|
|
|
74
|
-
See ${c.cyan("https://sugarcube.sh/docs/cli/components")} for more information.`,"COMPONENTS_FRAMEWORK_REQUIRED"),COMPONENTS_INVALID_FRAMEWORK:
|
|
74
|
+
See ${c.cyan("https://sugarcube.sh/docs/cli/components")} for more information.`,"COMPONENTS_FRAMEWORK_REQUIRED"),COMPONENTS_INVALID_FRAMEWORK:r(()=>"Invalid framework. Must be one of: react, css-only.","COMPONENTS_INVALID_FRAMEWORK"),COMPONENTS_DIRECTORY_NOT_CONFIGURED:r(()=>"Components directory must be configured in non-interactive mode. Please run the 'components' command without arguments first.","COMPONENTS_DIRECTORY_NOT_CONFIGURED"),PLUGIN_DETECTED:r(e=>`Plugin detected: ${e}
|
|
75
75
|
|
|
76
76
|
The 'generate' command is for manual generation without plugins. Since you have a plugin installed, use your development server instead:
|
|
77
77
|
|
|
78
78
|
npm run dev # or your framework's dev command
|
|
79
79
|
|
|
80
|
-
The plugin will automatically generate CSS with hot module replacement.`,"PLUGIN_DETECTED"),GENERATE_NO_CONFIG_OR_RESOLVER:
|
|
80
|
+
The plugin will automatically generate CSS with hot module replacement.`,"PLUGIN_DETECTED"),GENERATE_NO_CONFIG_OR_RESOLVER:r(()=>`No design tokens found.
|
|
81
81
|
|
|
82
|
-
|
|
82
|
+
Run ${c.cyan(F.INIT)} to set up your design tokens.
|
|
83
83
|
|
|
84
|
-
Stuck? ${c.cyan("https://sugarcube.sh")}`,"GENERATE_NO_CONFIG_OR_RESOLVER"),GENERATE_MULTIPLE_RESOLVERS_NO_CONFIG:
|
|
84
|
+
Stuck? ${c.cyan("https://sugarcube.sh")}`,"GENERATE_NO_CONFIG_OR_RESOLVER"),GENERATE_MULTIPLE_RESOLVERS_NO_CONFIG:r(e=>`No config file found, but multiple resolver files detected:
|
|
85
85
|
${e.map(t=>` - ${t}`).join(`
|
|
86
86
|
`)}
|
|
87
87
|
|
|
88
88
|
Please either:
|
|
89
|
-
- Create a config file with ${c.cyan(
|
|
90
|
-
- Use --resolver flag to specify which resolver to use`,"GENERATE_MULTIPLE_RESOLVERS_NO_CONFIG")};class p extends Error{static{
|
|
91
|
-
Available components: ${d}`)}const f=l.registryDependencies?.[n]||[];for(const d of f)await i(d);s.push(l)}
|
|
89
|
+
- Create a config file with ${c.cyan(F.INIT)}
|
|
90
|
+
- Use --resolver flag to specify which resolver to use`,"GENERATE_MULTIPLE_RESOLVERS_NO_CONFIG")};class p extends Error{static{r(this,"CLIError")}constructor(t,n){super(t),this.name="CLIError",this.cause=n}}const le=y.enum(["react","web-components","css-only"]),Ae=y.object({path:y.string(),type:y.string()}),It=Ae.extend({framework:le}),vt=y.object({name:y.string(),type:y.string(),description:y.string().optional(),frameworks:y.array(y.string()).optional(),files:y.array(y.union([It,Ae])),tokens:y.record(y.object({type:y.string(),mapping:y.string()})).optional(),dependencies:y.record(le,y.array(y.string())).optional(),registryDependencies:y.record(le,y.array(y.string())).optional(),tokenDependencies:y.array(y.string()).optional()}),kt=y.array(vt),Rt=y.object({content:y.string()}),Pe=process.env.REGISTRY_URL??"https://sugarcube.sh/r";async function Me(e){try{const t=await fetch(e);if(!t.ok){if(t.status===401)throw new p(g.REGISTRY_AUTH_REQUIRED(e));if(t.status===403)throw new p(g.REGISTRY_AUTH_INVALID(e));if(t.status===404)throw new p(g.REGISTRY_NOT_FOUND(e));const n=await t.json().catch(()=>null),s=n&&typeof n=="object"&&"error"in n?String(n.error):t.statusText;throw new p(g.REGISTRY_REQUEST_FAILED(s,e))}return t.json()}catch(t){throw t instanceof p?t:new p(g.REGISTRY_NETWORK_ERROR(e))}}r(Me,"fetchRegistry");async function U(){const e=`${Pe}/index.json`,t=await Me(e);try{return kt.parse(t)}catch{throw new p(g.REGISTRY_INVALID_DATA(e))}}r(U,"getRegistryIndex");async function ue({type:e,name:t,framework:n}){const s=await U(),o=s.find(l=>l.type===e&&l.name===t);if(!o){const l=s.filter(f=>f.type===e).map(f=>f.name);throw new p(g.REGISTRY_ITEM_NOT_FOUND(e,t,l))}let i=o.files;e==="component"&&n&&(i=o.files.filter(l=>"framework"in l&&l.framework===n));const a=await Promise.all(i.map(async l=>{const f=`${Pe}/${l.path}.json`,d=await Me(f);try{const u=Rt.parse(d);return{path:l.path,type:l.type,framework:"framework"in l?l.framework:void 0,content:u.content}}catch{throw new p(g.REGISTRY_FILE_INVALID(l.path))}}));return{item:o,files:a}}r(ue,"getRegistryFiles");async function _t(e){const t=await ue({type:"tokens",name:e});if(!t.files[0])throw new p(g.STARTER_KIT_UNAVAILABLE(e));return t}r(_t,"fetchStarterKit");async function de(e,t,n){const s=[],o=new Set;async function i(a){if(o.has(a))return;o.add(a);const l=e.find(d=>d.name===a);if(!l){const d=e.filter(u=>u.type==="component").map(u=>u.name).join(", ");throw new p(`Component '${a}' not found in registry
|
|
91
|
+
Available components: ${d}`)}const f=l.registryDependencies?.[n]||[];for(const d of f)await i(d);s.push(l)}r(i,"resolveComponent");for(const a of t)await i(a);return s}r(de,"resolveTree");async function $t({selectedComponents:e,componentType:t,componentsOutputDirectory:n}){const s={variableCSS:[],utilityCSS:[],componentFiles:[],componentCSS:[],cubeCSS:[],indexFiles:[]},o=await U(),a=(await de(o,e,t)).map(u=>u.name),l=o.filter(u=>u.type==="component").filter(u=>a.includes(u.name)),f=l.flatMap(u=>u.files.filter(m=>(m.type==="tsx"||m.type==="astro"||m.type==="njk")&&"framework"in m&&m.framework===t).map(m=>N(process.cwd(),R(n,u.name,`${u.name}.${m.type}`))));s.componentFiles=f.filter(u=>D(R(process.cwd(),u)));const d=l.map(u=>{const m=u.name;return N(process.cwd(),R(n,u.name,`${m}.css`))});return s.componentCSS=d.filter(u=>D(R(process.cwd(),u))),s}r($t,"collectComponentOverwriteWarnings");async function Ct({cubeDirectory:e}){const t={variableCSS:[],utilityCSS:[],componentFiles:[],componentCSS:[],cubeCSS:[],indexFiles:[]},s=(await U()).filter(o=>o.type==="cube").flatMap(o=>o.files).map(o=>{const i=o.path.replace(/^styles\//,"");return N(process.cwd(),R(e,i))});return t.cubeCSS=s.filter(o=>D(R(process.cwd(),o))),t}r(Ct,"collectCubeOverwriteWarnings");function Le(e){const t=[];if(e.variableCSS.length>0&&t.push(`CSS variables files:
|
|
92
92
|
${e.variableCSS.map(s=>` - ${s}`).join(`
|
|
93
93
|
`)}`),e.utilityCSS.length>0&&t.push(`CSS utility files:
|
|
94
94
|
${e.utilityCSS.map(s=>` - ${s}`).join(`
|
|
95
95
|
`)}`),e.cubeCSS.length>0&&t.push(`CUBE CSS files:
|
|
96
96
|
${e.cubeCSS.map(s=>` - ${s}`).join(`
|
|
97
97
|
`)}`),e.componentFiles.length>0||e.componentCSS.length>0){const s=[...e.componentFiles,...e.componentCSS];t.push(`Component files:
|
|
98
|
-
${s.map(
|
|
98
|
+
${s.map(o=>` - ${o}`).join(`
|
|
99
99
|
`)}`)}return e.indexFiles.length>0&&t.push(`Index files:
|
|
100
100
|
${e.indexFiles.map(s=>` - ${s}`).join(`
|
|
101
101
|
`)}`),t.length===0?void 0:`The following file(s) already exist and will be overwritten:
|
|
102
102
|
|
|
103
103
|
${t.join(`
|
|
104
104
|
|
|
105
|
-
`)}`}
|
|
105
|
+
`)}`}r(Le,"formatOverwriteWarnings");async function fe(e,t,n,s={}){if(e.length===0)return;const{devDependency:o=!1}=s,i=n==="npm"?"install":"add",a=(()=>{if(!o)return[];switch(n){case"npm":return["--save-dev"];case"pnpm":return["-D"];case"yarn":return["-D"];case"bun":return["-d"]}})();try{await rt(n,[i,...a,...e],{cwd:t})}catch{throw new p(g.DEPENDENCY_INSTALL_FAILED(n))}}r(fe,"installDependencies");async function Nt(e,t,n){const s=R(n,t.name);if(await B(s,{recursive:!0}),e.path.endsWith(".css")){const i=R(s,`${t.name}.css`);return await Q(i,e.content),i}const o=R(s,ye(e.path));return await Q(o,e.content),o}r(Nt,"writeComponentFile");async function Dt({registryIndex:e,selectedComponents:t,componentType:n,componentsOutputDirectory:s,packageManager:o}){const i=[],a=new Set;await B(s,{recursive:!0});const l=await de(e,t,n);for(const f of l){const d=await ue({type:"component",name:f.name,framework:n});for(const m of d.files)if(m)try{const h=await Nt(m,f,s);h&&i.push(h)}catch(h){const b=h instanceof Error?`: ${h.message}`:"";throw new p(`Failed to write component file for "${f.name}"${b}`)}const u=f.dependencies?.[n]||[];for(const m of u)a.add(m)}if(a.size>0)try{await fe(Array.from(a),process.cwd(),o)}catch(f){const d=f instanceof Error?`: ${f.message}`:"";throw new p(`Failed to install component dependencies${d}`)}return{createdFiles:i,npmDependencies:a}}r(Dt,"installComponents");function Ft(e,t){const n=L(e),s=L(t),o=N(s,n);return!o.startsWith("..")&&!nt(o)}r(Ft,"isWithinDirectory");async function Ot(e){const t=[],n=L(process.cwd(),e);await B(n,{recursive:!0});const o=(await U()).filter(i=>i.type==="cube").map(i=>i.name);for(const i of o){const a=await ue({type:"cube",name:i});for(const l of a.files){if(!l)continue;const f=l.path.replace(/^styles\//,""),d=L(n,f);if(!Ft(d,n))throw new p(`Invalid file path detected in CUBE module "${i}": path escapes target directory`);const u=tt(d);try{await B(u,{recursive:!0}),await Q(d,l.content),t.push(d)}catch(m){const h=m instanceof Error?`: ${m.message}`:"";throw new p(`Failed to write CUBE module "${i}"${h}`)}}}return t}r(Ot,"installCUBE");async function At(e,t){await ne.mkdir(t,{recursive:!0});const n=[];for(const s of e)await ne.writeFile(s.path,s.content),n.push(s.path);return n}r(At,"writeTokenFiles");async function V(e,t){let n;if(t)n={type:"memory",data:t,config:e};else{if(!e.resolver)throw new p(g.RESOLVER_NOT_CONFIGURED());n={type:"resolver",resolverPath:e.resolver,config:e}}const{trees:s,resolved:o,modifiers:i,errors:a}=await ot(n);if(a.load.length>0){const l=a.load.map(f=>{const d=f.file.split("/").pop()||"unknown file";let u=`File ${d}: `;return f.message.includes("Unexpected token")?u=g.TOKEN_FILE_INVALID_JSON(d):f.message.includes("Unexpected end")?u=g.TOKEN_FILE_INCOMPLETE_JSON(d):u=g.TOKEN_FILE_GENERIC_ERROR(d,f.message),u});throw new p(g.TOKEN_LOAD_FAILED(l))}if(a.validation.length>0||a.flatten.length>0||a.resolution.length>0){const l=[...a.flatten,...a.validation,...a.resolution],f=new Map;for(const d of l)if(d.source?.sourcePath){const u=f.get(d.source.sourcePath)||[];u.push(d.message),f.set(d.source.sourcePath,u)}throw new p(g.TOKEN_VALIDATION_FAILED(f))}return{trees:s,resolved:o,modifiers:i}}r(V,"loadAndResolveTokensForCLI");const Pt=r(async(e,t,n)=>{const s=await _t(e),o=L(process.cwd(),t),i=s.files.map(a=>({path:R(o,ye(a.path)),content:a.content}));return{config:n,tokenFiles:i,tokensDir:o,createdTokenPaths:i.map(a=>N(process.cwd(),a.path))}},"prepareStarterKitForInstall");async function Mt(e){const t=await Pt(e.starterKit??"",e.tokensDir,e.config),n=await At(t.tokenFiles,e.tokensDir),s=await se(e.tokensDir);if(s.found==="none")throw new p(g.RESOLVER_NOT_FOUND(e.tokensDir));if(s.found==="multiple")throw new p(g.RESOLVER_MULTIPLE_FOUND(s.paths));const o={...e.config,resolver:s.path},{trees:i,resolved:a}=await V(o);e.setupResult={config:o,createdTokenPaths:t.createdTokenPaths,trees:i,resolved:a,tokenFiles:t.tokenFiles,tokensDir:t.tokensDir},e.createdFiles.push(...n),e.config=o,e.sugarcubeConfig={...e.sugarcubeConfig,resolver:s.path}}r(Mt,"installFromStarterKit");async function Ue(e=!0){const t=[{label:"React",value:"react",hint:".tsx"},{label:"CSS Only",value:"css-only",hint:".css"},{label:c.dim("Web components"),value:"web-components",hint:"Coming soon!"}];e&&t.push({label:"Skip",value:"skip",hint:"continue without components"});const n=await at({message:"Build with",options:t});return oe(n)&&process.exit(0),n==="web-components"?(ct.info(c.blue("Web components are coming soon! Please choose React or CSS Only for now.")),Ue(e)):n}r(Ue,"promptComponentFramework");async function Lt(e,t){const n=e.filter(o=>o.type==="component"&&o.frameworks?.includes(t)),s=await lt({message:"Select components to add",options:n.map(o=>({label:o.name,value:o.name,hint:o.description})),required:!0});return oe(s)&&process.exit(0),s}r(Lt,"promptComponentSelectionFiltered");async function je(e,t=!1){const n=await ut({message:e,initialValue:t});return(!n||oe(n))&&($e(),process.exit(0)),!0}r(je,"confirmOverwrite");function j(e){return{absolute:L(process.cwd(),e)}}r(j,"resolveDirectoryFromFlag");async function Ut(e){if(e){const{absolute:t}=j(e);return{directory:t}}try{const{config:t}=await X(),n=t.output.cube||t.output.cssRoot,{absolute:s}=j(n);return{directory:s}}catch(t){if(be(t)){const{absolute:n}=j("src/styles");return{directory:n}}throw t}}r(Ut,"getCubeDir");async function jt(e){if(e){const{absolute:t}=j(e);return{directory:t}}try{const{config:t}=await X(),n=t.output.components??"src/components/ui",{absolute:s}=j(n);return{directory:s}}catch(t){if(be(t)){const{absolute:n}=j("src/components/ui");return{directory:n}}throw t}}r(jt,"getComponentsDir");const xt=pt(),E=r((e,t)=>xt?e:t,"unicodeOr"),Gt=E("\u25C7","o"),xe=E("\u250C","T"),O=E("\u2502","|"),pe=E("\u2514","\u2014"),Bt=E("\u2510","T"),Vt=E("\u2518","\u2014"),ee=E("\u2500","-"),Wt=E("\u256E","+"),Yt=E("\u256F","+"),Kt=E("\u2570","+"),zt=E("\u256D","+"),Ht=E("\u25CF","\u2022"),Jt=E("\u25C6","*"),qt=E("\u25B2","!"),Zt=E("\u25A0","x"),W=r((e,t=c.bgGreen,n=c.black)=>t(` ${n(e)} `),"label"),Y=r(e=>{const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"].join("|"),n=new RegExp(t,"g");return typeof e=="string"?e.replace(n,""):e},"strip"),K=r((e="",t)=>{process.stdout.write(`
|
|
106
106
|
|
|
107
|
-
|
|
108
|
-
|
|
107
|
+
${c.gray(xe)}${c.gray(ee)} ${e}
|
|
108
|
+
`)},"intro"),te=r((e="",t)=>{process.stdout.write(`${c.gray(O)}
|
|
109
|
+
${c.gray(pe)}${c.gray(ee)} ${e}
|
|
109
110
|
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
To create a config file:
|
|
116
|
-
${c.cyan(_.INIT)}
|
|
117
|
-
|
|
118
|
-
Stuck? ${c.cyan("https://sugarcube.sh")}`)}o(xt,"getCubeDir");async function Gt(e){if(e){const{absolute:t}=je(e);return{directory:t,fromConfig:!1}}if(O())try{const t=await ge("output.components");if(t)return{directory:t,fromConfig:!0}}catch{}throw new p(`A sugarcube config file was not found.
|
|
119
|
-
|
|
120
|
-
Either a config file or --components-dir is required to run this command.
|
|
121
|
-
|
|
122
|
-
To use the components command without a config file:
|
|
123
|
-
e.g. ${c.cyan(`${_.COMPONENTS} --components-dir src/components/ui`)}
|
|
124
|
-
|
|
125
|
-
To create a config file:
|
|
126
|
-
${c.cyan(_.INIT)}
|
|
127
|
-
|
|
128
|
-
Stuck? ${c.cyan("https://sugarcube.sh")}`)}o(Gt,"getComponentsDir");const Bt=mt(),E=o((e,t)=>Bt?e:t,"unicodeOr"),Vt=E("\u25C7","o"),xe=E("\u250C","T"),A=E("\u2502","|"),he=E("\u2514","\u2014"),Wt=E("\u2510","T"),Yt=E("\u2518","\u2014"),ne=E("\u2500","-"),Kt=E("\u256E","+"),Ht=E("\u256F","+"),zt=E("\u2570","+"),Jt=E("\u256D","+"),qt=E("\u25CF","\u2022"),Zt=E("\u25C6","*"),Qt=E("\u25B2","!"),Xt=E("\u25A0","x"),K=o((e,t=c.bgGreen,n=c.black)=>t(` ${n(e)} `),"label"),H=o(e=>{const t=["[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]+)*|[a-zA-Z\\d]+(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)","(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PRZcf-ntqry=><~]))"].join("|"),n=new RegExp(t,"g");return typeof e=="string"?e.replace(n,""):e},"strip"),z=o((e="",t)=>{process.stdout.write(`
|
|
129
|
-
|
|
130
|
-
${c.gray(xe)}${c.gray(ne)} ${e}
|
|
131
|
-
`)},"intro"),se=o((e="",t)=>{process.stdout.write(`${c.gray(A)}
|
|
132
|
-
${c.gray(he)}${c.gray(ne)} ${e}
|
|
133
|
-
|
|
134
|
-
`)},"outro");function x(e){return new Promise(t=>setTimeout(t,e))}o(x,"sleep");const en=[Jt,Kt,zt,Ht],tn=[xe,Wt,he,Yt];function Ge(e,t,n,s){let r=n,i=n;return s==="center"?r=Math.floor((t-e)/2):s==="right"&&(r=t-e-n),i=t-r-e,[r,i]}o(Ge,"getPaddingForLine");const nn=o(e=>e,"defaultFormatBorder"),we=o((e="",t="",n)=>{const s=n?.output??process.stdout,r=dt(s),a=1*2,l=n?.titlePadding??1,f=n?.contentPadding??2,d=n?.width===void 0||n.width==="auto"?1:Math.min(1,n.width),u=n?.includePrefix?`${A} `:"",m=n?.formatBorder??nn,h=(n?.rounded?en:tn).map(m),b=m(ne),v=m(A),S=r-u.length;let k=Math.floor(r*d)-u.length;if(n?.width==="auto"){const Z=e.split(`
|
|
135
|
-
`);let B=H(t).length+l*2;for(const Xe of Z){const Te=H(Xe).length+f*2;Te>B&&(B=Te)}const Q=B+a;Q<k&&(k=Q)}k%2!==0&&(k<S?k++:k--);const I=k-a,D=I-l*2,y=H(t).length>D?`${t.slice(0,D-3)}...`:t,[C,N]=Ge(H(y).length,I,l,n?.titleAlign),P=pt(e,I-f*2,{hard:!0,trim:!1});s.write(`${u}${h[0]}${b.repeat(C)}${y}${b.repeat(N)}${h[1]}
|
|
136
|
-
`);const q=P.split(`
|
|
137
|
-
`);for(const Z of q){const[B,Q]=Ge(H(Z).length,I,f,n?.contentAlign);s.write(`${u}${v}${" ".repeat(B)}${Z}${" ".repeat(Q)}${v}
|
|
111
|
+
`)},"outro");function x(e){return new Promise(t=>setTimeout(t,e))}r(x,"sleep");const Qt=[zt,Wt,Kt,Yt],Xt=[xe,Bt,pe,Vt];function Ge(e,t,n,s){let o=n,i=n;return s==="center"?o=Math.floor((t-e)/2):s==="right"&&(o=t-e-n),i=t-o-e,[o,i]}r(Ge,"getPaddingForLine");const en=r(e=>e,"defaultFormatBorder"),me=r((e="",t="",n)=>{const s=n?.output??process.stdout,o=dt(s),a=1*2,l=n?.titlePadding??1,f=n?.contentPadding??2,d=n?.width===void 0||n.width==="auto"?1:Math.min(1,n.width),u=n?.includePrefix?`${O} `:"",m=n?.formatBorder??en,h=(n?.rounded?Qt:Xt).map(m),b=m(ee),w=m(O),k=o-u.length;let v=Math.floor(o*d)-u.length;if(n?.width==="auto"){const q=e.split(`
|
|
112
|
+
`);let G=Y(t).length+l*2;for(const Xe of q){const we=Y(Xe).length+f*2;we>G&&(G=we)}const Z=G+a;Z<v&&(v=Z)}v%2!==0&&(v<k?v++:v--);const I=v-a,C=I-l*2,T=Y(t).length>C?`${t.slice(0,C-3)}...`:t,[_,$]=Ge(Y(T).length,I,l,n?.titleAlign),A=ft(e,I-f*2,{hard:!0,trim:!1});s.write(`${u}${h[0]}${b.repeat(_)}${T}${b.repeat($)}${h[1]}
|
|
113
|
+
`);const J=A.split(`
|
|
114
|
+
`);for(const q of J){const[G,Z]=Ge(Y(q).length,I,f,n?.contentAlign);s.write(`${u}${w}${" ".repeat(G)}${q}${" ".repeat(Z)}${w}
|
|
138
115
|
`)}s.write(`${u}${h[2]}${b.repeat(I)}${h[3]}
|
|
139
|
-
`)},"box");function
|
|
140
|
-
${e}`;
|
|
141
|
-
${e}`;
|
|
142
|
-
${e}`;
|
|
143
|
-
`),"renderContent");h(
|
|
144
|
-
`))}else{const
|
|
145
|
-
`))}else h([...
|
|
146
|
-
`));await x(1e3),s.removeListener("keypress",
|
|
147
|
-
`),"rawLog"),
|
|
116
|
+
`)},"box");function ge(e,t={}){const n=`
|
|
117
|
+
${e}`;me(n,c.black(c.bgRed(" ERROR ")),{width:"auto",titlePadding:2,formatBorder:c.red,...t})}r(ge,"errorBoxWithBadge");function Be(e,t={}){const n=`
|
|
118
|
+
${e}`;me(n,c.black(c.bgYellow(" WARNING ")),{width:"auto",titlePadding:2,formatBorder:c.yellow,...t})}r(Be,"warningBoxWithBadge");function tn(e,t={}){const n=`
|
|
119
|
+
${e}`;me(n,c.black(c.bgCyan(" INFO ")),{width:"auto",titlePadding:2,formatBorder:c.cyan,...t})}r(tn,"infoBoxWithBadge");const nn=r((e,t)=>{if(!(e.meta&&e.name!=="escape")){if(e.ctrl){if(e.name==="a")return"first";if(e.name==="c"||e.name==="d")return"abort";if(e.name==="e")return"last";if(e.name==="g")return"reset"}return e.name==="return"||e.name==="enter"?"submit":e.name==="backspace"?"delete":e.name==="delete"?"deleteForward":e.name==="abort"?"abort":e.name==="escape"?"exit":e.name==="tab"?"next":e.name==="pagedown"?"nextPage":e.name==="pageup"?"prevPage":e.name==="home"?"home":e.name==="end"?"end":e.name==="up"?"up":e.name==="down"?"down":e.name==="right"?"right":e.name==="left"?"left":!1}},"action"),sn=r(async(e,t={})=>{const{sidebarSymbol:n=c.gray("\u2502"),clear:s=!1,stdin:o=process.stdin,stdout:i=process.stdout}=t,a=Ne.createInterface({input:o,escapeCodeTimeout:50}),l=De(i,{showCursor:!1});Ne.emitKeypressEvents(o,a);let f=0,d=!1;const u=r(async()=>{o.off("keypress",m),o.isTTY&&o.setRawMode(!1),a.close(),d=!0,f<e.length-1||s?l.clear():l.done()},"done"),m=r((h,b)=>{o.isTTY&&o.setRawMode(!0);const w=nn(b);if(w==="abort")return u(),process.exit(0);["up","down","left","right"].includes(w)||u()},"handleKeyPress");o.isTTY&&o.setRawMode(!0),o.on("keypress",m);for(const h of e){const b=Array.isArray(h)?h:h.split(" "),w=[];for(const I of[""].concat(b)){I&&w.push(I);const C=w.join(" ").replace(/sugarcube/g,c.cyan("sugarcube")),T=`${n} ${C}`;l(T),d||await new Promise(_=>setTimeout(_,Math.floor(Math.random()*126)+75))}d||await new Promise(I=>setTimeout(I,100));const v=(await Promise.all(b).then(I=>I.join(" "))).replace(/sugarcube/g,c.cyan("sugarcube"));l(`${n} ${v}`),d||await new Promise(I=>setTimeout(I,Math.floor(Math.random()*201)+1200)),f++}o.off("keypress",m),await new Promise(h=>setTimeout(h,100)),u(),o.isTTY&&o.setRawMode(!1),o.removeAllListeners("keypress")},"sayAnimatedInSidebar");function rn(){return Math.floor(Math.random()*551)+200}r(rn,"getRandomTaskDuration");async function on(e,{sidebarSymbol:t="\u2502",spacing:n=1,stdin:s=process.stdin,stdout:o=process.stdout,initialDelayMs:i=200,minDurationMs:a,successPauseMs:l=300,successMessage:f,successAsOutro:d=!1}={}){const u=r((T,_)=>{let $="";switch(_){case"start":$=`${c.cyan(`\u25B6 ${T.start}`)}`;break;case"pending":$=`${c.dim(`\u25A1 ${T.pending}`)}`;break;case"success":$=`${c.green(`\u2714 ${T.end}`)}`;break;case"end":$=`${c.dim(`\u25A0 ${T.end}`)}`;break}return`${t} ${$}`},"formatWithSidebar"),m=Array.from({length:e.length},()=>"");e.forEach((T,_)=>{m[_]=u(T,"pending")});const h=De(o),b=Ce.createInterface({input:s,escapeCodeTimeout:50});Ce.emitKeypressEvents(s,b);const w=r(T=>{T===""&&(h.clear(),b.close(),s.isTTY&&s.setRawMode(!1),process.exit(0)),s.isTTY&&s.setRawMode(!0)},"keypress");s.isTTY&&s.setRawMode(!0),s.on("keypress",w);const k=Array.from({length:Math.max(n,0)},()=>`${t}`),v=r(()=>[...k,...m].join(`
|
|
120
|
+
`),"renderContent");h(v()),await x(i);let I=0;for(const T of e){m[I]=u(T,"start"),h(v());const _=Date.now(),$=T.while();try{await $;const A=Date.now()-_,J=typeof a=="number"?a:rn();A<J&&await x(J-A),m[I]=u(T,"success"),h(v()),await x(l)}catch(A){throw m[I]=`${t} ${c.red(`\u2717 ${T.end} (failed)`)}`,h(v()),T.onError?.(A),s.removeListener("keypress",w),b.close(),s.isTTY&&s.setRawMode(!1),A}I++}const C=e.map(T=>u(T,"end"));if(f)if(d){const T=`${c.gray(pe)}${c.gray(ee)} ${c.green(f)}`;h([...k,...C,`${t}`,T].join(`
|
|
121
|
+
`))}else{const T=`${t} ${c.green(f)}`;h([...k,...C,`${t}`,T].join(`
|
|
122
|
+
`))}else h([...k,...C].join(`
|
|
123
|
+
`));await x(1e3),s.removeListener("keypress",w),s.isTTY&&s.setRawMode(!1),b.close(),h.done()}r(on,"executeTasksInSidebar");const an=r(e=>process.stdout.write(`${e}
|
|
124
|
+
`),"rawLog"),S={message:r((e=[],{symbol:t=c.gray(O),secondarySymbol:n=c.gray(O),output:s=process.stdout,spacing:o=1}={})=>{const i=[];for(let l=0;l<o;l++)i.push(`${n}`);const a=Array.isArray(e)?e:e.split(`
|
|
148
125
|
`);if(a.length>0){const[l,...f]=a;l&&l.length>0?i.push(`${t} ${l}`):i.push(t);for(const d of f)d.length>0?i.push(`${n} ${d}`):i.push(n)}s.write(`${i.join(`
|
|
149
126
|
`)}
|
|
150
|
-
`)},"message"),info:
|
|
151
|
-
`)},"space"),break:
|
|
152
|
-
`)},"break")};function
|
|
127
|
+
`)},"message"),info:r((e,t)=>{S.message(e,{...t,symbol:c.blue(Ht)})},"info"),success:r((e,t)=>{S.message(e,{...t,symbol:c.green(Jt)})},"success"),step:r((e,t)=>{S.message(e,{...t,symbol:c.green(Gt)})},"step"),warn:r((e,t)=>{S.message(e,{...t,symbol:c.yellow(qt)})},"warn"),error:r((e,t)=>{S.message(e,{...t,symbol:c.red(Zt)})},"error"),animated:r(async(e,{secondarySymbol:t=c.gray(O),output:n=process.stdout,clear:s=!1,...o}={})=>sn(e,{sidebarSymbol:t,stdout:n,clear:s,...o}),"animated"),tasks:r(async(e,{spacing:t=1,secondarySymbol:n=c.gray(O),output:s=process.stdout,...o}={})=>on(e,{sidebarSymbol:n,spacing:t,stdout:s,...o}),"tasks"),space:r((e=1)=>{for(let t=0;t<e;t++)process.stdout.write(`${c.gray(O)}
|
|
128
|
+
`)},"space"),break:r((e=1)=>{for(let t=0;t<e;t++)process.stdout.write(`
|
|
129
|
+
`)},"break")};function z(e){if(e instanceof p)S.space(1),ge(e.message,{});else{const t=`An unexpected error occurred: ${e instanceof Error?e.message:String(e)}
|
|
153
130
|
|
|
154
|
-
If this issue persists, please report it: ${c.cyan("https://github.com/sugarcube-org/sugarcube/issues")}`;
|
|
155
|
-
${e.
|
|
131
|
+
If this issue persists, please report it: ${c.cyan("https://github.com/sugarcube-org/sugarcube/issues")}`;S.space(1),ge(t,{})}process.exit(1)}r(z,"handleError");function H(e,t=process.cwd()){try{const n=mt(t,"package.json");if(!D(n))return!1;const s=Te(n,"utf-8"),o=JSON.parse(s),i={...o.dependencies,...o.devDependencies,...o.peerDependencies};return e in i}catch{return!1}}r(H,"isPackageInstalled");async function Ve(e,{withFallback:t=!1}={}){const n=await gt({programmatic:!0,cwd:e});if(n?.includes("yarn"))return"yarn";if(n?.includes("pnpm"))return"pnpm";if(n?.includes("bun"))return"bun";if(n?.includes("npm"))return"npm";if(t){const s=process.env.npm_config_user_agent||"";if(s.includes("yarn"))return"yarn";if(s.includes("pnpm"))return"pnpm";if(s.includes("bun"))return"bun"}return"npm"}r(Ve,"getPackageManager");const cn=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, css-only)").option("--components-dir <dir>","Components output directory (e.g., 'src/components')").option("-s, --silent","Suppress logs and prompts").option("-o, --overwrite","Overwrite existing files").action(async(e,t)=>{try{t.silent||K(W(c.bgGreen(c.black("Components"))));const{directory:n}=await jt(t.componentsDir);let s=[],o;if(e.length>0||t.framework){if(!t.framework)throw new p(g.COMPONENTS_FRAMEWORK_REQUIRED());if(!["react","css-only"].includes(t.framework))throw new p(g.COMPONENTS_INVALID_FRAMEWORK());o=t.framework,s=e}else{o=await Ue(!1);const w=await U();w||($e("Failed to fetch component list"),process.exit(1)),s=await Lt(w,o)}const i=await Ve(process.cwd(),{withFallback:!0}),a=await U(),l=await de(a,s,o),f=await $t({selectedComponents:s,componentType:o,componentsOutputDirectory:n}),d=Le(f);if(d&&!t.force&&!t.silent){const w=Be(d,{});S.space(1),await je("Continue?",!1)}const u=[],m=[],h=new Set;for(const w of l){const k=w.dependencies?.[o]||[];for(const v of k)h.add(v)}const b=Array.from(h).filter(w=>!H(w,process.cwd()));b.length>0&&u.push({pending:`Install ${b.length} dependencies`,start:`Installing ${b.join(", ")}...`,end:`Installed ${b.join(", ")}`,while:r(async()=>{await fe(b,process.cwd(),i)},"while")});for(const w of l)u.push({pending:`Write component files for ${w.name}`,start:`Writing component files for ${w.name}...`,end:`Wrote component files for ${w.name}`,while:r(async()=>{const k=await Dt({registryIndex:a,selectedComponents:[w.name],componentType:o,componentsOutputDirectory:n,overwrite:t.overwrite||!1,packageManager:i});m.push(...k.createdFiles)},"while")});await S.tasks(u,{successMessage:"Components added successfully! \u{1F389} ",minDurationMs:0,successAsOutro:!0}),an("")}catch(n){z(n)}}),ln=new M().name("cube").description("Add CUBE CSS to your project").option("-s, --silent","Suppress logs and prompts").option("-f, --force","Skip overwrite confirmation").option("--cube-dir <dir>","CUBE CSS output directory (defaults to cssRoot)").action(async e=>{try{e.silent||K(W("CUBE CSS"));const{directory:t}=await Ut(e.cubeDir);try{await B(t,{recursive:!0})}catch(i){const a=i instanceof Error?`: ${i.message}`:"";throw new p(`Failed to create output directory${a}`)}const n=await Ct({cubeDirectory:t}),s=Le(n);if(s&&!e.force&&!e.silent){S.space(1);const i=Be(s,{});await je("Continue?",!1)}const o=await Ot(t);if(!e.silent){S.space(1);const i=o,f=[...new Set(i)].map(d=>N(process.cwd(),d)).map(d=>({pending:`Write ${d}`,start:`Writing ${d}`,end:`Wrote ${d}`,while:r(async()=>{},"while")}));await S.tasks(f,{spacing:0,minDurationMs:0,successPauseMs:100,successMessage:"\u{1F389} Files written!"}),te(c.green("CUBE added successfully."))}}catch(t){z(t)}}),un="**/*.{html,htm,js,ts,jsx,tsx,vue,svelte,astro,php,njk,liquid,pug,hbs,handlebars,twig,erb,ejs}",dn=["**/node_modules/**","**/dist/**","**/build/**","**/.next/**","**/.nuxt/**","**/.astro/**","**/.git/**","**/coverage/**","**/.pnpm/**","**/.pnpm-store/**","**/.npm/**","**/.cache/**","**/.turbo/**","**/.vercel/**","**/.svelte-kit/**","**/out/**","**/__snapshots__/**","**/*.config.{js,ts,mjs}","**/*.min.js","**/*.bundle.js","**/*.d.ts"],We=1e4,Ye=100;async function Ke(e,t){const n={name:"sugarcube",rules:it(t.utilities??{},e),preflights:[]},s=await ht({presets:[n]}),o=await ae([un],{ignore:dn,dot:!1,onlyFiles:!0,absolute:!1});if(o.length===0)return[];if(o.length>We)throw new p(`Found ${o.length} files to scan (limit: ${We}). Are you running this from a monorepo root or a directory containing multiple projects? Run the command from within a single project directory instead.`);const i=[];let a=0;const l=Ye*1024*1024;for(const u of o){const m=await Se(u,"utf8");if(a+=m.length,a>l)throw new p(`Total source size exceeds ${Ye}MB. Are you running this from a monorepo root or a directory containing multiple projects? Run the command from within a single project directory instead.`);i.push(m)}const f=i.join(`
|
|
132
|
+
`),{css:d}=await s.generate(f,{preflights:!1});return d?.trim()?[{path:`${t.output.utilities}/utilities.gen.css`,css:d}]:[]}r(Ke,"generateSugarcubeUtilities");async function fn(e,t,n,s){const o=[],i=await re(e,t,n),a=await Ie(i,n,s);await ve(a),o.push(...a);const l=await Ke(i,n);return await ke(l),o.push(...l),o}r(fn,"generateAllCSS");function pn(e){let t;(e.fluidMin||e.fluidMax)&&(t={min:e.fluidMin?Number.parseInt(e.fluidMin,10):320,max:e.fluidMax?Number.parseInt(e.fluidMax,10):1200});const n={resolver:e.resolver,output:{cssRoot:e.stylesDir,variables:e.variablesDir,utilities:e.utilitiesDir},transforms:{fluid:t,colorFallbackStrategy:e.colorFallback}};return Re(n)}r(pn,"buildConfigFromFlags");function mn(e,t){const n={min:t.fluidMin?Number.parseInt(t.fluidMin,10):e.transforms.fluid.min,max:t.fluidMax?Number.parseInt(t.fluidMax,10):e.transforms.fluid.max};return{...e,resolver:t.resolver??e.resolver,transforms:{fluid:n,colorFallbackStrategy:t.colorFallback??e.transforms.colorFallbackStrategy},output:{...e.output,cssRoot:t.stylesDir??e.output.cssRoot,variables:t.variablesDir??e.output.variables,utilities:t.utilitiesDir??e.output.utilities}}}r(mn,"mergeConfigWithFlags");function gn(e){return!!(e.resolver||e.stylesDir||e.variablesDir||e.utilitiesDir||e.fluidMin||e.fluidMax||e.colorFallback)}r(gn,"hasRelevantFlags");function hn(e){if(e.colorFallback&&!["native","polyfill"].includes(e.colorFallback))throw new p(`Invalid --color-fallback value: "${e.colorFallback}". Must be "native" or "polyfill".`);if(e.fluidMin){const t=Number.parseInt(e.fluidMin,10);if(Number.isNaN(t)||t<=0)throw new p(`Invalid --fluid-min value: "${e.fluidMin}". Must be a positive number.`)}if(e.fluidMax){const t=Number.parseInt(e.fluidMax,10);if(Number.isNaN(t)||t<=0)throw new p(`Invalid --fluid-max value: "${e.fluidMax}". Must be a positive number.`)}}r(hn,"validateFlags");async function wn(e){if(Ee()){const{config:s}=await X();return mn(s,e)}const t=await se(process.cwd());if(t.found==="multiple")throw new p(g.GENERATE_MULTIPLE_RESOLVERS_NO_CONFIG(t.paths));const n=e.resolver??(t.found==="one"?t.path:void 0);if(n||gn(e))return pn({...e,resolver:n});throw new p(g.GENERATE_NO_CONFIG_OR_RESOLVER())}r(wn,"resolveConfig");const yn=new M().name("generate").description("Generate CSS from your design tokens").option("--force","Skip overwrite confirmation").option("-s, --silent","Suppress logs and prompts").option("--resolver <path>","Path to token resolver file (.resolver.json)").option("--styles-dir <dir>","CSS output directory (default: 'src/styles')").option("--variables-dir <dir>","Token variables output directory (default: 'src/styles/global')").option("--utilities-dir <dir>","Utilities output directory (default: 'src/styles/utilities')").option("--fluid-min <number>","Minimum viewport width for fluid scaling (default: 320)").option("--fluid-max <number>","Maximum viewport width for fluid scaling (default: 1200)").option("--color-fallback <strategy>","Color fallback strategy: 'native' or 'polyfill' (default: native)").action(async e=>{try{if(e.silent||K(W("Generate CSS")),hn(e),H("@sugarcube-org/vite"))throw new p("Sugarcube vite plugin detected. When using the plugin, CSS is generated automatically during your build process. Remove the plugin to use CLI generation instead.");const t=await wn(e),{trees:n,resolved:s,modifiers:o}=await V(t),i=await fn(n,s,t,o);if(!e.silent){const a=i.map(u=>u.path),d=[...new Set(a)].map(u=>N(process.cwd(),u)).map(u=>({pending:`Write ${u}`,start:`Writing ${u}`,end:`Wrote ${u}`,while:r(async()=>{},"while")}));await S.tasks(d,{spacing:1,minDurationMs:0,successPauseMs:100,successMessage:"\u{1F389} Files written!"}),S.space(1),te(c.green("CSS generated successfully."))}}catch(t){z(t)}});async function Tn(e){const t={};return(e.stylesDir||e.variablesDir||e.utilitiesDir)&&(t.output={},e.stylesDir&&(t.output.cssRoot=e.stylesDir),e.variablesDir&&(t.output.variables=e.variablesDir),e.utilitiesDir&&(t.output.utilities=e.utilitiesDir)),(e.fluidMin!==void 0||e.colorFallback)&&(t.transforms={},e.fluidMin!==void 0&&e.fluidMax!==void 0&&(t.transforms.fluid={min:Number(e.fluidMin),max:Number(e.fluidMax)}),e.colorFallback&&(t.transforms.colorFallbackStrategy=e.colorFallback)),t}r(Tn,"buildSugarcubeConfig");function ze(e){try{const t=ie.resolve(e,"package.json");if(!D(t))return null;const n=Te(t,"utf-8");return JSON.parse(n)}catch{return null}}r(ze,"getPackageJson");function P(e,t){if(!e)return!1;const n=e.dependencies,s=e.devDependencies;return!!(n?.[t]||s?.[t])}r(P,"hasDependency");function Sn(e,t){if(!e)return!1;const n=e.dependencies,s=e.devDependencies,o={...n,...s};return Object.keys(o).some(i=>i.startsWith(t))}r(Sn,"hasDependencyStartingWith");function bn(e){const t=D(ie.resolve(e,"src")),n=ze(e),s=t?"src/design-tokens":"design-tokens",o=t?"src/styles":"styles",i=t?"src/components":"components";let a="none";return P(n,"next")?a=D(ie.resolve(e,`${t?"src/":""}app`))?"next-app":"next-pages":P(n,"astro")?a="astro":P(n,"nuxt")?a="nuxt":P(n,"@sveltejs/kit")?a="sveltekit":Sn(n,"@remix-run/")?a="remix":P(n,"@11ty/eleventy")?a="eleventy":P(n,"vite")&&(a="vite"),{framework:a,isSrcDir:t,tokensDir:s,stylesDir:o,componentDir:i}}r(bn,"getProjectInfo");function En(e,t){if(["vite","astro","nuxt","sveltekit","remix"].includes(e))return!0;if(e==="eleventy"){const s=ze(t);return P(s,"vite")}return!1}r(En,"shouldInstallVitePlugin");function He(e,t=0){if(typeof e!="object"||e===null||t>Et)return!1;for(const[n,s]of Object.entries(e))if(!n.startsWith("$")&&typeof s=="object"&&s!==null&&("$value"in s||He(s,t+1)))return!0;return!1}r(He,"hasAnyToken");async function In(e){try{const t=await ae([St],{cwd:e,absolute:!0});for(const n of t)try{const s=await ne.readFile(n,"utf-8"),o=JSON.parse(s);if(He(o))return!0}catch{}return!1}catch{return!1}}r(In,"detectExistingTokens");function vn(e=process.cwd()){return wt(e)!==null}r(vn,"isTypeScriptProject");async function Je(e=process.cwd()){return vn(e)?"sugarcube.config.ts":"sugarcube.config.js"}r(Je,"getConfigFileName");function kn(e){return/^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(e)}r(kn,"isValidIdentifier");function he(e,t=0){const n=" ".repeat(t);if(e===null)return"null";if(e===void 0)return"undefined";if(typeof e=="string")return JSON.stringify(e);if(typeof e=="number"||typeof e=="boolean")return String(e);if(Array.isArray(e))return e.length===0?"[]":`[
|
|
133
|
+
${e.map(o=>`${n} ${he(o,t+1)}`).join(`,
|
|
156
134
|
`)}
|
|
157
135
|
${n}]`;if(typeof e=="object"){const s=Object.entries(e);return s.length===0?"{}":`{
|
|
158
|
-
${s.map(([i,a])=>{const l=
|
|
136
|
+
${s.map(([i,a])=>{const l=kn(i)?i:JSON.stringify(i);return`${n} ${l}: ${he(a,t+1)}`}).join(`,
|
|
159
137
|
`)}
|
|
160
|
-
${n}}`}return JSON.stringify(e)}
|
|
138
|
+
${n}}`}return JSON.stringify(e)}r(he,"formatValue");function Rn(e,t,n){const s=he(e,0);let o;return n?o=t?`import type { SugarcubeConfig } from "@sugarcube-org/vite";
|
|
161
139
|
|
|
162
140
|
const config: SugarcubeConfig = `:`// @ts-check
|
|
163
141
|
/**
|
|
164
142
|
* @type {import('@sugarcube-org/vite').SugarcubeConfig}
|
|
165
143
|
*/
|
|
166
|
-
const config = `:
|
|
167
|
-
const config = `,`${
|
|
144
|
+
const config = `:o=`// Configuration reference: ${Oe.CONFIGURATION}
|
|
145
|
+
const config = `,`${o}${s};
|
|
168
146
|
|
|
169
147
|
export default config;
|
|
170
|
-
`}
|
|
171
|
-
`),{css:d}=await s.generate(f,{preflights:!1});return d?.trim()?[{path:`${t.output.utilities}/utilities.gen.css`,css:d}]:[]}o(Je,"generateSugarcubeUtilities");async function yn(e,t,n,s){const r=[],i=await re(e,t,n),a=await ve(i,n,s);await ke(a),r.push(...a);const l=await Je(i,n);return await Re(l),r.push(...l),r}o(yn,"generateAllCSS");function Sn(e){let t;(e.fluidMin||e.fluidMax)&&(t={min:e.fluidMin?Number.parseInt(e.fluidMin,10):320,max:e.fluidMax?Number.parseInt(e.fluidMax,10):1200});const n={resolver:e.resolver,output:{cssRoot:e.stylesDir,variables:e.variablesDir,utilities:e.utilitiesDir},transforms:{fluid:t,colorFallbackStrategy:e.colorFallback}};return _e(n)}o(Sn,"buildConfigFromFlags");function Tn(e,t){const n={min:t.fluidMin?Number.parseInt(t.fluidMin,10):e.transforms.fluid.min,max:t.fluidMax?Number.parseInt(t.fluidMax,10):e.transforms.fluid.max};return{...e,resolver:t.resolver??e.resolver,transforms:{fluid:n,colorFallbackStrategy:t.colorFallback??e.transforms.colorFallbackStrategy},output:{...e.output,cssRoot:t.stylesDir??e.output.cssRoot,variables:t.variablesDir??e.output.variables,utilities:t.utilitiesDir??e.output.utilities}}}o(Tn,"mergeConfigWithFlags");function In(e){return!!(e.resolver||e.stylesDir||e.variablesDir||e.utilitiesDir||e.fluidMin||e.fluidMax||e.colorFallback)}o(In,"hasRelevantFlags");function En(e){if(e.colorFallback&&!["native","polyfill"].includes(e.colorFallback))throw new p(`Invalid --color-fallback value: "${e.colorFallback}". Must be "native" or "polyfill".`);if(e.fluidMin){const t=Number.parseInt(e.fluidMin,10);if(Number.isNaN(t)||t<=0)throw new p(`Invalid --fluid-min value: "${e.fluidMin}". Must be a positive number.`)}if(e.fluidMax){const t=Number.parseInt(e.fluidMax,10);if(Number.isNaN(t)||t<=0)throw new p(`Invalid --fluid-max value: "${e.fluidMax}". Must be a positive number.`)}}o(En,"validateFlags");async function bn(e){if(O()){const{config:s}=await W();return Tn(s,e)}const t=await me(process.cwd());if(t.found==="multiple")throw new p(g.GENERATE_MULTIPLE_RESOLVERS_NO_CONFIG(t.paths));const n=e.resolver??(t.found==="one"?t.path:void 0);if(n||In(e))return Sn({...e,resolver:n});throw new p(g.GENERATE_NO_CONFIG_OR_RESOLVER())}o(bn,"resolveConfig");const vn=new U().name("generate").description("Generate CSS from your design tokens").option("--force","Skip overwrite confirmation").option("-s, --silent","Suppress logs and prompts").option("--resolver <path>","Path to token resolver file (.resolver.json)").option("--styles-dir <dir>","CSS output directory (default: 'src/styles')").option("--variables-dir <dir>","Token variables output directory (default: 'src/styles/global')").option("--utilities-dir <dir>","Utilities output directory (default: 'src/styles/utilities')").option("--fluid-min <number>","Minimum viewport width for fluid scaling (default: 320)").option("--fluid-max <number>","Maximum viewport width for fluid scaling (default: 1200)").option("--color-fallback <strategy>","Color fallback strategy: 'native' or 'polyfill' (default: native)").action(async e=>{try{if(e.silent||z(K("Generate CSS")),En(e),G("@sugarcube-org/vite"))throw new p("Sugarcube vite plugin detected. When using the plugin, CSS is generated automatically during your build process. Remove the plugin to use CLI generation instead.");const t=await bn(e),{trees:n,resolved:s,modifiers:r}=await Y(t),i=await yn(n,s,t,r);if(!e.silent){const a=i.map(u=>u.path),d=[...new Set(a)].map(u=>R(process.cwd(),u)).map(u=>({pending:`Write ${u}`,start:`Writing ${u}`,end:`Wrote ${u}`,while:o(async()=>{},"while")}));await T.tasks(d,{spacing:1,minDurationMs:0,successPauseMs:100,successMessage:"\u{1F389} Files written!"}),T.space(1),se(c.green("CSS generated successfully."))}}catch(t){J(t)}});async function kn(e){const t=R(process.cwd(),e.actualStylesDir),n=e.isSrcDir?te.output.components:te.output.components.replace(/^src\//,"");return{resolver:e.resolverPath,output:{cssRoot:t,components:n}}}o(kn,"buildSugarcubeConfig");function qe(e){try{const t=ae.resolve(e,"package.json");if(!F(t))return null;const n=Ee(t,"utf-8");return JSON.parse(n)}catch{return null}}o(qe,"getPackageJson");function M(e,t){if(!e)return!1;const n=e.dependencies,s=e.devDependencies;return!!(n?.[t]||s?.[t])}o(M,"hasDependency");function Rn(e,t){if(!e)return!1;const n=e.dependencies,s=e.devDependencies,r={...n,...s};return Object.keys(r).some(i=>i.startsWith(t))}o(Rn,"hasDependencyStartingWith");function _n(e){const t=F(ae.resolve(e,"src")),n=qe(e),s=t?"src/design-tokens":"design-tokens",r=t?"src/styles":"styles",i=t?"src/components":"components";let a="none";return M(n,"next")?a=F(ae.resolve(e,`${t?"src/":""}app`))?"next-app":"next-pages":M(n,"astro")?a="astro":M(n,"nuxt")?a="nuxt":M(n,"@sveltejs/kit")?a="sveltekit":Rn(n,"@remix-run/")?a="remix":M(n,"@11ty/eleventy")?a="eleventy":M(n,"vite")&&(a="vite"),{framework:a,isSrcDir:t,tokensDir:s,stylesDir:r,componentDir:i}}o(_n,"getProjectInfo");function $n(e,t){if(["vite","astro","nuxt","sveltekit","remix"].includes(e))return!0;if(e==="eleventy"){const s=qe(t);return M(s,"vite")}return!1}o($n,"shouldInstallVitePlugin");function Ze(e,t=0){if(typeof e!="object"||e===null||t>bt)return!1;for(const[n,s]of Object.entries(e))if(!n.startsWith("$")&&typeof s=="object"&&s!==null&&("$value"in s||Ze(s,t+1)))return!0;return!1}o(Ze,"hasAnyToken");async function Cn(e){try{const t=await ee(It,{cwd:e,absolute:!0});for(const n of t)try{const s=await oe.readFile(n,"utf-8"),r=JSON.parse(s);if(Ze(r))return!0}catch{}return!1}catch{return!1}}o(Cn,"detectExistingTokens");const Nn=o(async e=>{T.space(2),await x(200);let t="Next steps";if(e.pluginToInstall===le)t+=`
|
|
148
|
+
`}r(Rn,"formatConfigAsCode");async function _n(e,t){try{const n=await Je(),s=n.endsWith(".ts"),o=Rn(e,s,t);await Q(n,o,"utf-8")}catch(n){const s=n instanceof Error?`: ${n.message}`:"";throw new p(`Failed to write config file${s}`)}}r(_n,"writeSugarcubeConfig");const $n=r(async e=>{S.space(2),await x(200);let t="Next steps";if(e.pluginToInstall===Fe)t+=`
|
|
172
149
|
|
|
173
150
|
`,t+=`1. Configure the plugin
|
|
174
151
|
`,t+=` Add the plugin to your build configuration:
|
|
@@ -180,18 +157,20 @@ export default config;
|
|
|
180
157
|
`,t+=`
|
|
181
158
|
|
|
182
159
|
`,t+=`3. (Optional) Add CUBE CSS
|
|
183
|
-
`,t+=` ${c.cyan(
|
|
160
|
+
`,t+=` ${c.cyan(F.CUBE)}`,t+=`
|
|
184
161
|
|
|
185
162
|
`,t+=`4. (Optional) Add components
|
|
186
|
-
`,t+=` ${c.cyan(
|
|
163
|
+
`,t+=` ${c.cyan(F.COMPONENTS)}`;else{const n=`${e.stylesDir}/global/tokens.variables.gen.css`;t+=`
|
|
187
164
|
|
|
188
165
|
`,t+=`1. Import the generated CSS
|
|
189
166
|
`;const s=e.isSrcDir?`"${n}"`:`"./${n}"`;t+=` ${c.cyan(`import ${s}`)}`,t+=`
|
|
190
167
|
|
|
191
168
|
`,t+=`2. (Optional) Add CUBE CSS
|
|
192
|
-
`,t+=` ${c.cyan(
|
|
169
|
+
`,t+=` ${c.cyan(F.CUBE)}`,t+=`
|
|
193
170
|
|
|
194
171
|
`,t+=`3. (Optional) Add components
|
|
195
|
-
`,t+=` ${c.cyan(
|
|
172
|
+
`,t+=` ${c.cyan(F.COMPONENTS)}`}t+=`
|
|
173
|
+
|
|
174
|
+
`,t+=`Docs: ${c.cyan("https://sugarcube.sh")}`,tn(t,{width:.75}),await x(200),S.break(1)},"nextSteps");async function Cn(e){await $n(e)}r(Cn,"next");const Nn=r(async()=>{const e=["Welcome to sugarcube \u2014 the toolkit for seriously sweet frontends!"];S.space(1),await S.animated(e,{clear:!1})},"welcome");function qe(e,t){if(!e||e.trim()==="")throw new p(g.DIRECTORY_PATH_EMPTY(t));const s=st(e).split("/")[0];if(s&&bt.includes(s))throw new p(g.DIRECTORY_PATH_RESERVED(t,e))}r(qe,"validateDirectoryPath");function Dn(e){e.tokensDir&&qe(e.tokensDir,"tokens-dir"),e.stylesDir&&qe(e.stylesDir,"styles-dir");const t=e.fluidMin!==void 0,n=e.fluidMax!==void 0;if(t!==n)throw new p(`Both --fluid-min and --fluid-max must be provided together.
|
|
196
175
|
|
|
197
|
-
|
|
176
|
+
Either specify both flags or omit both to use defaults (320px - 1200px).`)}r(Dn,"validateOptions");async function Fn(){Ee()&&(ge(g.CONFIG_EXISTS(),{}),process.exit(1))}r(Fn,"preflightInit");async function On(e){const t=bn(process.cwd()),n=e.tokensDir||t.tokensDir,s=e.stylesDir||t.stylesDir,o=await In(n);let i=null;if(o){const a=await se(n);if(a.found==="none")throw new p(g.RESOLVER_NOT_FOUND(n));if(a.found==="multiple")throw new p(g.RESOLVER_MULTIPLE_FOUND(a.paths));i=a.path}return{tokensDir:n,stylesDir:s,isSrcDir:t.isSrcDir,hasExistingTokens:o,resolverPath:i,framework:t.framework}}r(On,"initializeProjectContext");function An(e,t,n){const s=t?null:e.kit||ce;if(e.skipPlugin)return{starterKit:s,pluginToInstall:null};const o=Pn(n,process.cwd());return{starterKit:s,pluginToInstall:o}}r(An,"determineInstallationTargets");function Pn(e,t){return En(e,t)?Fe:null}r(Pn,"determinePlugin");async function Mn(e,t,n,s,o){const i=await Ve(process.cwd(),{withFallback:!0});return{options:e,...t,isSrcDir:t.isSrcDir,config:n,sugarcubeConfig:s,...o,packageManager:i,createdFiles:[],createdDirectories:[],installedDependencies:[],tasks:[]}}r(Mn,"buildInitContext");async function Ln(e){const{trees:t,resolved:n}=await V(e.config);e.setupResult={config:e.config,createdTokenPaths:[],trees:t,resolved:n,tokenFiles:[],tokensDir:e.tokensDir}}r(Ln,"processExistingTokens");async function Un(e){!e.hasExistingTokens&&e.starterKit?await Mt(e):await Ln(e)}r(Un,"setupDesignTokens");async function jn(e){if(!e.setupResult)throw new p(g.INITIALIZATION_INCOMPLETE());const{trees:t,resolved:n}=e.setupResult,s=await re(t,n,e.config),o=await Ie(s,e.config);await ve(o)}r(jn,"writeCSSVariables");async function xn(e){if(!e.setupResult)throw new p(g.INITIALIZATION_INCOMPLETE());const{trees:t,resolved:n}=e.setupResult,s=await re(t,n,e.config),o=await Ke(s,e.config);o.length&&await ke(o)}r(xn,"writeCSSUtilities");async function Gn(e){if(e.pluginToInstall&&!H(e.pluginToInstall))try{await fe([e.pluginToInstall],process.cwd(),e.packageManager,{devDependency:!0}),e.installedDependencies.push(e.pluginToInstall)}catch{throw new p(g.PLUGIN_INSTALL_FAILED({pluginToInstall:e.pluginToInstall,packageManager:e.packageManager}))}}r(Gn,"installPlugins");function Ze(e){return!!(e.stylesDir||e.variablesDir||e.utilitiesDir||e.fluidMin||e.fluidMax||e.colorFallback)}r(Ze,"hasCustomizationFlags");async function Qe(e){if(Ze(e.options))try{const t=!!e.pluginToInstall;await _n(e.sugarcubeConfig,t);const n=await Je();e.createdFiles.push(n)}catch{throw new p(g.CONFIG_WRITE_FAILED())}}r(Qe,"finalize");function Bn(e){const t=[];if(e.hasExistingTokens?t.push({pending:"Looking for existing tokens",start:"Looking for existing tokens...",end:`Existing tokens found at ${e.tokensDir} ${E("\u2192","->")} using them`,while:r(async()=>{},"while")}):e.starterKit&&t.push({pending:"Looking for existing tokens",start:"Looking for existing tokens...",end:`No existing tokens detected ${E("\u2192","->")} adding starter kit`,while:r(async()=>{},"while")}),e.pluginToInstall){const n="Vite";H(e.pluginToInstall)?t.push({pending:`Checking for ${n} compatibility`,start:`Checking for ${n} compatibility...`,end:`${n} plugin already installed ${E("\u2192","->")} skipping plugin installation`,while:r(async()=>{},"while")}):t.push({pending:"Checking for Vite compatibility",start:"Checking for Vite compatibility...",end:`Vite detected ${E("\u2192","->")} plugin will be installed`,while:r(async()=>{},"while")})}else{const n=e.options.skipPlugin;t.push({pending:"Checking for Vite compatibility",start:"Checking for Vite compatibility...",end:n?`Plugin skipped ${E("\u2192","->")} CSS will be generated as file(s)`:`No Vite detected ${E("\u2192","->")} CSS will be generated as file(s)`,while:r(async()=>{},"while")})}return t}r(Bn,"buildDetectionTasks");async function Vn(e){if(e.tasks.push({pending:e.hasExistingTokens?"Process existing design tokens":"Add design tokens",start:e.hasExistingTokens?"Processing existing design tokens...":"Adding design tokens...",end:e.hasExistingTokens?"Design tokens processed":"Design tokens added",while:r(async()=>{await Un(e)},"while")}),!e.pluginToInstall)e.tasks.push({pending:"Generate CSS variables",start:"Generating CSS variables...",end:"CSS variables generated",while:r(async()=>{await jn(e)},"while")}),e.tasks.push({pending:"Generate CSS utilities",start:"Generating CSS utilities...",end:"CSS utilities generated",while:r(async()=>{await xn(e)},"while")});else if(e.pluginToInstall&&!H(e.pluginToInstall)){const t="Vite";e.tasks.push({pending:`Install ${t} plugin`,start:`Installing ${t} plugin...`,end:`${t} plugin installed`,while:r(async()=>{await Gn(e)},"while")})}Ze(e.options)?e.tasks.push({pending:"Write configuration file",start:"Writing configuration file...",end:"Configuration file written",while:r(async()=>{await Qe(e)},"while")}):e.tasks.push({pending:"Finalize setup",start:"Finalizing...",end:"Setup complete",while:r(async()=>{await Qe(e)},"while")})}r(Vn,"buildExecutionTasks");const Wn=new M().name("init").description("Initialize a new sugarcube project").option("--kit <kit>",`Starter kit to use (default: ${ce})`,ce).option("--tokens-dir <dir>","Design tokens directory (e.g., 'src/design-tokens')").option("--styles-dir <dir>","Styles output directory (e.g., 'src/styles')").option("--variables-dir <dir>","Token variables directory (e.g., 'src/styles/global')").option("--utilities-dir <dir>","Utilities directory (e.g., 'src/styles/utilities')").option("--fluid-min <number>","Minimum viewport width for fluid scaling (default: 320)").option("--fluid-max <number>","Maximum viewport width for fluid scaling (default: 1200)").option("--color-fallback <strategy>","Color fallback strategy: 'native' or 'polyfill' (default: native)").option("--skip-plugin","Don't install framework plugin").action(async e=>{let t;try{Dn(e),await Fn();const n=await On(e),s=await Tn(e),o=Re(s),i=An(e,n.hasExistingTokens,n.framework);t=await Mn(e,n,o,s,i),K(W("sugarcube")),await Nn();const a=Bn(t);a.length>0&&(S.message("Detecting project\u2026"),await S.tasks(a,{minDurationMs:1e3})),t.tasks=[],await Vn(t),t.tasks.length>0&&(S.message("Setting things up\u2026"),await S.tasks(t.tasks,{successMessage:"\u{1F389} Tasks completed successfully!"})),await Cn(t)}catch(n){z(n)}}),Yn=new M().name("validate").description("Validate design token files").argument("[paths...]","Token files or directories to validate (e.g., src/design-tokens)").action(async e=>{try{if(K(W("Validate")),!e.length)try{const{config:i}=await X();await V(i),te(c.greenBright("All tokens valid \u2728"));return}catch{throw new p(g.VALIDATE_NO_PATH_SPECIFIED())}for(const i of e)if(!D(i))throw new p(g.VALIDATE_PATH_NOT_FOUND(i));const n=(await ae(e.map(i=>i.endsWith(".json")?i:R(i,"**/*.json")),{absolute:!0})).filter(i=>!i.endsWith(".resolver.json"));if(n.length===0)throw new p(g.VALIDATE_NO_TOKEN_FILES());const s={};for(const i of n){const a=await Se(i,"utf-8"),l=N(process.cwd(),i);s[l]={content:a}}const o={output:_e.output,transforms:_e.transforms};await V(o,s),te(c.greenBright("All tokens valid \u2728"))}catch(t){z(t)}});process.on("SIGINT",()=>process.exit(0)),process.on("SIGTERM",()=>process.exit(0));async function Kn(){const e=new M().name("sugarcube").description("CLI for sugarcube").version(Tt.version,"-v, --version","display the version number");e.addCommand(Wn).addCommand(yn).addCommand(Yn).addCommand(cn).addCommand(ln),e.parse()}r(Kn,"main"),Kn();
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@sugarcube-org/cli",
|
|
3
|
-
"version": "0.0.0-alpha.
|
|
3
|
+
"version": "0.0.0-alpha.36",
|
|
4
4
|
"publishConfig": {
|
|
5
5
|
"access": "public",
|
|
6
6
|
"provenance": false
|
|
@@ -40,17 +40,17 @@
|
|
|
40
40
|
"@antfu/ni": "23.3.0",
|
|
41
41
|
"@clack/core": "1.0.0-alpha.3",
|
|
42
42
|
"@clack/prompts": "1.0.0-alpha.3",
|
|
43
|
-
"@sugarcube-org/core": "0.1.0-alpha.
|
|
43
|
+
"@sugarcube-org/core": "0.1.0-alpha.20",
|
|
44
44
|
"@unocss/core": "66.5.2",
|
|
45
45
|
"commander": "12.1.0",
|
|
46
46
|
"execa": "9.5.2",
|
|
47
|
-
"fast-glob": "3.3.2",
|
|
48
47
|
"fast-wrap-ansi": "0.1.3",
|
|
49
48
|
"get-tsconfig": "4.7.2",
|
|
50
49
|
"is-unicode-supported": "2.1.0",
|
|
51
50
|
"log-update": "6.1.0",
|
|
52
51
|
"pathe": "2.0.3",
|
|
53
52
|
"picocolors": "1.1.1",
|
|
53
|
+
"tinyglobby": "^0.2.9",
|
|
54
54
|
"zod": "^3.23.8"
|
|
55
55
|
},
|
|
56
56
|
"devDependencies": {
|