@sugarcube-org/core 0.0.1-alpha.4 → 0.0.1-alpha.6

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.js CHANGED
@@ -1,23 +1,42 @@
1
- var $e=Object.defineProperty;var o=(e,t)=>$e(e,"name",{value:t,configurable:!0});import{readFile as ye}from"node:fs/promises";import Ae from"fast-glob";import Ee,{relative as L}from"node:path";import{converter as _,formatHex8 as Te,formatHex as z}from"culori";import T from"path";import Ne,{mkdir as be,readFile as Y,writeFile as B}from"fs/promises";import{existsSync as H}from"fs";import{z as m}from"zod";const u={LOAD:{NO_FILES_FOUND:o(e=>`No files found matching pattern: ${e}.`,"NO_FILES_FOUND"),INVALID_JSON:o((e,t)=>`Invalid JSON in file ${e}: ${t}`,"INVALID_JSON"),GLOB_ERROR:o((e,t)=>`Error resolving glob pattern ${e}: ${t}`,"GLOB_ERROR")},FLATTEN:{INVALID_TOKEN_NAME:o(e=>`Invalid token name "${e}": Token names cannot contain dots (.), curly braces ({,}), or other special characters`,"INVALID_TOKEN_NAME"),MISSING_DOLLAR_PREFIX:o(e=>`Token at ${e} is using 'value' or 'type' without the required '$' prefix. Use '$value' and '$type' instead.`,"MISSING_DOLLAR_PREFIX")},METADATA:{COLLECTION_ERROR:o(e=>`Error collecting metadata: ${e}`,"COLLECTION_ERROR"),INVALID_EXTENSIONS:o(e=>`Invalid extensions at ${e}: expected object, got ${typeof e}`,"INVALID_EXTENSIONS"),INVALID_DESCRIPTION:o(e=>`Invalid description at ${e}: expected string, got ${typeof e}`,"INVALID_DESCRIPTION")},VALIDATE:{MISSING_TYPE:o(e=>`Token at '${e}' is missing the "$type" property`,"MISSING_TYPE"),UNKNOWN_TOKEN_TYPE:o((e,t)=>`Unknown token type '${e}' at ${t}. Valid types are: color, dimension, fontFamily, fontWeight, duration, cubicBezier, strokeStyle, border, transition, shadow, gradient, typography`,"UNKNOWN_TOKEN_TYPE"),INVALID_COLOR:o((e,t)=>`Invalid color at ${t}: '${e}'. Color should be a valid hex value`,"INVALID_COLOR"),INVALID_DIMENSION:o((e,t)=>`Invalid dimension at '${t}': ${e}. Dimensions should have a numeric value and unit, like { "value": 16, "unit": "px" }`,"INVALID_DIMENSION"),INVALID_DIMENSION_UNIT:o((e,t)=>`Invalid unit at ${t}': '${e}'. Unit must be either "px" or "rem"`,"INVALID_DIMENSION_UNIT"),INVALID_FONT_FAMILY:o((e,t)=>`Invalid font family at '${t}': ${e}. Should be a string or array of strings, like "Arial" or ["Arial", "sans-serif"]`,"INVALID_FONT_FAMILY"),INVALID_FONT_WEIGHT:o((e,t)=>`Invalid font weight at '${t}': ${e}. Should be a number between 1-1000 or a keyword like "thin", "light", "normal", "bold"`,"INVALID_FONT_WEIGHT"),INVALID_DURATION:o((e,t)=>`Invalid duration at '${t}': ${e}. Should be like { "value": 300, "unit": "ms" }`,"INVALID_DURATION"),INVALID_DURATION_UNIT:o((e,t)=>`Invalid unit at ${t}: "${e}". Unit must be "ms" or "s"`,"INVALID_DURATION_UNIT"),INVALID_CUBIC_BEZIER:o((e,t)=>`Invalid cubic bezier at ${t}: "${e}". Should be an array of 4 numbers between 0 and 1`,"INVALID_CUBIC_BEZIER"),INVALID_STROKE_STYLE:o((e,t)=>`Invalid stroke style at ${t}: "${e}". Should be "solid", "dashed", "dotted", etc.`,"INVALID_STROKE_STYLE"),INVALID_STROKE_LINE_CAP:o((e,t)=>`Invalid line cap at ${t}: "${e}". Should be one of: round, butt, square`,"INVALID_STROKE_LINE_CAP"),INVALID_BORDER:o((e,t)=>`Invalid border at ${t}: "${e}". Should have color, width, and style properties`,"INVALID_BORDER"),INVALID_SHADOW:o((e,t)=>`Invalid shadow at ${t}: "${e}". Should have color, offsetX, offsetY properties (blur and spread are optional)`,"INVALID_SHADOW"),INVALID_SHADOW_INSET:o((e,t)=>`Invalid inset value at ${t}: "${e}". Should be true or false`,"INVALID_SHADOW_INSET"),INVALID_TRANSITION:o((e,t)=>`Invalid transition at ${t}: "${e}". Should have duration, delay, and timingFunction properties`,"INVALID_TRANSITION"),INVALID_GRADIENT:o((e,t)=>`Invalid gradient at ${t}: "${e}". Should be an array of color stops with position values between 0 and 1`,"INVALID_GRADIENT"),INVALID_GRADIENT_STOP_POSITION:o((e,t)=>`Invalid gradient stop position at ${t}: "${e}". Position must be between 0 and 1`,"INVALID_GRADIENT_STOP_POSITION"),INVALID_TYPOGRAPHY:o((e,t)=>`Invalid typography at ${t}: "${e}". Should have fontFamily and fontSize (fontWeight, letterSpacing, and lineHeight are optional)`,"INVALID_TYPOGRAPHY"),MISSING_REQUIRED_PROPERTY:o((e,t)=>`Missing required property '${e}' at ${t}`,"MISSING_REQUIRED_PROPERTY"),INVALID_NUMBER:o((e,t)=>`Invalid number at ${t}: "${e}". Expected a number value`,"INVALID_NUMBER"),INVALID_ARRAY:o((e,t)=>`Invalid array at ${t}: "${e}". Expected an array value`,"INVALID_ARRAY"),MISSING_FLUID_CONFIG:o(e=>`Missing fluid configuration. Token at ${e} requires fluid viewport settings.`,"MISSING_FLUID_CONFIG"),INVALID_FLUID_DIMENSION:o((e,t)=>`Invalid fluid dimension at ${t}: "${e}". Fluid dimensions should have min and max values, like { "min": { "value": 16, "unit": "px" }, "max": { "value": 24, "unit": "px" } }`,"INVALID_FLUID_DIMENSION"),INVALID_VIEWPORT_CONFIG:o((e,t)=>`Invalid viewport configuration at ${t}: "${e}". Viewport config should have min and max dimension values`,"INVALID_VIEWPORT_CONFIG"),MISMATCHED_UNITS:o((e,t,n)=>`Mismatched units at ${n}: min uses '${e}', max uses '${t}'. Both values must use the same unit`,"MISMATCHED_UNITS"),INVALID_FLUID_VALUE_RANGE:o(e=>`Invalid fluid value range at ${e}: min value must be less than max value`,"INVALID_FLUID_VALUE_RANGE"),INVALID_TOKEN_TYPE:o((e,t,n)=>`Invalid token type at ${n}: expected ${e}, got ${t}`,"INVALID_TOKEN_TYPE"),INVALID_TYPE:o((e,t,n)=>`Expected ${e}, received ${typeof t} at ${n}`,"INVALID_TYPE"),INVALID_ENUM_VALUE:o((e,t,n)=>`Expected value to be one of [${e.join(", ")}], but got ${String(t)} at ${n}`,"INVALID_ENUM_VALUE")},RESOLVE:{CIRCULAR_REFERENCE:o((e,t)=>`Circular reference detected: ${e} -> ${t}`,"CIRCULAR_REFERENCE"),REFERENCE_NOT_FOUND:o((e,t)=>`Reference not found: ${e} in ${t}`,"REFERENCE_NOT_FOUND"),TYPE_MISMATCH:o(e=>`Type mismatch in ${e}`,"TYPE_MISMATCH")},GENERATE:{INVALID_CSS_VALUE:o((e,t)=>`Invalid CSS value for property '${e}': ${t}`,"INVALID_CSS_VALUE"),INVALID_VARIABLE_NAME:o((e,t)=>`Invalid CSS variable name at '${e}': ${t}`,"INVALID_VARIABLE_NAME")},CONFIG:{INVALID_JSON:o(e=>`Invalid JSON in config file: ${e}`,"INVALID_JSON"),INVALID_CONFIG:o((e,t)=>`Invalid configuration at ${e}: ${t}`,"INVALID_CONFIG"),DUPLICATE_FILENAMES:o((e,t,n)=>`Duplicate filename "${t}" found in collection "${e}":
2
- ${n.map(r=>` - ${r}`).join(`
3
- `)}`,"DUPLICATE_FILENAMES"),FILE_NOT_FOUND:o(e=>`Cannot read config file at ${e} - check file permissions and path`,"FILE_NOT_FOUND")}};async function q(e){const t={files:[],errors:[]};for(const n of e)try{const r=!n.includes("*")&&!n.endsWith(".json")?Ee.join(n,"**/*.json"):n,s=await Ae(r,{absolute:!0,onlyFiles:!0});if(s.length===0){t.errors.push({pattern:n,error:u.LOAD.NO_FILES_FOUND(n)});continue}t.files.push(...s)}catch(r){t.errors.push({pattern:n,error:u.LOAD.GLOB_ERROR(n,r instanceof Error?r.message:"Unknown error")})}return t}o(q,"resolveFiles");async function K(e){try{const t=await ye(e,"utf-8");return JSON.parse(t)}catch(t){throw t instanceof Error&&t instanceof SyntaxError?new Error(u.LOAD.INVALID_JSON(e,t.message)):t}}o(K,"loadTree");function Se(e){const t=new Set;return e.themes&&Object.values(e.themes).forEach(n=>{n.forEach(r=>t.add(r))}),t}o(Se,"collectThemePaths");async function O(e){const t=[],n=[],r=Array.isArray(e.tokens)?{default:{source:e.tokens,type:"custom"}}:"source"in e.tokens?{default:e.tokens}:e.tokens;for(const[s,i]of Object.entries(r)){const a=Se(i),{files:c,errors:l}=await q(Array.isArray(i.source)?i.source:[i.source]);if(l.length>0){t.push(...l.map(f=>({file:f.pattern,message:f.error})));continue}for(const f of c){const p=L(process.cwd(),f);if(!a.has(p))try{const d=await K(f),I={collection:s,tokens:d,sourcePath:p};n.push(I)}catch(d){t.push({file:f,message:d instanceof Error?d.message:"Unknown error"})}}if(i.themes)for(const[f,p]of Object.entries(i.themes))try{const{files:d,errors:I}=await q(p);if(I.length>0){t.push(...I.map(g=>({file:g.pattern,message:g.error})));continue}for(const g of d)try{const y=await K(g),A={collection:s,theme:f,tokens:y,sourcePath:L(process.cwd(),g)};n.push(A)}catch(y){t.push({file:g,message:y instanceof Error?y.message:"Unknown error"})}}catch(d){t.push({file:p.join(", "),message:d instanceof Error?d.message:"Unknown error"})}}return{trees:n,errors:t}}o(O,"loadTreesFromConfig");async function V(e){const t=[],n=[],r=new Map;for(const[s,{collection:i,theme:a,content:c}]of Object.entries(e)){r.has(i)||r.set(i,new Map);const l=r.get(i);l.has(a)||l.set(a,[]),l.get(a).push({content:c,path:s})}for(const[s,i]of r)for(const[a,c]of i)for(const{content:l,path:f}of c)try{const p=JSON.parse(l);t.push({collection:s,theme:a,tokens:p,sourcePath:L(process.cwd(),f)})}catch(p){p instanceof Error?p instanceof SyntaxError?n.push({file:f,message:u.LOAD.INVALID_JSON(f,p.message)}):n.push({file:f,message:p.message}):n.push({file:f,message:"Unknown error"})}return{trees:t,errors:n}}o(V,"loadTreesFromMemory");function De(e){if(typeof e!="object"||e===null||"$value"in e)return!1;const t="value"in e,n="type"in e;if(t&&n)return!0;if(t){const r=e.value;return typeof r=="string"||typeof r=="number"||Array.isArray(r)}return!1}o(De,"looksLikeUnprefixedToken");function Le(e,t){const n={tokens:{},pathIndex:new Map},r=[];function s(a=[]){const c=[t.collection];return t.theme&&c.push(t.theme),a.length>0&&c.push(a.join(".")),c.join(".")}o(s,"createLookupKey"),(e.$description||e.$extensions)&&(n.tokens[s()]={$description:e.$description,$extensions:e.$extensions});function i(a,c=[],l){if(c.length>0){const d=s(c);n.tokens[d]={$description:a.$description,$extensions:a.$extensions,$path:c.join("."),$source:{collection:t.collection,theme:t.theme,sourcePath:t.sourcePath}}}if("$value"in a)return;const f=a.$type||l,p=Object.keys(a).filter(d=>!d.startsWith("$"));for(const d of p){const I=a[d],g=[...c,d];if(De(I)){r.push({path:g.join("."),source:t,message:u.FLATTEN.MISSING_DOLLAR_PREFIX(g.join("."))});continue}if(d.includes(".")||d.includes("{")||d.includes("}")){r.push({path:g.join("."),source:t,message:u.FLATTEN.INVALID_TOKEN_NAME(d)});continue}if("$value"in I){const y=s(g),A=g.join(".");n.tokens[y]={...I,$type:I.$type||f,$path:A,$source:{collection:t.collection,theme:t.theme,sourcePath:t.sourcePath},$originalPath:A},n.pathIndex.set(A,y)}else i(I,g,f)}}return o(i,"processNode"),i(e),{tokens:n,errors:r}}o(Le,"flattenTree");function F(e){const t={tokens:{},pathIndex:new Map},n=[];for(const r of e){const{tokens:s,errors:i}=Le(r.tokens,{collection:r.collection,theme:r.theme,sourcePath:r.sourcePath});Object.assign(t.tokens,s.tokens);for(const[a,c]of s.pathIndex)t.pathIndex.set(a,c);n.push(...i)}return{tokens:t,errors:n}}o(F,"flatten");const _e={isObject:o(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObject")};function h(e){return typeof e=="string"&&e.startsWith("{")&&e.endsWith("}")}o(h,"isReference");function $(e,t,n,r){if(h(t))return[];switch(e.type){case"object":return Ve(e,t,n,r);case"union":return Fe(e,t,n,r);case"array":return ke(e,t,n,r);default:return Oe(e,t,n,r)}}o($,"validateSchema");function Oe(e,t,n,r){return typeof t!==e.type?[{path:n,message:e.errorMessage?.(t,n)||u.VALIDATE.INVALID_TYPE(e.type,t,n),source:r}]:e.validate?.(t,n,r)??[]}o(Oe,"validateSimpleValue");function Ve(e,t,n,r){if(!_e.isObject(t))return[{path:n,message:e.errorMessage?.(t,n)||u.VALIDATE.INVALID_TYPE("object",t,n),source:r}];const s=[],i=t;if(e.required)for(const a of e.required)a in i||s.push({path:`${n}.${a}`,message:u.VALIDATE.MISSING_REQUIRED_PROPERTY(a,n),source:r});for(const[a,c]of Object.entries(e.properties))a in i&&s.push(...$(c,i[a],`${n}.${a}`,r));return s}o(Ve,"validateObject");function Fe(e,t,n,r){let s=[],i=1/0;for(const a of e.oneOf){if(a.type==="string"&&typeof t!="string"||a.type==="object"&&typeof t!="object")continue;const c=$(a,t,n,r);if(c.length===0)return e.validate?.(t,n,r)??[];c.length<i&&(s=c,i=c.length)}return i===1/0?[{path:n,message:u.VALIDATE.INVALID_TYPE(e.oneOf.map(a=>a.type).join(" or "),t,n),source:r}]:s}o(Fe,"validateUnion");function ke(e,t,n,r){return Array.isArray(t)?e.validate?.(t,n,r)??[]:[{path:n,message:e.errorMessage?.(t,n)||u.VALIDATE.INVALID_TYPE("array",t,n),source:r}]}o(ke,"validateArray");const N={tokenType:"color",schema:{type:"string",errorMessage:o((e,t)=>u.VALIDATE.INVALID_COLOR(e,t),"errorMessage"),validate:o((e,t,n)=>/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/.test(e)?[]:[{path:t,message:u.VALIDATE.INVALID_COLOR(e,t),source:n}],"validate")}};function ve(e,t,n){return $(N.schema,e,t,n)}o(ve,"validateColor");const b={tokenType:"number",schema:{type:"number",errorMessage:o((e,t)=>u.VALIDATE.INVALID_NUMBER(e,t),"errorMessage"),validate:o((e,t,n)=>typeof e!="number"||isNaN(e)?[{path:t,message:u.VALIDATE.INVALID_NUMBER(e,t),source:n}]:[],"validate")}};function we(e,t,n){return $(b.schema,e,t,n)}o(we,"validateNumber");const E={tokenType:"dimension",schema:{type:"object",errorMessage:o((e,t)=>u.VALIDATE.INVALID_DIMENSION(e,t),"errorMessage"),properties:{value:b.schema,unit:{type:"string",validate:o((e,t,n)=>typeof e!="string"||!["px","rem"].includes(e)?[{path:t,message:u.VALIDATE.INVALID_DIMENSION_UNIT(e,t),source:n}]:[],"validate")}},required:["value","unit"]}};function xe(e,t,n){return $(E.schema,e,t,n)}o(xe,"validateDimension");const X={tokenType:"fontFamily",schema:{type:"union",oneOf:[{type:"string",errorMessage:o((e,t)=>u.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage")},{type:"array",errorMessage:o((e,t)=>u.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage"),validate:o((e,t,n)=>e.every(s=>typeof s=="string")?[]:[{path:t,message:u.VALIDATE.INVALID_FONT_FAMILY(e,t),source:n}],"validate")}],errorMessage:o((e,t)=>u.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage")}};function Ce(e,t,n){return $(X.schema,e,t,n)}o(Ce,"validateFontFamily");const Re=["thin","hairline","extra-light","ultra-light","light","normal","regular","book","medium","semi-bold","demi-bold","bold","extra-bold","ultra-bold","black","heavy","extra-black","ultra-black"],J={tokenType:"fontWeight",schema:{type:"union",errorMessage:o((e,t)=>u.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),oneOf:[{type:"number",errorMessage:o((e,t)=>u.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),validate:o((e,t,n)=>e<1||e>1e3?[{path:t,message:u.VALIDATE.INVALID_FONT_WEIGHT(e,t),source:n}]:[],"validate")},{type:"string",errorMessage:o((e,t)=>u.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),validate:o((e,t,n)=>Re.includes(e.toLowerCase())?[]:[{path:t,message:u.VALIDATE.INVALID_FONT_WEIGHT(e,t),source:n}],"validate")}]}};function je(e,t,n){return $(J.schema,e,t,n)}o(je,"validateFontWeight");const Me=["ms","s"],k={tokenType:"duration",schema:{type:"object",errorMessage:o((e,t)=>u.VALIDATE.INVALID_DURATION(e,t),"errorMessage"),properties:{value:b.schema,unit:{type:"string",validate:o((e,t,n)=>Me.includes(e)?[]:[{path:t,message:u.VALIDATE.INVALID_DURATION_UNIT(e,t),source:n}],"validate")}},required:["value","unit"]}};function Pe(e,t,n){return $(k.schema,e,t,n)}o(Pe,"validateDuration");const Z={tokenType:"cubicBezier",schema:{type:"array",errorMessage:o((e,t)=>u.VALIDATE.INVALID_CUBIC_BEZIER(e,t),"errorMessage"),validate:o((e,t,n)=>{const r=e;if(r.length!==4||!r.every(a=>typeof a=="number"))return[{path:t,message:u.VALIDATE.INVALID_CUBIC_BEZIER(e,t),source:n}];const[s,,i]=r;return s<0||s>1||i<0||i>1?[{path:t,message:u.VALIDATE.INVALID_CUBIC_BEZIER(e,t),source:n}]:[]},"validate")}};function Ue(e,t,n){return $(Z.schema,e,t,n)}o(Ue,"validateCubicBezier");const Ge={tokenType:"typography",schema:{type:"object",properties:{fontFamily:X.schema,fontSize:E.schema,letterSpacing:E.schema,lineHeight:b.schema,fontWeight:J.schema},required:["fontFamily","fontSize"],errorMessage:o((e,t)=>u.VALIDATE.INVALID_TYPOGRAPHY(e,t),"errorMessage")}};function We(e,t,n){return $(Ge.schema,e,t,n)}o(We,"validateTypography");const ze=["solid","dashed","dotted","double","groove","ridge","outset","inset"],Ye=["round","butt","square"],Be={type:"object",errorMessage:o((e,t)=>u.VALIDATE.INVALID_STROKE_STYLE(e,t),"errorMessage"),properties:{dashArray:{type:"array",validate:o((e,t,n)=>{const r=e,s=[];return r.forEach((i,a)=>{typeof i!="string"&&s.push(...$(E.schema,i,`${t}.${a}`,n))}),s},"validate")},lineCap:{type:"string",validate:o((e,t,n)=>Ye.includes(e)?[]:[{path:t,message:u.VALIDATE.INVALID_STROKE_LINE_CAP(e,t),source:n}],"validate")}},required:["dashArray","lineCap"]},Q={tokenType:"strokeStyle",schema:{type:"union",oneOf:[{type:"string",validate:o((e,t,n)=>!ze.includes(e)&&typeof e=="string"?[{path:t,message:u.VALIDATE.INVALID_STROKE_STYLE(e,t),source:n}]:[],"validate")},Be]}};function He(e,t,n){return $(Q.schema,e,t,n)}o(He,"validateStrokeStyle");const qe={tokenType:"border",schema:{type:"object",properties:{color:N.schema,width:E.schema,style:Q.schema},required:["color","width","style"],errorMessage:o((e,t)=>u.VALIDATE.INVALID_BORDER(e,t),"errorMessage")}};function Ke(e,t,n){return $(qe.schema,e,t,n)}o(Ke,"validateBorder");const Xe={tokenType:"transition",schema:{type:"object",properties:{duration:k.schema,delay:k.schema,timingFunction:Z.schema},required:["duration","delay","timingFunction"],errorMessage:o((e,t)=>u.VALIDATE.INVALID_TRANSITION(e,t),"errorMessage")}};function Je(e,t,n){return $(Xe.schema,e,t,n)}o(Je,"validateTransition");const ee={tokenType:"shadow",schema:{type:"object",properties:{color:N.schema,offsetX:E.schema,offsetY:E.schema,blur:E.schema,spread:E.schema,inset:{type:"boolean",errorMessage:o((e,t)=>u.VALIDATE.INVALID_SHADOW_INSET(e,t),"errorMessage")}},required:["color","offsetX","offsetY","blur","spread"],errorMessage:o((e,t)=>u.VALIDATE.INVALID_SHADOW(e,t),"errorMessage")}};function Ze(e,t,n){const r=[];return Array.isArray(e)?(e.forEach((s,i)=>{r.push(...$(ee.schema,s,`${t}[${i}]`,n))}),r):$(ee.schema,e,t,n)}o(Ze,"validateShadow");const Qe={type:"object",errorMessage:o((e,t)=>u.VALIDATE.INVALID_GRADIENT(e,t),"errorMessage"),properties:{color:{type:"string",validate:N.schema.validate},position:{type:"number",validate:o((e,t,n)=>e<0||e>1?[{path:t,message:u.VALIDATE.INVALID_GRADIENT_STOP_POSITION(e,t),source:n}]:[],"validate")}},required:["color","position"]},et={tokenType:"gradient",schema:{type:"array",errorMessage:o((e,t)=>u.VALIDATE.INVALID_ARRAY(e,t),"errorMessage"),validate:o((e,t,n)=>{const r=e,s=[];return r.forEach((i,a)=>{s.push(...$(Qe,i,`${t}[${a}]`,n))}),s},"validate")}};function tt(e,t,n){return $(et.schema,e,t,n)}o(tt,"validateGradient");const nt={tokenType:"fluidDimension",schema:{type:"object",errorMessage:o((e,t)=>u.VALIDATE.INVALID_FLUID_DIMENSION(e,t),"errorMessage"),properties:{min:E.schema,max:E.schema},required:["min","max"]}};function rt(e,t,n){return $(nt.schema,e,t,n)}o(rt,"validateFluidDimension");const ot={color:ve,dimension:xe,fluidDimension:rt,duration:Pe,cubicBezier:Ue,fontFamily:Ce,fontWeight:je,number:we,strokeStyle:He,typography:We,border:Ke,shadow:Ze,gradient:tt,transition:Je};function v(e){const t=[];for(const[n,r]of Object.entries(e.tokens)){if(typeof r!="object"||r===null||!("$type"in r)||!("$path"in r)||r.$path.startsWith("$"))continue;if(!("$value"in r)){t.push({path:r.$path,message:u.VALIDATE.MISSING_REQUIRED_PROPERTY("$value",r.$path),source:r.$source});continue}const s=ot[r.$type];if(!s){t.push({path:r.$path,message:u.VALIDATE.UNKNOWN_TOKEN_TYPE(r.$type,r.$path),source:r.$source});continue}const i=r;t.push(...s(i.$value,i.$path,i.$source))}return t}o(v,"validate");function S(e,t,n,r){return typeof t=="string"&&h(t)?st(e,t,n,r):Array.isArray(t)?t.map(s=>S(e,s,n,r)):typeof t=="object"&&t!==null?Object.entries(t).reduce((i,[a,c])=>({...i,[a]:S(`${e}.${a}`,c,n,r)}),{}):t}o(S,"resolveValue");function w(e){const t={},n=new Set,r=[];for(const[s,i]of Object.entries(e.tokens))try{if(!("$value"in i)){t[s]=i;continue}const a=i;t[s]={...a,$resolvedValue:S(a.$path,a.$value,e,n)}}catch(a){const c=a instanceof Error?a.message:String(a),l=i,f=l.$path,p=l.$source;let d,I;c.includes("Circular reference detected")?(d="circular",I=c):c.includes("Reference not found")?(d="missing",I=c):(d="type-mismatch",I=u.RESOLVE.TYPE_MISMATCH(f)),r.push({type:d,path:f,source:p,message:I})}return{resolved:t,errors:r}}o(w,"resolve");function st(e,t,n,r){const s=t.slice(1,-1),i=n.pathIndex.get(s);if(!i)throw new Error(u.RESOLVE.REFERENCE_NOT_FOUND(s,e));if(r.has(i)){const l=n.tokens[i];throw!l||!("$path"in l)?new Error(u.RESOLVE.REFERENCE_NOT_FOUND(s,e)):new Error(u.RESOLVE.CIRCULAR_REFERENCE(e,l.$path))}const a=n.tokens[i];if(!a||!("$value"in a))throw new Error(u.RESOLVE.REFERENCE_NOT_FOUND(s,e));r.add(i);const c=S(i,a.$value,n,r);return r.delete(i),c}o(st,"resolveReferenceChain");function x(e,t){const n=new Map;for(const[r,s]of Object.entries(t)){if(!("$source"in s)){for(const l of e){const f=l.collection;n.has(f)||n.set(f,new Map);const p=n.get(f),d=l.theme;p.has(d)||p.set(d,{}),p.get(d)[r]=s}continue}const i=s.$source.collection,a=s.$source.theme;n.has(i)||n.set(i,new Map);const c=n.get(i);c.has(void 0)||c.set(void 0,{}),a||(c.get(void 0)[r]=s),a&&(c.has(a)||c.set(a,{}),c.get(a)[r]=s)}return e.map(r=>{const s=n.get(r.collection);if(!s)return{collection:r.collection,theme:r.theme,tokens:{}};if(r.theme){const i=s.get(r.theme)||{};return{collection:r.collection,theme:r.theme,tokens:i}}else{const i=s.get(void 0)||{};return{collection:r.collection,theme:r.theme,tokens:i}}})}o(x,"processTrees");function D(e){return["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","emoji","math","fangsong"].includes(e.toLowerCase())?e:/[\s'"!@#$%^&*()=+[\]{};:|\\/,.<>?~]/.test(e)?`"${e}"`:e}o(D,"quoteFont");const it={thin:100,hairline:100,"extra-light":200,"ultra-light":200,light:300,normal:400,regular:400,book:400,medium:500,"semi-bold":600,"demi-bold":600,bold:700,"extra-bold":800,"ultra-bold":800,black:900,heavy:900,"extra-black":950,"ultra-black":950};function te(e){return h(e)?{value:e}:typeof e=="number"?{value:e}:{value:it[e.toLowerCase()]??e}}o(te,"convertFontWeightToken");function at(e){if(h(e))return{"font-family":e,"font-size":e};const t={"font-family":h(e.fontFamily)?e.fontFamily:Array.isArray(e.fontFamily)?e.fontFamily.map(n=>D(n)).join(", "):D(e.fontFamily),"font-size":h(e.fontSize)?e.fontSize:`${e.fontSize.value}${e.fontSize.unit}`};return e.fontWeight&&(t["font-weight"]=h(e.fontWeight)?e.fontWeight:te(e.fontWeight).value),e.letterSpacing&&(t["letter-spacing"]=h(e.letterSpacing)?e.letterSpacing:`${e.letterSpacing.value}${e.letterSpacing.unit}`),e.lineHeight&&(t["line-height"]=(h(e.lineHeight),e.lineHeight)),t}o(at,"convertTypographyToken");function ne(e){return e?`${e.value}${e.unit}`:"0ms"}o(ne,"formatDuration");function ct(e){if(h(e))return{value:e};const t=h(e.duration)?e.duration:ne(e.duration),n=h(e.timingFunction)?e.timingFunction:`cubic-bezier(${e.timingFunction.join(", ")})`,r=e.delay&&(h(e.delay)?e.delay:ne(e.delay));return{value:[t,n,r].filter(Boolean).join(" ")}}o(ct,"convertTransitionToken");function lt(e){return h(e)?{value:e}:{value:`cubic-bezier(${e.join(", ")})`}}o(lt,"convertCubicBezierToken");function ut(e){return h(e)?{value:e}:{value:e}}o(ut,"convertNumberToken");function ft(e){return h(e)?{value:e}:{value:`${e.value}${e.unit}`}}o(ft,"convertDurationToken");function re(e){return h(e)?{value:e}:typeof e=="string"?{value:e}:{value:`${e.dashArray.map(n=>h(n)?n:`${n.value}${n.unit}`).join(" ")} ${e.lineCap}`}}o(re,"convertStrokeStyleToken");function dt(e){if(h(e))return{value:e};const t=h(e.width)?e.width:`${e.width.value}${e.width.unit}`,n=(h(e.color),e.color),r=typeof e.style=="string"?e.style:re(e.style).value;return{value:`${t} ${r} ${n}`}}o(dt,"convertBorderToken");function oe(e){const t=h(e.offsetX)?e.offsetX:`${e.offsetX.value}${e.offsetX.unit}`,n=h(e.offsetY)?e.offsetY:`${e.offsetY.value}${e.offsetY.unit}`,r=h(e.blur)?e.blur:`${e.blur.value}${e.blur.unit}`,s=h(e.spread)?e.spread:`${e.spread.value}${e.spread.unit}`,i=(h(e.color),e.color);return`${e.inset?"inset ":""}${t} ${n} ${r} ${s} ${i}`}o(oe,"convertSingleShadow");function pt(e){return h(e)?{value:e}:Array.isArray(e)?{value:e.map(oe).join(", ")}:{value:oe(e)}}o(pt,"convertShadowToken");function ht(e){return h(e)?{value:e}:{value:`linear-gradient(${e.map(n=>{const r=(h(n.color),n.color),s=h(n.position)?n.position:`${n.position*100}`;return`${r} ${s}%`}).join(", ")})`}}o(ht,"convertGradientToken");function mt(e){return h(e)?{value:e}:{value:Array.isArray(e)?e.map(n=>D(n)).join(", "):D(e)}}o(mt,"convertFontFamilyToken");function It(e){return h(e)?{value:e}:{value:`${e.value}${e.unit}`}}o(It,"convertDimensionToken");function se(e,t=16){return e.unit==="px"?e.value:e.value*t}o(se,"normalizeToPixels");function gt(e,t){const{min:n,max:r}=e,s=t.fluidConfig;if(!s)throw new Error(u.VALIDATE.MISSING_FLUID_CONFIG(t.path??""));const i=16,a=se(n,i),c=se(r,i),l=s.min,f=s.max;if(a===c)return{value:`${a/i}rem`};const p=a/i,d=c/i,I=l/i,g=f/i,y=(d-p)/(g-I),A=-1*I*y+p;return{value:`clamp(${p}rem, ${A.toFixed(2)}rem + ${(y*100).toFixed(2)}vw, ${d}rem)`}}o(gt,"convertFluidDimension");function $t(e,t){if(h(e))return{value:e};if(!t.fluidConfig)throw new Error(u.VALIDATE.MISSING_FLUID_CONFIG(t.path??""));return gt(e,t)}o($t,"convertFluidDimensionToken");function C(e){return e===1?"1":e===0?"0":e.toFixed(2)}o(C,"formatAlpha");function R(e,t){try{const n=t==="rgba"?"rgb":t==="hsla"?"hsl":t,r=_(n==="hex"?"rgb":n)(e);if(!r)throw new Error(`Failed to convert color ${e} to ${t}`);switch(n){case"hsl":{if(r.mode!=="hsl")throw new Error("Unexpected color mode");const s=Math.round(r.h??0),i=Math.round((r.s??0)*100),a=Math.round((r.l??0)*100),c=r.alpha;return c!==void 0?`hsl(${s} ${i}% ${a}% / ${C(c)})`:`hsl(${s} ${i}% ${a}%)`}case"oklch":{if(r.mode!=="oklch")throw new Error("Unexpected color mode");const s=r.l??0,i=r.c??0,a=r.h??0,c=r.alpha;return c!==void 0?`oklch(${s.toFixed(3)} ${i.toFixed(3)} ${a.toFixed(1)} / ${c.toFixed(2)})`:`oklch(${s.toFixed(3)} ${i.toFixed(3)} ${a.toFixed(1)})`}case"rgb":{if(r.mode!=="rgb")throw new Error("Unexpected color mode");const s=Math.round((r.r??0)*255),i=Math.round((r.g??0)*255),a=Math.round((r.b??0)*255),c=r.alpha;return c!==void 0?`rgb(${s} ${i} ${a} / ${C(c)})`:`rgb(${s} ${i} ${a})`}case"p3":{if(r.mode!=="p3")throw new Error("Unexpected color mode");const s=r.r??0,i=r.g??0,a=r.b??0,c=r.alpha;return c!==void 0?`color(display-p3 ${s.toFixed(6)} ${i.toFixed(6)} ${a.toFixed(6)} / ${C(c)})`:`color(display-p3 ${s.toFixed(6)} ${i.toFixed(6)} ${a.toFixed(6)})`}default:{const s=_("rgb")(r);return s?s.alpha!==void 0?Te(s):z(s):e}}}catch{const r=_("rgb")(e);return console.warn(`Failed to convert color ${e} to ${t}, falling back to hex`),r?z(r):e}}o(R,"convertHexToColorString");function yt(e,t){if(h(e))return{value:e};const n=t.colorFormat||"hex";try{const r=R(e,n);return n==="p3"?{value:R(e,"hex")||e,featureValues:[{query:"@supports (color: color(display-p3 1 1 1))",value:r||e}]}:{value:r||e}}catch{return console.warn(`Failed to convert color ${e} to ${n}, falling back to hex`),{value:R(e,"hex")}}}o(yt,"convertColorToken");const ie={duration:ft,number:ut,cubicBezier:lt,color:yt,dimension:It,fluidDimension:$t,typography:at,border:dt,shadow:pt,gradient:ht,transition:ct,strokeStyle:re,fontFamily:mt,fontWeight:te};function At(e,t){const n=ie[e.$type];return{...e.$description?{$description:e.$description}:{},...e.$extensions?{$extensions:e.$extensions}:{},$type:e.$type,$value:e.$value,$path:e.$path,$source:e.$source,$originalPath:e.$originalPath,$resolvedValue:e.$resolvedValue,$cssProperties:n(e.$value,t)}}o(At,"convertSingleToken");function ae(e,t){const n={};for(const[r,s]of Object.entries(e)){if(!s||typeof s!="object")continue;if(!("$type"in s)){n[r]={...s.$description?{$description:s.$description}:{},...s.$extensions?{$extensions:s.$extensions}:{}};continue}if(!ie[s.$type])continue;const i={fluidConfig:t.options?.fluid,colorFormat:t.options?.color,path:s.$path};n[r]=At(s,i)}return n}o(ae,"convertTokens");function j(e,t){const n={};for(const[r,s]of Object.entries(e)){const i={default:ae(s.default,t)};for(const[a,c]of Object.entries(s))a!=="default"&&(i[a]=ae(c,t));n[r]=i}return n}o(j,"convert");const ce=new Map;function Et(e){const t=ce.get(e);if(t)return t;const n=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase();return ce.set(e,n),n}o(Et,"toKebabCase");function M({collection:e,filename:t,separate:n,baseDir:r}){const s=`${t}.variables.css`;return e==="default"?`${r}/${s}`:`${r}/${e}/${s}`}o(M,"getOutputPath");const le="@supports (color: color(display-p3 1 1 1))";function Tt(e){return e.$type==="typography"}o(Tt,"isTypographyToken");function P(e){return e.split(".").join("-")}o(P,"formatCSSVarPath");function ue(e){return typeof e=="number"?e:typeof e!="string"?(console.warn("Unexpected value type in convertReferenceToCSSVar, got:",e),String(e)):e.replace(/\{([^}]+)\}/g,(t,n)=>`var(--${n.split(".").map(Et).join("-")})`)}o(ue,"convertReferenceToCSSVar");function Nt(e){const t=e.$cssProperties;if("value"in t)return{name:`--${P(e.$path)}`,value:ue(t.value)}}o(Nt,"generateSingleVariable");function bt(e){return Object.entries(e.$cssProperties).filter(([t,n])=>n!==void 0).map(([t,n])=>({name:`--${P(e.$path)}-${t}`,value:ue(n)}))}o(bt,"generateTypographyVariables");function fe(e){if(e.$type!=="color")return[];const t=e.$cssProperties;return"featureValues"in t?t.featureValues?.filter(n=>n.query===le).map(n=>({name:`--${P(e.$path)}`,value:n.value}))??[]:[]}o(fe,"generateFeatureVariables");function de(e){const t=[`${e.selector} {`];if(e.comment&&t.push(` /* ${e.comment} */`),e.vars.length>0){const n=e.vars.map(r=>` ${r.name}: ${r.value};`).join(`
1
+ var je=Object.defineProperty;var r=(e,t)=>je(e,"name",{value:t,configurable:!0});import{converter as P,formatHex8 as Me,formatHex as ne}from"culori";import _,{readFile as U,mkdir as oe,writeFile as re}from"node:fs/promises";import D,{relative as G}from"node:path";import B from"fast-glob";import{z as l}from"zod";import{existsSync as O}from"node:fs";import{normalize as se,join as E,relative as Y,basename as Pe}from"pathe";function I(e){return typeof e=="string"&&e.startsWith("{")&&e.endsWith("}")}r(I,"isReference");function Ue(e){if(typeof e!="object"||e===null||!("$value"in e))return!1;const t=e.$value;return typeof t=="object"&&t!==null&&!Array.isArray(t)&&Object.keys(t).length>0}r(Ue,"isCompositeToken");function ie(e){return I(e)?{value:e}:typeof e=="string"?{value:e}:{value:`${e.dashArray.map(n=>I(n)?n:`${n.value}${n.unit}`).join(" ")} ${e.lineCap}`}}r(ie,"convertStrokeStyleToken");function Ge(e){if(I(e))return{value:e};const t=I(e.width)?e.width:`${e.width.value}${e.width.unit}`,n=(I(e.color),e.color),o=typeof e.style=="string"?e.style:ie(e.style).value;return{value:`${t} ${o} ${n}`}}r(Ge,"convertBorderToken");function W(e){return e===1?"1":e===0?"0":e.toFixed(2)}r(W,"formatAlpha");function z(e,t){try{const n=t==="rgba"?"rgb":t==="hsla"?"hsl":t,o=P(n==="hex"?"rgb":n)(e);if(!o)throw new Error(`Failed to convert color ${e} to ${t}`);switch(n){case"hsl":{if(o.mode!=="hsl")throw new Error("Unexpected color mode");const s=Math.round(o.h??0),i=Math.round((o.s??0)*100),a=Math.round((o.l??0)*100),c=o.alpha;return c!==void 0?`hsl(${s} ${i}% ${a}% / ${W(c)})`:`hsl(${s} ${i}% ${a}%)`}case"oklch":{if(o.mode!=="oklch")throw new Error("Unexpected color mode");const s=o.l??0,i=o.c??0,a=o.h??0,c=o.alpha;return c!==void 0?`oklch(${s.toFixed(3)} ${i.toFixed(3)} ${a.toFixed(1)} / ${c.toFixed(2)})`:`oklch(${s.toFixed(3)} ${i.toFixed(3)} ${a.toFixed(1)})`}case"rgb":{if(o.mode!=="rgb")throw new Error("Unexpected color mode");const s=Math.round((o.r??0)*255),i=Math.round((o.g??0)*255),a=Math.round((o.b??0)*255),c=o.alpha;return c!==void 0?`rgb(${s} ${i} ${a} / ${W(c)})`:`rgb(${s} ${i} ${a})`}case"p3":{if(o.mode!=="p3")throw new Error("Unexpected color mode");const s=o.r??0,i=o.g??0,a=o.b??0,c=o.alpha;return c!==void 0?`color(display-p3 ${s.toFixed(6)} ${i.toFixed(6)} ${a.toFixed(6)} / ${W(c)})`:`color(display-p3 ${s.toFixed(6)} ${i.toFixed(6)} ${a.toFixed(6)})`}default:{const s=P("rgb")(o);return s?s.alpha!==void 0?Me(s):ne(s):e}}}catch{const o=P("rgb")(e);return console.warn(`Failed to convert color ${e} to ${t}, falling back to hex`),o?ne(o):e}}r(z,"convertHexToColorString");function Be(e,t){if(I(e))return{value:e};const n=t.colorFormat||"hex";try{const o=z(e,n);return n==="p3"?{value:z(e,"hex")||e,featureValues:[{query:"@supports (color: color(display-p3 1 1 1))",value:o||e}]}:{value:o||e}}catch{return console.warn(`Failed to convert color ${e} to ${n}, falling back to hex`),{value:z(e,"hex")}}}r(Be,"convertColorToken");function Ye(e){return I(e)?{value:e}:{value:`cubic-bezier(${e.join(", ")})`}}r(Ye,"convertCubicBezierToken");function We(e){return I(e)?{value:e}:{value:`${e.value}${e.unit}`}}r(We,"convertDimensionToken");function ze(e){return I(e)?{value:e}:{value:`${e.value}${e.unit}`}}r(ze,"convertDurationToken");const F="_sugarcube.css",H="global",ae="utilities",b=".variables.css",He=".tokens.json",K="tokens",ce="utilities.css",Ke="src/styles",qe="src/design-tokens",S="sugarcube.config.json",u={LOAD:{NO_FILES_FOUND:r(e=>`No files found matching pattern: ${e}.`,"NO_FILES_FOUND"),INVALID_JSON:r((e,t)=>`Invalid JSON in file ${e}: ${t}`,"INVALID_JSON"),GLOB_ERROR:r((e,t)=>`Error resolving glob pattern ${e}: ${t}`,"GLOB_ERROR")},FLATTEN:{INVALID_TOKEN_NAME:r(e=>`Invalid token name "${e}": Token names cannot contain dots (.), curly braces ({,}), or other special characters`,"INVALID_TOKEN_NAME"),MISSING_DOLLAR_PREFIX:r(e=>`Token at ${e} is using 'value' or 'type' without the required '$' prefix. Use '$value' and '$type' instead.`,"MISSING_DOLLAR_PREFIX"),INVALID_TOKEN_NESTING:r(e=>`Token at "${e}" cannot contain child tokens or groups. Only metadata properties (starting with $) are allowed.`,"INVALID_TOKEN_NESTING"),COMPOSITE_TOKEN_MISSING_TYPE:r(e=>`Composite token at '${e}' is missing the required "$type" property. Composite tokens (tokens with object values) must specify their type to define their structure.`,"COMPOSITE_TOKEN_MISSING_TYPE")},METADATA:{COLLECTION_ERROR:r(e=>`Error collecting metadata: ${e}`,"COLLECTION_ERROR"),INVALID_EXTENSIONS:r(e=>`Invalid extensions at ${e}: expected object, got ${typeof e}`,"INVALID_EXTENSIONS"),INVALID_DESCRIPTION:r(e=>`Invalid description at ${e}: expected string, got ${typeof e}`,"INVALID_DESCRIPTION")},VALIDATE:{MISSING_TYPE:r(e=>`Token at '${e}' is missing the "$type" property`,"MISSING_TYPE"),UNKNOWN_TOKEN_TYPE:r((e,t)=>`Unknown token type '${e}' at ${t}. Valid types are: color, dimension, fontFamily, fontWeight, duration, cubicBezier, strokeStyle, border, transition, shadow, gradient, typography`,"UNKNOWN_TOKEN_TYPE"),INVALID_COLOR:r((e,t)=>`Invalid color at ${t}: '${e}'. Color should be a valid hex value`,"INVALID_COLOR"),INVALID_DIMENSION:r((e,t)=>`Invalid dimension at '${t}': ${e}. Dimensions should have a numeric value and unit, like { "value": 16, "unit": "px" }`,"INVALID_DIMENSION"),INVALID_DIMENSION_UNIT:r((e,t)=>`Invalid unit at ${t}': '${e}'. Unit must be either "px" or "rem"`,"INVALID_DIMENSION_UNIT"),INVALID_FONT_FAMILY:r((e,t)=>`Invalid font family at '${t}': ${e}. Should be a string or array of strings, like "Arial" or ["Arial", "sans-serif"]`,"INVALID_FONT_FAMILY"),INVALID_FONT_WEIGHT:r((e,t)=>`Invalid font weight at '${t}': ${e}. Should be a number between 1-1000 or a keyword like "thin", "light", "normal", "bold"`,"INVALID_FONT_WEIGHT"),INVALID_DURATION:r((e,t)=>`Invalid duration at '${t}': ${e}. Should be like { "value": 300, "unit": "ms" }`,"INVALID_DURATION"),INVALID_DURATION_UNIT:r((e,t)=>`Invalid unit at ${t}: "${e}". Unit must be "ms" or "s"`,"INVALID_DURATION_UNIT"),INVALID_CUBIC_BEZIER:r((e,t)=>`Invalid cubic bezier at ${t}: "${e}". Should be an array of 4 numbers between 0 and 1`,"INVALID_CUBIC_BEZIER"),INVALID_STROKE_STYLE:r((e,t)=>`Invalid stroke style at ${t}: "${e}". Should be "solid", "dashed", "dotted", etc.`,"INVALID_STROKE_STYLE"),INVALID_STROKE_LINE_CAP:r((e,t)=>`Invalid line cap at ${t}: "${e}". Should be one of: round, butt, square`,"INVALID_STROKE_LINE_CAP"),INVALID_BORDER:r((e,t)=>`Invalid border at ${t}: "${e}". Should have color, width, and style properties`,"INVALID_BORDER"),INVALID_SHADOW:r((e,t)=>`Invalid shadow at ${t}: "${e}". Should have color, offsetX, offsetY properties (blur and spread are optional)`,"INVALID_SHADOW"),INVALID_SHADOW_INSET:r((e,t)=>`Invalid inset value at ${t}: "${e}". Should be true or false`,"INVALID_SHADOW_INSET"),INVALID_TRANSITION:r((e,t)=>`Invalid transition at ${t}: "${e}". Should have duration, delay, and timingFunction properties`,"INVALID_TRANSITION"),INVALID_GRADIENT:r((e,t)=>`Invalid gradient at ${t}: "${e}". Should be an array of color stops with position values between 0 and 1`,"INVALID_GRADIENT"),INVALID_GRADIENT_STOP_POSITION:r((e,t)=>`Invalid gradient stop position at ${t}: "${e}". Position must be between 0 and 1`,"INVALID_GRADIENT_STOP_POSITION"),INVALID_TYPOGRAPHY:r((e,t)=>`Invalid typography at ${t}: "${e}". Should have fontFamily and fontSize (fontWeight, letterSpacing, and lineHeight are optional)`,"INVALID_TYPOGRAPHY"),MISSING_REQUIRED_PROPERTY:r((e,t)=>`Missing required property '${e}' at ${t}`,"MISSING_REQUIRED_PROPERTY"),INVALID_NUMBER:r((e,t)=>`Invalid number at ${t}: "${e}". Expected a number value`,"INVALID_NUMBER"),INVALID_ARRAY:r((e,t)=>`Invalid array at ${t}: "${e}". Expected an array value`,"INVALID_ARRAY"),MISSING_FLUID_CONFIG:r(e=>`Missing fluid configuration. Token at ${e} requires fluid viewport settings.`,"MISSING_FLUID_CONFIG"),INVALID_FLUID_DIMENSION:r((e,t)=>`Invalid fluid dimension at ${t}: "${e}". Fluid dimensions should have min and max values, like { "min": { "value": 16, "unit": "px" }, "max": { "value": 24, "unit": "px" } }`,"INVALID_FLUID_DIMENSION"),INVALID_VIEWPORT_CONFIG:r((e,t)=>`Invalid viewport configuration at ${t}: "${e}". Viewport config should have min and max dimension values`,"INVALID_VIEWPORT_CONFIG"),MISMATCHED_UNITS:r((e,t,n)=>`Mismatched units at ${n}: min uses '${e}', max uses '${t}'. Both values must use the same unit`,"MISMATCHED_UNITS"),INVALID_FLUID_VALUE_RANGE:r(e=>`Invalid fluid value range at ${e}: min value must be less than max value`,"INVALID_FLUID_VALUE_RANGE"),INVALID_TOKEN_TYPE:r((e,t,n)=>`Invalid token type at ${n}: expected ${e}, got ${t}`,"INVALID_TOKEN_TYPE"),INVALID_TYPE:r((e,t,n)=>`Expected ${e}, received ${typeof t} at ${n}`,"INVALID_TYPE"),INVALID_ENUM_VALUE:r((e,t,n)=>`Expected value to be one of [${e.join(", ")}], but got ${String(t)} at ${n}`,"INVALID_ENUM_VALUE")},RESOLVE:{CIRCULAR_REFERENCE:r((e,t)=>`Circular reference detected: ${e} -> ${t}`,"CIRCULAR_REFERENCE"),REFERENCE_NOT_FOUND:r((e,t)=>`Reference not found: ${e} in ${t}`,"REFERENCE_NOT_FOUND"),TYPE_MISMATCH:r(e=>`Type mismatch in ${e}`,"TYPE_MISMATCH")},GENERATE:{INVALID_CSS_VALUE:r((e,t)=>`Invalid CSS value for property '${e}': ${t}`,"INVALID_CSS_VALUE"),INVALID_VARIABLE_NAME:r((e,t)=>`Invalid CSS variable name at '${e}': ${t}`,"INVALID_VARIABLE_NAME")},CONFIG:{INVALID_JSON:r(e=>`Invalid JSON in config file: ${e}`,"INVALID_JSON"),INVALID_CONFIG:r((e,t)=>`Invalid configuration at ${e}: ${t}`,"INVALID_CONFIG"),DUPLICATE_FILENAMES:r((e,t,n)=>`Duplicate filename "${t}" found in collection "${e}":
2
+ ${n.map(o=>` - ${o}`).join(`
3
+ `)}`,"DUPLICATE_FILENAMES"),FILE_NOT_FOUND:r(e=>e===S?`Cannot find sugarcube config file. Please ensure you have a valid ${S} file in your project root.`:`Cannot find sugarcube config file at "${e}". Please check the path and file permissions.`,"FILE_NOT_FOUND")},UTILITIES:{RESERVED_PREFIX:r((e,t)=>`Cannot use reserved prefix "${e}" for ${t} token type. This prefix is reserved for default utility classes. Please use a custom prefix instead.`,"RESERVED_PREFIX"),DUPLICATE_CLASS_NAME:r((e,t)=>`Ambiguous utility class "${e}" would be generated from multiple token paths: ${t.join(", ")}. This would make it impossible to know which token value should be used when this class is applied in HTML. To fix this, configure one or more paths with custom prefixes to make the intent clear.`,"DUPLICATE_CLASS_NAME"),INVALID_PROPERTY_MAPPING:r(e=>`Invalid property mapping for ${e} token type. When mapping multiple properties, each mapping must include a unique prefix to avoid class name collisions.`,"INVALID_PROPERTY_MAPPING"),DUPLICATE_PREFIX:r((e,t)=>`Duplicate prefix "${e}" found in property mappings for ${t} token type. Each property mapping must have a unique prefix to avoid class name collisions.`,"DUPLICATE_PREFIX")}};function le(e,t=16){return e.unit==="px"?e.value:e.value*t}r(le,"normalizeToPixels");function Xe(e,t){const{min:n,max:o}=e,s=t.fluidConfig;if(!s)throw new Error(u.VALIDATE.MISSING_FLUID_CONFIG(t.path??""));const i=16,a=le(n,i),c=le(o,i),f=s.min,d=s.max;if(a===c)return{value:`${a/i}rem`};const p=a/i,h=c/i,m=f/i,$=d/i,g=(h-p)/($-m),T=-1*m*g+p;return{value:`clamp(${p}rem, ${T.toFixed(2)}rem + ${(g*100).toFixed(2)}vw, ${h}rem)`}}r(Xe,"convertFluidDimension");function Je(e,t){if(I(e))return{value:e};if(!t.fluidConfig)throw new Error(u.VALIDATE.MISSING_FLUID_CONFIG(t.path??""));return Xe(e,t)}r(Je,"convertFluidDimensionToken");function v(e){return["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","emoji","math","fangsong"].includes(e.toLowerCase())?e:/[\s'"!@#$%^&*()=+[\]{};:|\\/,.<>?~]/.test(e)?`"${e}"`:e}r(v,"quoteFont");function Ze(e){return I(e)?{value:e}:{value:Array.isArray(e)?e.map(n=>v(n)).join(", "):v(e)}}r(Ze,"convertFontFamilyToken");const Qe={thin:100,hairline:100,"extra-light":200,"ultra-light":200,light:300,normal:400,regular:400,book:400,medium:500,"semi-bold":600,"demi-bold":600,bold:700,"extra-bold":800,"ultra-bold":800,black:900,heavy:900,"extra-black":950,"ultra-black":950};function ue(e){return I(e)?{value:e}:typeof e=="number"?{value:e}:{value:Qe[e.toLowerCase()]??e}}r(ue,"convertFontWeightToken");function et(e){return I(e)?{value:e}:{value:`linear-gradient(${e.map(n=>{const o=(I(n.color),n.color),s=I(n.position)?n.position:`${n.position*100}`;return`${o} ${s}%`}).join(", ")})`}}r(et,"convertGradientToken");function tt(e){return I(e)?{value:e}:{value:e}}r(tt,"convertNumberToken");function fe(e){const t=I(e.offsetX)?e.offsetX:`${e.offsetX.value}${e.offsetX.unit}`,n=I(e.offsetY)?e.offsetY:`${e.offsetY.value}${e.offsetY.unit}`,o=I(e.blur)?e.blur:`${e.blur.value}${e.blur.unit}`,s=I(e.spread)?e.spread:`${e.spread.value}${e.spread.unit}`,i=(I(e.color),e.color);return`${e.inset?"inset ":""}${t} ${n} ${o} ${s} ${i}`}r(fe,"convertSingleShadow");function nt(e){return I(e)?{value:e}:Array.isArray(e)?{value:e.map(fe).join(", ")}:{value:fe(e)}}r(nt,"convertShadowToken");function pe(e){return e?`${e.value}${e.unit}`:"0ms"}r(pe,"formatDuration");function ot(e){if(I(e))return{value:e};const t=I(e.duration)?e.duration:pe(e.duration),n=I(e.timingFunction)?e.timingFunction:`cubic-bezier(${e.timingFunction.join(", ")})`,o=e.delay&&(I(e.delay)?e.delay:pe(e.delay));return{value:[t,n,o].filter(Boolean).join(" ")}}r(ot,"convertTransitionToken");function rt(e){if(I(e))return{"font-family":e,"font-size":e};const t={"font-family":I(e.fontFamily)?e.fontFamily:Array.isArray(e.fontFamily)?e.fontFamily.map(n=>v(n)).join(", "):v(e.fontFamily),"font-size":I(e.fontSize)?e.fontSize:`${e.fontSize.value}${e.fontSize.unit}`};return e.fontWeight&&(t["font-weight"]=I(e.fontWeight)?e.fontWeight:ue(e.fontWeight).value),e.letterSpacing&&(t["letter-spacing"]=I(e.letterSpacing)?e.letterSpacing:`${e.letterSpacing.value}${e.letterSpacing.unit}`),e.lineHeight&&(t["line-height"]=(I(e.lineHeight),e.lineHeight)),t}r(rt,"convertTypographyToken");const he={duration:ze,number:tt,cubicBezier:Ye,color:Be,dimension:We,fluidDimension:Je,typography:rt,border:Ge,shadow:nt,gradient:et,transition:ot,strokeStyle:ie,fontFamily:Ze,fontWeight:ue};function st(e,t){const n=he[e.$type];return{...e.$description?{$description:e.$description}:{},...e.$extensions?{$extensions:e.$extensions}:{},$type:e.$type,$value:e.$value,$path:e.$path,$source:e.$source,$originalPath:e.$originalPath,$resolvedValue:e.$resolvedValue,$cssProperties:n(e.$value,t)}}r(st,"convertSingleToken");function de(e,t){const n={};for(const[o,s]of Object.entries(e)){if(!s||typeof s!="object")continue;if(!("$type"in s)){n[o]={...s.$description?{$description:s.$description}:{},...s.$extensions?{$extensions:s.$extensions}:{}};continue}if(!he[s.$type])continue;const i={fluidConfig:t.transforms?.fluid??{min:320,max:1200},colorFormat:t.transforms?.colorFormat,path:s.$path};n[o]=st(s,i)}return n}r(de,"convertTokens");function it(e,t){const n={};for(const[o,s]of Object.entries(e)){const i={default:de(s.default,t)};for(const[a,c]of Object.entries(s))a!=="default"&&(i[a]=de(c,t));n[o]=i}return n}r(it,"convert");function at(e){if(typeof e!="object"||e===null||"$value"in e)return!1;const t="value"in e,n="type"in e;if(t&&n)return!0;if(t){const o=e.value;return typeof o=="string"||typeof o=="number"||Array.isArray(o)}return!1}r(at,"looksLikeUnprefixedToken");function ct(e,t){const n={tokens:{},pathIndex:new Map},o=[];function s(a=[]){const c=[t.collection];return t.theme&&c.push(t.theme),a.length>0&&c.push(a.join(".")),c.join(".")}r(s,"createLookupKey"),(e.$description||e.$extensions)&&(n.tokens[s()]={$description:e.$description,$extensions:e.$extensions});function i(a,c=[],f){if(c.join("."),c.length>0){const h=s(c);n.tokens[h]={$description:a.$description,$extensions:a.$extensions,$path:c.join("."),$source:{collection:t.collection,theme:t.theme,sourcePath:t.sourcePath}}}const d=Object.keys(a).filter(h=>!h.startsWith("$")),p=a.$type||f;for(const h of d){const m=a[h],$=[...c,h],g=$.join(".");if(at(m)){o.push({path:g,source:t,message:u.FLATTEN.MISSING_DOLLAR_PREFIX(g)});continue}if(h.includes(".")||h.includes("{")||h.includes("}")){o.push({path:g,source:t,message:u.FLATTEN.INVALID_TOKEN_NAME(h)});continue}if("$value"in m){if(Object.keys(m).filter(Re=>!Re.startsWith("$")).length>0){o.push({path:g,source:t,message:u.FLATTEN.INVALID_TOKEN_NESTING(g)});continue}if(Ue(m)&&!m.$type&&!p){o.push({path:g,source:t,message:u.FLATTEN.COMPOSITE_TOKEN_MISSING_TYPE(g)});continue}const L=s($),M=$.join(".");n.tokens[L]={...m,...m.$type||p?{$type:m.$type||p}:{},$path:M,$source:{collection:t.collection,theme:t.theme,sourcePath:t.sourcePath},$originalPath:M},n.pathIndex.set(M,L)}else i(m,$,p)}}return r(i,"processNode"),i(e),{tokens:n,errors:o}}r(ct,"flattenTree");function lt(e){const t={tokens:{},pathIndex:new Map},n=[];for(const o of e){const{tokens:s,errors:i}=ct(o.tokens,{collection:o.collection,theme:o.theme,sourcePath:o.sourcePath});Object.assign(t.tokens,s.tokens);for(const[a,c]of s.pathIndex)t.pathIndex.set(a,c);n.push(...i)}return{tokens:t,errors:n}}r(lt,"flatten");const me=new Map;function ut(e){const t=me.get(e);if(t)return t;const n=e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/([A-Z])([A-Z])(?=[a-z])/g,"$1-$2").toLowerCase();return me.set(e,n),n}r(ut,"toKebabCase");const Ie="@supports (color: color(display-p3 1 1 1))";function ft(e){return e.$type==="typography"}r(ft,"isTypographyToken");function q(e){return e.split(".").join("-")}r(q,"formatCSSVarPath");function $e(e){return typeof e=="number"?e:typeof e!="string"?(console.warn("Unexpected value type in convertReferenceToCSSVar, got:",e),String(e)):e.replace(/\{([^}]+)\}/g,(t,n)=>`var(--${n.split(".").map(ut).join("-")})`)}r($e,"convertReferenceToCSSVar");function pt(e){const t=e.$cssProperties;if("value"in t)return{name:`--${q(e.$path)}`,value:$e(t.value)}}r(pt,"generateSingleVariable");function ht(e){return Object.entries(e.$cssProperties).filter(([t,n])=>n!==void 0).map(([t,n])=>({name:`--${q(e.$path)}-${t}`,value:$e(n)}))}r(ht,"generateTypographyVariables");function ge(e){if(e.$type!=="color")return[];const t=e.$cssProperties;return"featureValues"in t?t.featureValues?.filter(n=>n.query===Ie).map(n=>({name:`--${q(e.$path)}`,value:n.value}))??[]:[]}r(ge,"generateFeatureVariables");function ye(e){const t=[`${e.selector} {`];if(e.comment&&t.push(` /* ${e.comment} */`),e.vars.length>0){const n=e.vars.map(o=>` ${o.name}: ${o.value};`).join(`
4
4
  `);t.push(n)}return t.push("}"),t.join(`
5
- `)}o(de,"generateCSSBlock");function St(e){const t=[];return e.root.vars.length>0&&t.push(de({selector:e.root.selector,vars:e.root.vars})),e.features.forEach(n=>{const s=de({selector:e.root.selector,vars:n.vars}).split(`
5
+ `)}r(ye,"generateCSSBlock");function dt(e){const t=[];e.root.vars.length>0&&t.push(ye({selector:e.root.selector,vars:e.root.vars}));for(const n of e.features){const s=ye({selector:e.root.selector,vars:n.vars}).split(`
6
6
  `).map(i=>` ${i}`).join(`
7
7
  `);t.push(`${n.query} {
8
8
  ${s}
9
- }`)}),t.filter(Boolean).join(`
9
+ }`)}return t.filter(Boolean).join(`
10
10
 
11
- `)}o(St,"convertCSSVarsToString");function Dt(e){if(Tt(e))return{vars:bt(e),features:fe(e)};const t=Nt(e);return{vars:t?[t]:[],features:fe(e)}}o(Dt,"generateVariablesForToken");async function U(e,t={}){const n=Object.entries(e).filter(([c,l])=>c!=="$extensions"&&"$type"in l).map(([c,l])=>Dt(l));let r=":root";t.theme&&t.theme!=="default"&&(r=`[data-theme="${t.theme}"]`);const s=n.flatMap(c=>c.vars),i=n.flatMap(c=>c.features||[]),a=St({root:{selector:r,vars:s},features:i.length?[{query:le,vars:i}]:[]});return a.trim()?{output:[{path:"tokens.variables.css",css:Lt(a)}]}:{output:[{path:"tokens.variables.css",css:""}]}}o(U,"generateCSS");function Lt(e){return e.endsWith(`
12
- `)?e:e+`
13
- `}o(Lt,"formatCSSVars");async function G(e,t){const n={};for(const[r,s]of Object.entries(e)){n[r]={default:{}},s.default&&(n[r].default=s.default);for(const[i,a]of Object.entries(s))i!=="default"&&a&&(n[r][i]=a);Object.keys(n[r].default).length===0&&Object.keys(n[r]).length===1&&delete n[r]}return t.output.css.separate?{output:await Ot(n,t)}:{output:await _t(n,t)}}o(G,"generate");async function _t(e,t){const n=`${t.output.directories.css}/global/variables`,r=[];for(const[s,i]of Object.entries(e)){const a=[];for(const[c,l]of Object.entries(i)){const f=await U(l,{theme:c!=="default"?c:void 0,collection:s!=="default"?s:void 0});f.output[0].css.trim()&&a.push(f.output[0].css)}a.length>0&&r.push({path:M({collection:s,filename:"tokens",separate:!1,baseDir:n}),css:a.filter(Boolean).join(`
14
- `).trim()+`
15
- `})}return r}o(_t,"generateSingleFile");async function Ot(e,t){const n=`${t.output.directories.css}/global/variables`,r=[];for(const[s,i]of Object.entries(e))if(Object.keys(i).length!==0){for(const[a,c]of Object.entries(i))if(Object.keys(c).length!==0)if(a==="default"){const l=new Map;for(const[f,p]of Object.entries(c)){if(!("$type"in p))continue;const I=p.$source.sourcePath;l.has(I)||l.set(I,{}),l.get(I)[f]=p}for(const[f,p]of l){if(Object.keys(p).length===0)continue;const d=f.split("/").pop()?.replace(/\.json$/,"")??"tokens",g=(await U(p,{collection:s==="default"?void 0:s})).output[0].css;g.trim()&&r.push({path:M({collection:s,filename:d,separate:!0,baseDir:n}),css:g})}}else{const f=(await U(c,{theme:a,collection:s==="default"?void 0:s})).output[0].css;f.trim()&&r.push({path:M({collection:s,filename:a,separate:!0,baseDir:n}),css:f})}}return r}o(Ot,"generateSeparateFiles");function W(e){const t=[],n=[],r=new Set,s=new Map;e.forEach(c=>{const{collection:l,theme:f="default"}=c;r.add(l),s.has(l)||s.set(l,new Set),s.get(l).add(f)});const i={};function a(c){const l={default:{}};i[c]=l;const f=s.get(c);return f&&f.forEach(p=>{l[p]={}}),l}return o(a,"addCollection"),r.forEach(c=>{a(c)}),e.forEach(c=>{const{collection:l,theme:f="default",tokens:p}=c,d=i[l]||a(l),I=d[f]||(d[f]={});Object.entries(p).forEach(([g,y])=>{const A=g.replace(`${l}.`,"");I[A]=y})}),{tokens:i,errors:n,warnings:t}}o(W,"normalizeTokens");async function Vt(e,t){const n={load:[],flatten:[],validation:[],resolution:[]},r={normalization:[]},{trees:s,errors:i}=await(t?.loader?.type==="memory"?V(t.loader.data):O(e));n.load.push(...i);const{tokens:a,errors:c}=F(s);n.flatten.push(...c);const l=v(a);if(n.validation.push(...l),l.length>0)return{output:[],trees:s,errors:n,warnings:r};const{resolved:f,errors:p}=w(a);n.resolution.push(...p);const d=x(s,f),{tokens:I,warnings:g}=W(d);r.normalization.push(...g);const y=j(I,e),{output:A}=await G(y,e);return{output:A,trees:s,errors:n,warnings:r}}o(Vt,"tokensToCSSPipeline");async function Ft(e,t){const{trees:n,errors:r}=await(t.loader.type==="memory"?V(t.loader.data):O(t.loader.paths)),{tokens:s,errors:i}=F(n),a=v(s),{resolved:c,errors:l}=w(s);return{trees:n,flattenedTokens:s,resolved:c,errors:{load:r,flatten:i,validation:a,resolution:l}}}o(Ft,"validationPipeline");async function kt(e,t,n){const r={normalization:[]},s=x(e,t),{tokens:i,warnings:a}=W(s);r.normalization.push(...a);const c=j(i,n),{output:l}=await G(c,n);return{output:l,warnings:r}}o(kt,"generationPipeline");function vt(e){return"source"in e&&Array.isArray(e.source)}o(vt,"isSingleCollection");function pe(e){return`/**
16
- * \u26A0\uFE0F AUTOMATICALLY GENERATED FILE - DO NOT EDIT DIRECTLY \u26A0\uFE0F
11
+ `)}r(dt,"convertCSSVarsToString");function mt(e){if(ft(e))return{vars:ht(e),features:ge(e)};const t=pt(e);return{vars:t?[t]:[],features:ge(e)}}r(mt,"generateVariablesForToken");async function X(e,t={}){const n=Object.entries(e).filter(([c,f])=>c!=="$extensions"&&"$type"in f).map(([c,f])=>mt(f));let o=":root";t.theme&&t.theme!=="default"&&(o=`[data-theme="${t.theme}"]`);const s=n.flatMap(c=>c.vars),i=n.flatMap(c=>c.features||[]),a=dt({root:{selector:o,vars:s},features:i.length?[{query:Ie,vars:i}]:[]});return a.trim()?{output:[{path:"tokens.variables.css",css:It(a)}]}:{output:[{path:"tokens.variables.css",css:""}]}}r(X,"generateCSS");function It(e){return e.endsWith(`
12
+ `)?e:`${e}
13
+ `}r(It,"formatCSSVars");async function $t(e,t){const o=`${t.output?.css||"src/styles"}/${H}`,s=[];for(const[i,a]of Object.entries(e)){const c=[];for(const[f,d]of Object.entries(a)){const p=await X(d,{theme:f!=="default"?f:void 0});p.output[0].css.trim()&&c.push(p.output[0].css)}c.length>0&&s.push({path:i==="default"?`${o}/${K}${b}`:`${o}/${i}/${K}${b}`,css:`${c.filter(Boolean).join(`
14
+ `).trim()}
15
+ `})}return s}r($t,"generateSingleFile");async function gt(e,t){const o=`${t.output?.css||"src/styles"}/${H}`,s=[];for(const[i,a]of Object.entries(e))if(Object.keys(a).length!==0){for(const[c,f]of Object.entries(a))if(Object.keys(f).length!==0)if(c==="default"){const d=new Map;for(const[p,h]of Object.entries(f)){if(!("$type"in h))continue;const $=h.$source.sourcePath;d.has($)||d.set($,{}),d.get($)[p]=h}for(const[p,h]of d){if(Object.keys(h).length===0)continue;const m=p.split("/").pop()?.replace(/\.json$/,"")??"tokens",g=(await X(h,{})).output[0].css;g.trim()&&s.push({path:i==="default"?`${o}/${m}${b}`:`${o}/${i}/${m}${b}`,css:g})}}else{const p=(await X(f,{theme:c})).output[0].css;p.trim()&&s.push({path:i==="default"?`${o}/${c}${b}`:`${o}/${i}/${c}${b}`,css:p})}}return s}r(gt,"generateSeparateFiles");async function yt(e,t){const n={};for(const[o,s]of Object.entries(e)){n[o]={default:{}},s.default&&(n[o].default=s.default);for(const[i,a]of Object.entries(s))i!=="default"&&a&&(n[o][i]=a);Object.keys(n[o].default).length===0&&Object.keys(n[o]).length===1&&delete n[o]}return t.output?.separate?{output:await gt(n,t)}:{output:await $t(n,t)}}r(yt,"generate");async function Ae(e){const t={files:[],errors:[]};for(const n of e)try{const o=!n.includes("*")&&!n.endsWith(".json")?D.join(n,"**/*.json"):n,s=await B(o,{absolute:!0,onlyFiles:!0});if(s.length===0){t.errors.push({pattern:n,error:u.LOAD.NO_FILES_FOUND(n)});continue}t.files.push(...s)}catch(o){t.errors.push({pattern:n,error:u.LOAD.GLOB_ERROR(n,o instanceof Error?o.message:"Unknown error")})}return t}r(Ae,"resolveFiles");async function Ee(e){try{const t=await U(e,"utf-8");return JSON.parse(t)}catch(t){throw t instanceof Error&&t instanceof SyntaxError?new Error(u.LOAD.INVALID_JSON(e,t.message)):t}}r(Ee,"loadTree");function At(e){const t=new Set;if(e.themes)for(const n of Object.values(e.themes))for(const o of n)t.add(o);return t}r(At,"collectThemePaths");async function Et(e){const t=[],n=[],o=Array.isArray(e.tokens)?{default:{source:e.tokens}}:"source"in e.tokens?{default:e.tokens}:e.tokens;if(!Object.values(o).some(i=>i.source.some(a=>{try{return B.sync(a).length>0}catch{return!1}})))return{trees:[],errors:[{file:S,message:u.LOAD.NO_FILES_FOUND(Object.values(o).flatMap(i=>i.source).join(", "))}]};for(const[i,a]of Object.entries(o)){const c=At(a),{files:f,errors:d}=await Ae(Array.isArray(a.source)?a.source:[a.source]);if(d.length>0){t.push(...d.map(p=>({file:p.pattern,message:p.error})));continue}for(const p of f){const h=G(process.cwd(),p);if(!c.has(h))try{const m=await Ee(p),$={collection:i,tokens:m,sourcePath:h};n.push($)}catch(m){t.push({file:p,message:m instanceof Error?m.message:"Unknown error"})}}if(a.themes)for(const[p,h]of Object.entries(a.themes))try{const{files:m,errors:$}=await Ae(h);if($.length>0){t.push(...$.map(g=>({file:g.pattern,message:g.error})));continue}for(const g of m)try{const T=await Ee(g),L={collection:i,theme:p,tokens:T,sourcePath:G(process.cwd(),g)};n.push(L)}catch(T){t.push({file:g,message:T instanceof Error?T.message:"Unknown error"})}}catch(m){t.push({file:h.join(", "),message:m instanceof Error?m.message:"Unknown error"})}}return{trees:n,errors:t}}r(Et,"loadTreesFromConfig");async function Tt(e){const t=[],n=[],o=new Map;for(const[s,{collection:i,theme:a,content:c}]of Object.entries(e)){o.has(i)||o.set(i,new Map);const f=o.get(i);f.has(a)||f.set(a,[]),f.get(a)?.push({content:c,path:s})}for(const[s,i]of o)for(const[a,c]of i)for(const{content:f,path:d}of c)try{const p=JSON.parse(f);t.push({collection:s,theme:a,tokens:p,sourcePath:G(process.cwd(),d)})}catch(p){p instanceof Error?p instanceof SyntaxError?n.push({file:d,message:u.LOAD.INVALID_JSON(d,p.message)}):n.push({file:d,message:p.message}):n.push({file:d,message:"Unknown error"})}return{trees:t,errors:n}}r(Tt,"loadTreesFromMemory");function bt(e){const t=new Set,n=new Map;for(const i of e){const{collection:a,theme:c="default"}=i;t.add(a),n.has(a)||n.set(a,new Set),n.get(a)?.add(c)}const o={};function s(i){const a={default:{}};o[i]=a;const c=n.get(i);if(c)for(const f of c)a[f]={};return a}r(s,"addCollection");for(const i of t)s(i);for(const i of e){const{collection:a,theme:c="default",tokens:f}=i,d=o[a]||s(a);let p=d[c];p||(p=d[c]={});for(const[h,m]of Object.entries(f)){const $=h.replace(`${a}.`,"");p[$]=m}}return{tokens:o}}r(bt,"normalizeTokens");function Nt(e,t){const n=new Map;for(const[o,s]of Object.entries(t)){if(!("$source"in s)){for(const f of e){const d=f.collection;n.has(d)||n.set(d,new Map);const p=n.get(d),h=f.theme;p.has(h)||p.set(h,{}),p.get(h)[o]=s}continue}const i=s.$source.collection,a=s.$source.theme;n.has(i)||n.set(i,new Map);const c=n.get(i);c.has(void 0)||c.set(void 0,{}),a||(c.get(void 0)[o]=s),a&&(c.has(a)||c.set(a,{}),c.get(a)[o]=s)}return e.map(o=>{const s=n.get(o.collection);if(!s)return{collection:o.collection,theme:o.theme,tokens:{}};if(o.theme){const a=s.get(o.theme)||{};return{collection:o.collection,theme:o.theme,tokens:a}}const i=s.get(void 0)||{};return{collection:o.collection,theme:o.theme,tokens:i}})}r(Nt,"processTrees");function k(e,t,n,o){return typeof t=="string"&&I(t)?Lt(e,t,n,o):Array.isArray(t)?t.map(s=>k(e,s,n,o)):typeof t=="object"&&t!==null?Object.entries(t).reduce((i,[a,c])=>Object.assign(i,{[a]:k(`${e}.${a}`,c,n,o)}),{}):t}r(k,"resolveValue");function Te(e,t){const n=e.slice(1,-1),o=t.pathIndex.get(n);if(!o)return;const s=t.tokens[o];if(!(!s||!("$value"in s))){if(s.$type)return s.$type;if(typeof s.$value=="string"&&I(s.$value))return Te(s.$value,t)}}r(Te,"inferTypeFromReference");function St(e){const t={},n=new Set,o=[];for(const[s,i]of Object.entries(e.tokens))try{if(!("$value"in i)){t[s]=i;continue}const a=i;let c=a.$type;!c&&typeof a.$value=="string"&&I(a.$value)&&(c=Te(a.$value,e)),t[s]={...a,...c?{$type:c}:{},$resolvedValue:k(a.$path,a.$value,e,n)}}catch(a){const c=a instanceof Error?a.message:String(a),f=i,d=f.$path,p=f.$source;let h,m;c.includes("Circular reference detected")?(h="circular",m=c):c.includes("Reference not found")?(h="missing",m=c):(h="type-mismatch",m=u.RESOLVE.TYPE_MISMATCH(d)),o.push({type:h,path:d,source:p,message:m})}return{resolved:t,errors:o}}r(St,"resolve");function Lt(e,t,n,o){const s=t.slice(1,-1),i=n.pathIndex.get(s);if(!i)throw new Error(u.RESOLVE.REFERENCE_NOT_FOUND(s,e));if(o.has(i)){const f=n.tokens[i];throw!f||!("$path"in f)?new Error(u.RESOLVE.REFERENCE_NOT_FOUND(s,e)):new Error(u.RESOLVE.CIRCULAR_REFERENCE(e,f.$path))}const a=n.tokens[i];if(!a||!("$value"in a))throw new Error(u.RESOLVE.REFERENCE_NOT_FOUND(s,e));o.add(i);const c=k(i,a.$value,n,o);return o.delete(i),c}r(Lt,"resolveReferenceChain");const _t={isObject:r(e=>typeof e=="object"&&e!==null&&!Array.isArray(e),"isObject")};function y(e,t,n,o){if(I(t))return[];switch(e.type){case"object":return Ot(e,t,n,o);case"union":return Ft(e,t,n,o);case"array":return vt(e,t,n,o);default:return Dt(e,t,n,o)}}r(y,"validateSchema");function Dt(e,t,n,o){return e.type!==typeof t?[{path:n,message:e.errorMessage?.(t,n)||u.VALIDATE.INVALID_TYPE(e.type,t,n),source:o}]:e.validate?.(t,n,o)??[]}r(Dt,"validateSimpleValue");function Ot(e,t,n,o){if(!_t.isObject(t))return[{path:n,message:e.errorMessage?.(t,n)||u.VALIDATE.INVALID_TYPE("object",t,n),source:o}];const s=[],i=t;if(e.required)for(const a of e.required)a in i||s.push({path:`${n}.${a}`,message:u.VALIDATE.MISSING_REQUIRED_PROPERTY(a,n),source:o});for(const[a,c]of Object.entries(e.properties))a in i&&s.push(...y(c,i[a],`${n}.${a}`,o));return s}r(Ot,"validateObject");function Ft(e,t,n,o){let s=[],i=Number.POSITIVE_INFINITY;for(const a of e.oneOf){if(a.type==="string"&&typeof t!="string"||a.type==="object"&&typeof t!="object")continue;const c=y(a,t,n,o);if(c.length===0)return e.validate?.(t,n,o)??[];c.length<i&&(s=c,i=c.length)}return i===Number.POSITIVE_INFINITY?[{path:n,message:u.VALIDATE.INVALID_TYPE(e.oneOf.map(a=>a.type).join(" or "),t,n),source:o}]:s}r(Ft,"validateUnion");function vt(e,t,n,o){return Array.isArray(t)?e.validate?.(t,n,o)??[]:[{path:n,message:e.errorMessage?.(t,n)||u.VALIDATE.INVALID_TYPE("array",t,n),source:o}]}r(vt,"validateArray");const w={schema:{type:"string",errorMessage:r((e,t)=>u.VALIDATE.INVALID_COLOR(e,t),"errorMessage"),validate:r((e,t,n)=>/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{8})$/.test(e)?[]:[{path:t,message:u.VALIDATE.INVALID_COLOR(e,t),source:n}],"validate")}};function kt(e,t,n){return y(w.schema,e,t,n)}r(kt,"validateColor");const V={schema:{type:"number",errorMessage:r((e,t)=>u.VALIDATE.INVALID_NUMBER(e,t),"errorMessage"),validate:r((e,t,n)=>typeof e!="number"||Number.isNaN(e)?[{path:t,message:u.VALIDATE.INVALID_NUMBER(e,t),source:n}]:[],"validate")}};function wt(e,t,n){return y(V.schema,e,t,n)}r(wt,"validateNumber");const A={schema:{type:"object",errorMessage:r((e,t)=>u.VALIDATE.INVALID_DIMENSION(e,t),"errorMessage"),properties:{value:V.schema,unit:{type:"string",validate:r((e,t,n)=>typeof e!="string"||!["px","rem"].includes(e)?[{path:t,message:u.VALIDATE.INVALID_DIMENSION_UNIT(e,t),source:n}]:[],"validate")}},required:["value","unit"]}};function Vt(e,t,n){return y(A.schema,e,t,n)}r(Vt,"validateDimension");const be={schema:{type:"union",oneOf:[{type:"string",errorMessage:r((e,t)=>u.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage")},{type:"array",errorMessage:r((e,t)=>u.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage"),validate:r((e,t,n)=>e.every(s=>typeof s=="string")?[]:[{path:t,message:u.VALIDATE.INVALID_FONT_FAMILY(e,t),source:n}],"validate")}],errorMessage:r((e,t)=>u.VALIDATE.INVALID_FONT_FAMILY(e,t),"errorMessage")}};function xt(e,t,n){return y(be.schema,e,t,n)}r(xt,"validateFontFamily");const Ct=["thin","hairline","extra-light","ultra-light","light","normal","regular","book","medium","semi-bold","demi-bold","bold","extra-bold","ultra-bold","black","heavy","extra-black","ultra-black"],Ne={schema:{type:"union",errorMessage:r((e,t)=>u.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),oneOf:[{type:"number",errorMessage:r((e,t)=>u.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),validate:r((e,t,n)=>e<1||e>1e3?[{path:t,message:u.VALIDATE.INVALID_FONT_WEIGHT(e,t),source:n}]:[],"validate")},{type:"string",errorMessage:r((e,t)=>u.VALIDATE.INVALID_FONT_WEIGHT(e,t),"errorMessage"),validate:r((e,t,n)=>Ct.includes(e.toLowerCase())?[]:[{path:t,message:u.VALIDATE.INVALID_FONT_WEIGHT(e,t),source:n}],"validate")}]}};function Rt(e,t,n){return y(Ne.schema,e,t,n)}r(Rt,"validateFontWeight");const jt=["ms","s"],J={schema:{type:"object",errorMessage:r((e,t)=>u.VALIDATE.INVALID_DURATION(e,t),"errorMessage"),properties:{value:V.schema,unit:{type:"string",validate:r((e,t,n)=>jt.includes(e)?[]:[{path:t,message:u.VALIDATE.INVALID_DURATION_UNIT(e,t),source:n}],"validate")}},required:["value","unit"]}};function Mt(e,t,n){return y(J.schema,e,t,n)}r(Mt,"validateDuration");const Se={schema:{type:"array",errorMessage:r((e,t)=>u.VALIDATE.INVALID_CUBIC_BEZIER(e,t),"errorMessage"),validate:r((e,t,n)=>{const o=e;if(o.length!==4||!o.every(a=>typeof a=="number"))return[{path:t,message:u.VALIDATE.INVALID_CUBIC_BEZIER(e,t),source:n}];const[s,,i]=o;return s<0||s>1||i<0||i>1?[{path:t,message:u.VALIDATE.INVALID_CUBIC_BEZIER(e,t),source:n}]:[]},"validate")}};function Pt(e,t,n){return y(Se.schema,e,t,n)}r(Pt,"validateCubicBezier");const Ut={schema:{type:"object",properties:{fontFamily:be.schema,fontSize:A.schema,letterSpacing:A.schema,lineHeight:V.schema,fontWeight:Ne.schema},required:["fontFamily","fontSize"],errorMessage:r((e,t)=>u.VALIDATE.INVALID_TYPOGRAPHY(e,t),"errorMessage")}};function Gt(e,t,n){return y(Ut.schema,e,t,n)}r(Gt,"validateTypography");const Bt=["solid","dashed","dotted","double","groove","ridge","outset","inset"],Yt=["round","butt","square"],Wt={type:"object",errorMessage:r((e,t)=>u.VALIDATE.INVALID_STROKE_STYLE(e,t),"errorMessage"),properties:{dashArray:{type:"array",validate:r((e,t,n)=>{const o=e,s=[];return o.forEach((i,a)=>{typeof i!="string"&&s.push(...y(A.schema,i,`${t}.${a}`,n))}),s},"validate")},lineCap:{type:"string",validate:r((e,t,n)=>Yt.includes(e)?[]:[{path:t,message:u.VALIDATE.INVALID_STROKE_LINE_CAP(e,t),source:n}],"validate")}},required:["dashArray","lineCap"]},Le={schema:{type:"union",oneOf:[{type:"string",validate:r((e,t,n)=>!Bt.includes(e)&&typeof e=="string"?[{path:t,message:u.VALIDATE.INVALID_STROKE_STYLE(e,t),source:n}]:[],"validate")},Wt]}};function zt(e,t,n){return y(Le.schema,e,t,n)}r(zt,"validateStrokeStyle");const Ht={schema:{type:"object",properties:{color:w.schema,width:A.schema,style:Le.schema},required:["color","width","style"],errorMessage:r((e,t)=>u.VALIDATE.INVALID_BORDER(e,t),"errorMessage")}};function Kt(e,t,n){return y(Ht.schema,e,t,n)}r(Kt,"validateBorder");const qt={schema:{type:"object",properties:{duration:J.schema,delay:J.schema,timingFunction:Se.schema},required:["duration","delay","timingFunction"],errorMessage:r((e,t)=>u.VALIDATE.INVALID_TRANSITION(e,t),"errorMessage")}};function Xt(e,t,n){return y(qt.schema,e,t,n)}r(Xt,"validateTransition");const _e={schema:{type:"object",properties:{color:w.schema,offsetX:A.schema,offsetY:A.schema,blur:A.schema,spread:A.schema,inset:{type:"boolean",errorMessage:r((e,t)=>u.VALIDATE.INVALID_SHADOW_INSET(e,t),"errorMessage")}},required:["color","offsetX","offsetY","blur","spread"],errorMessage:r((e,t)=>u.VALIDATE.INVALID_SHADOW(e,t),"errorMessage")}};function Jt(e,t,n){const o=[];return Array.isArray(e)?(e.forEach((s,i)=>{o.push(...y(_e.schema,s,`${t}[${i}]`,n))}),o):y(_e.schema,e,t,n)}r(Jt,"validateShadow");const Zt={type:"object",errorMessage:r((e,t)=>u.VALIDATE.INVALID_GRADIENT(e,t),"errorMessage"),properties:{color:{type:"string",validate:w.schema.validate},position:{type:"number",validate:r((e,t,n)=>e<0||e>1?[{path:t,message:u.VALIDATE.INVALID_GRADIENT_STOP_POSITION(e,t),source:n}]:[],"validate")}},required:["color","position"]},Qt={schema:{type:"array",errorMessage:r((e,t)=>u.VALIDATE.INVALID_ARRAY(e,t),"errorMessage"),validate:r((e,t,n)=>{const o=e,s=[];return o.forEach((i,a)=>{s.push(...y(Zt,i,`${t}[${a}]`,n))}),s},"validate")}};function en(e,t,n){return y(Qt.schema,e,t,n)}r(en,"validateGradient");const tn={schema:{type:"object",errorMessage:r((e,t)=>u.VALIDATE.INVALID_FLUID_DIMENSION(e,t),"errorMessage"),properties:{min:A.schema,max:A.schema},required:["min","max"]}};function nn(e,t,n){return y(tn.schema,e,t,n)}r(nn,"validateFluidDimension");const on={color:kt,dimension:Vt,fluidDimension:nn,duration:Mt,cubicBezier:Pt,fontFamily:xt,fontWeight:Rt,number:wt,strokeStyle:zt,typography:Gt,border:Kt,shadow:Jt,gradient:en,transition:Xt};function rn(e){const t=[];for(const[n,o]of Object.entries(e.tokens)){if(typeof o!="object"||o===null||!("$type"in o)||!("$path"in o)||o.$path.startsWith("$"))continue;if(!("$value"in o)){t.push({path:o.$path,message:u.VALIDATE.MISSING_REQUIRED_PROPERTY("$value",o.$path),source:o.$source});continue}const s=on[o.$type];if(!s){t.push({path:o.$path,message:u.VALIDATE.UNKNOWN_TOKEN_TYPE(o.$type,o.$path),source:o.$source});continue}const i=o;t.push(...s(i.$value,i.$path,i.$source))}return t}r(rn,"validate");async function sn(e){const{trees:t,errors:n}=await(e.type==="memory"?Tt(e.data):Et(e.config)),{tokens:o,errors:s}=lt(t),i=rn(o),{resolved:a,errors:c}=St(o);return{trees:t,resolved:a,errors:{load:n,flatten:s,validation:i,resolution:c}}}r(sn,"tokenProcessingPipeline");const x=l.array(l.string()).min(1,"At least one file path must be specified"),Z=l.object({source:x,themes:l.record(x).optional()}),De=l.record(l.string(),Z),Oe=l.object({min:l.number(),max:l.number()}),C=l.object({typeMap:l.record(l.enum(["color","dimension","fluidDimension","duration","cubicBezier","fontFamily","fontWeight","number","border","shadow","gradient","transition","strokeStyle"]),x).optional(),directions:l.union([l.enum(["top","right","bottom","left","x","y","full"]),l.array(l.enum(["top","right","bottom","left","x","y","full"]))]).optional(),properties:x.optional(),prefix:l.string().optional(),stripLevels:l.number().optional(),custom:l.record(l.string(),l.string()).optional()}),Q=l.object({tokens:l.union([Z,De]),transforms:l.object({fluid:Oe.optional(),colorFormat:l.enum(["hex","rgb","rgba","hsl","hsla","oklch","p3"]).optional(),prefix:l.string().optional()}).optional(),output:l.object({css:l.string().optional(),tokens:l.string().optional(),components:l.string().optional(),separate:l.boolean().optional()}).optional(),utilities:l.object({core:l.boolean().optional()}).catchall(l.union([C,l.array(C)])).optional(),components:l.object({framework:l.enum(["react","astro"]).optional(),installed:l.array(l.string()).optional()}).optional(),plugins:l.array(l.string()).optional()}),Fe=l.object({tokens:l.union([Z,De]),transforms:l.object({fluid:Oe.optional(),colorFormat:l.enum(["hex","rgb","rgba","hsl","hsla","oklch","p3"]).optional(),prefix:l.string().optional()}).optional(),output:l.object({css:l.string(),tokens:l.string(),components:l.string(),separate:l.boolean()}),utilities:l.object({core:l.boolean().optional()}).catchall(l.union([C,l.array(C)])).optional(),components:l.object({framework:l.enum(["react","astro"]).optional(),installed:l.array(l.string()).optional()}).optional(),plugins:l.array(l.string()).optional()}),an=Q,N={output:{css:"src/styles",tokens:"src/design-tokens",components:"src/ui/components",separate:!1}};function ve(e){const t={tokens:e.tokens,output:{css:e.output?.css??N.output.css,tokens:e.output?.tokens??N.output.tokens,separate:e.output?.separate??N.output.separate}};return(e.output?.components!==void 0||N.output.components!==void 0)&&(t.output.components=e.output?.components??N.output.components),e.transforms&&(t.transforms=e.transforms),e.utilities&&(t.utilities=e.utilities),e.components&&(t.components=e.components),e.plugins&&(t.plugins=e.plugins),t}r(ve,"normalizeConfig");function ke(e){const t=Q.safeParse(e);if(!t.success){const s=t.error.errors.map(i=>{const a=i.path.join(".");return u.CONFIG.INVALID_CONFIG(a||"root",i.message)});throw new Error(s.join(`
16
+ `))}const n=ve(t.data),o=Fe.safeParse(n);if(!o.success){const s=o.error.errors.map(i=>{const a=i.path.join(".");return u.CONFIG.INVALID_CONFIG(a||"root",i.message)});throw new Error(s.join(`
17
+ `))}return cn(o.data),o.data}r(ke,"validateConfig");function we(e){try{const t=JSON.parse(e);return ke(t)}catch(t){throw t instanceof SyntaxError?new Error(u.CONFIG.INVALID_JSON(t.message)):t}}r(we,"parseAndValidateConfig");function cn(e){if(typeof e.tokens=="object")for(const[t,n]of Object.entries(e.tokens)){if(!n.source?.length)continue;const o=new Map;for(const s of n.source){const i=D.basename(s),a=o.get(i)||[];o.set(i,[...a,s])}for(const[s,i]of o)if(i.length>1)throw new Error(u.CONFIG.DUPLICATE_FILENAMES(t,s,i))}}r(cn,"validateFileNames");async function ln(e=S){try{const t=await _.readFile(e,"utf-8");return{config:we(t),configPath:e}}catch(t){throw t instanceof Error&&"code"in t&&t.code==="ENOENT"?new Error(u.CONFIG.FILE_NOT_FOUND(e)):t}}r(ln,"loadConfig");function un(e){return"source"in e&&Array.isArray(e.source)}r(un,"isSingleCollection");function fn(e){return`/**
18
+ * THIS FILE IS AUTOMATICALLY GENERATED BY SUGARCUBE FROM YOUR DESIGN TOKENS
19
+ * To make changes to it, edit your token files instead.
20
+ *
21
+ * For more information, see: https://sugarcube.style/docs/design-tokens
17
22
  */
18
23
 
19
- ${e}`}o(pe,"addWarningBanner");function wt(e){return vt(e.tokens)?e.tokens.source:Object.values(e.tokens).flatMap(t=>"source"in t?t.source:[])}o(wt,"getTokenPathsFromConfig");async function xt(e,t=!0,n){for(const r of e){const s=t&&n?pe(r.css):r.css;try{await be(T.dirname(r.path),{recursive:!0});let i=!0;if(H(r.path))try{await Y(r.path,"utf-8")===s&&(i=!1)}catch{}i&&await B(r.path,s,"utf-8")}catch(i){throw new Error(`Failed to write CSS file ${r.path}: ${i instanceof Error?i.message:"Unknown error"}`)}}return e}o(xt,"writeCSSFilesToDisk");const he=m.object({tokens:m.union([m.object({source:m.array(m.string()),type:m.enum(["starter-kit","custom"]),themes:m.record(m.array(m.string())).optional()}),m.record(m.string(),m.object({source:m.array(m.string()),type:m.enum(["starter-kit","custom"]),themes:m.record(m.array(m.string())).optional()}))]),options:m.object({fluid:m.object({min:m.number(),max:m.number()}).strict().optional(),prefix:m.string().optional(),color:m.enum(["hex","rgb","rgba","hsl","hsla","oklch","p3"]).optional()}).optional(),output:m.object({directories:m.object({tokens:m.string(),components:m.string().optional(),css:m.string()}),css:m.object({separate:m.boolean(),manageIndex:m.boolean().optional(),format:m.enum(["css","scss","less"]).optional()})})});function me(e){const t=he.safeParse(e);if(!t.success){const n=t.error.errors.map(r=>{const s=r.path.join(".");return u.CONFIG.INVALID_CONFIG(s||"root",r.message)});throw new Error(n.join(`
20
- `))}return Ct(t.data),t.data}o(me,"validateConfig");function Ie(e){try{const t=JSON.parse(e);return me(t)}catch(t){throw t instanceof SyntaxError?new Error(u.CONFIG.INVALID_JSON(t.message)):t}}o(Ie,"parseAndValidateConfig");function Ct(e){if(typeof e.tokens=="object")for(const[t,n]of Object.entries(e.tokens)){if(!n.source?.length)continue;const r=new Map;n.source.forEach(s=>{const i=T.basename(s),a=r.get(i)||[];r.set(i,[...a,s])});for(const[s,i]of r)if(i.length>1)throw new Error(u.CONFIG.DUPLICATE_FILENAMES(t,s,i))}}o(Ct,"validateFileNames");async function Rt(e="sugarcube.config.json"){try{const t=await Ne.readFile(e,"utf-8");return Ie(t)}catch(t){throw t instanceof Error&&"code"in t&&t.code==="ENOENT"?new Error(u.CONFIG.FILE_NOT_FOUND(e)):t}}o(Rt,"loadConfig");function jt(e){const t=e.split("/"),n=t.findIndex(s=>s==="variables");if(n===-1||n===t.length-1)return"default";const r=t[n+1];return!r||r.endsWith(".css")?"default":r}o(jt,"getCollectionFromPath");function ge(e,t){if(e.includes("/variables/")){const n=jt(e),r=t.variables.get(n)??[];r.push(e),t.variables.set(n,r)}else e.startsWith("global/")?t.global.push(e):e.startsWith("compositions/")?t.compositions.push(e):e.startsWith("utilities/")&&t.utilities.push(e)}o(ge,"groupFile");async function Mt(e,t){const n={variables:new Map,global:[],compositions:[],utilities:[]},r=T.join(t,"index.css");let s="";H(r)&&(s=await Y(r,"utf-8"),s.split(`
21
- `).filter(l=>l.trim().startsWith("@import")).map(l=>l.match(/'([^']+)'/)?.[1]).filter(l=>l!==void 0).forEach(l=>ge(l,n))),e.filter(c=>c.endsWith(".css")).forEach(c=>{const l=T.relative(t,c).replace(/\\/g,"/");ge(l,n)});const i=["reset.css","fonts.css","global-styles.css"];n.global.sort((c,l)=>{const f=i.findIndex(d=>c.endsWith(d)),p=i.findIndex(d=>l.endsWith(d));return f-p});const a=[];for(const[,c]of Array.from(n.variables.entries()).sort())c.length>0&&a.push(...c.sort().map(l=>`@import '${l}';`));return n.global.length>0&&(a.length&&a.push(""),a.push(...n.global.map(c=>`@import '${c}';`))),n.compositions.length>0&&(a.length&&a.push(""),a.push(...n.compositions.sort().map(c=>`@import '${c}';`))),n.utilities.length>0&&(a.length&&a.push(""),a.push(...n.utilities.sort().map(c=>`@import '${c}';`))),a.filter(Boolean).join(`
22
- `)+`
23
- `}o(Mt,"generateCSSIndex");async function Pt({cssOutputDirectory:e,files:t}){const n=t.filter(s=>s.endsWith(".css"));if(n.length===0)throw new Error("No CSS files to manage");const r=T.join(e,"index.css");try{const s=await Mt(n,e);return await B(r,s),r}catch(s){throw new Error(`Failed to manage CSS index file: ${s instanceof Error?s.message:String(s)}`)}}o(Pt,"manageCSSIndex");export{pe as addWarningBanner,he as configSchema,j as convert,F as flatten,G as generate,kt as generationPipeline,wt as getTokenPathsFromConfig,Rt as loadConfig,O as loadTreesFromConfig,V as loadTreesFromMemory,Pt as manageCSSIndex,W as normalizeTokens,Ie as parseAndValidateConfig,x as processTrees,w as resolve,Vt as tokensToCSSPipeline,v as validate,me as validateConfig,Ft as validationPipeline,xt as writeCSSFilesToDisk};
24
+ ${e}`}r(fn,"addWarningBanner");function pn(e){return un(e.tokens)?e.tokens.source.map(se):Object.values(e.tokens).flatMap(t=>"source"in t?t.source.map(se):[])}r(pn,"getTokenPathsFromConfig");async function hn(e){for(const t of e){const n=fn(t.css);try{await oe(D.dirname(t.path),{recursive:!0});let o=!0;if(O(t.path))try{await U(t.path,"utf-8")===n&&(o=!1)}catch{}o&&await re(t.path,n,"utf-8")}catch(o){throw new Error(`Failed to write CSS file ${t.path}: ${o instanceof Error?o.message:"Unknown error"}`)}}return e}r(hn,"writeCSSVariablesToDisk");async function dn(e){const t=`/**
25
+ * THIS FILE IS AUTOMATICALLY GENERATED BY SUGARCUBE FROM YOUR UTILITIES CONFIGURATION
26
+ * To make changes to it, edit your utilities configuration.
27
+ *
28
+ * For more information on configuration, see: https://sugarcube.style/docs/configuration
29
+ */
30
+
31
+ `;for(const n of e){const o=t+n.css;try{await oe(D.dirname(n.path),{recursive:!0});let s=!0;if(O(n.path))try{await U(n.path,"utf-8")===o&&(s=!1)}catch{}s&&await re(n.path,o,"utf-8")}catch(s){throw new Error(`Failed to write utility CSS file ${n.path}: ${s instanceof Error?s.message:"Unknown error"}`)}}return e}r(dn,"writeCSSUtilitiesToDisk");function mn(e,t){if(!t)return[];const n=[],o=t[e];o&&(Array.isArray(o)?n.push(...o):n.push(o));for(const[s,i]of Object.entries(t))if(s.endsWith("*")){const a=s.slice(0,-1);e.startsWith(a)&&(Array.isArray(i)?n.push(...i):n.push(i))}return n}r(mn,"findMatchingConfig");function R(e,t,n){return`${e} {
32
+ ${t}: ${n};
33
+ }`}r(R,"generateCSSRule");function ee(e){return e.charAt(0)}r(ee,"getAbbreviatedName");function Ve(e,t,n,o){if(t==="full"){const i=`${ee(e)}-${n}`;return o.prefix?`${o.prefix}-${i}`:i}if(t){const s=ee(e),i=ee(t),a=`${s}${i}-${n}`;return o.prefix?`${o.prefix}-${a}`:a}return o.prefix?`${o.prefix}-${n}`:n}r(Ve,"generateClassName");function In(e,t){return t==="full"?e:`${e}-${{top:"block-start",right:"inline-end",bottom:"block-end",left:"inline-start",x:"inline",y:"block"}[t]}`}r(In,"getLogicalProperty");function $n(e,t,n,o){return o.directions?(Array.isArray(o.directions)?o.directions:[o.directions]).map(i=>R(`.${Ve(e,i,t,o)}`,In(e,i),`var(--${n.join("-")})`)):[]}r($n,"generateDirectionalCSS");function gn(e,t){if(e.$type&&t.typeMap){const n=t.typeMap[e.$type];if(n)return n}return t.properties?t.properties:[]}r(gn,"getPropertiesForToken");const yn={"w-full":"width: 100%;","h-full":"height: 100%;","w-fit-content":"width: fit-content;","h-fit-content":"height: fit-content;","w-auto":"width: auto;","h-auto":"height: auto;","w-min-content":"width: min-content;","h-min-content":"height: min-content;","w-max-content":"width: max-content;","h-max-content":"height: max-content;",block:"display: block;",inline:"display: inline;","inline-block":"display: inline-block;",hidden:"display: none;","text-left":"text-align: left;","text-center":"text-align: center;","text-right":"text-align: right;","text-justify":"text-align: justify;",uppercase:"text-transform: uppercase;",lowercase:"text-transform: lowercase;",capitalize:"text-transform: capitalize;","normal-case":"text-transform: none;",relative:"position: relative;",absolute:"position: absolute;",fixed:"position: fixed;",sticky:"position: sticky;",static:"position: static;","overflow-auto":"overflow: auto;","overflow-hidden":"overflow: hidden;","overflow-visible":"overflow: visible;","overflow-scroll":"overflow: scroll;","cursor-pointer":"cursor: pointer;","cursor-default":"cursor: default;","cursor-not-allowed":"cursor: not-allowed;","select-none":"user-select: none;","select-text":"user-select: text;","select-all":"user-select: all;","list-none":"list-style: none;","list-disc":"list-style: disc;","list-decimal":"list-style: decimal;","list-inside":"list-style: inside;","mx-auto":"margin-inline: auto;","ml-auto":"margin-inline-start: auto;","mr-auto":"margin-inline-end: auto;","mt-auto":"margin-block-start: auto;","mb-auto":"margin-block-end: auto;"};function An(e,t){const n=new Set;if(t.utilities?.core)for(const[i,a]of Object.entries(yn)){const[c,f]=a.split(": ");if(c&&f){const d=f.replace(";","");n.add(R(`.${i}`,c,d))}}if(t.utilities)for(const[i,a]of Object.entries(t.utilities)){if(i==="core"||typeof a=="boolean")continue;const c=Array.isArray(a)?a:[a];for(const f of c)if(f.custom&&f.properties)for(const[d,p]of Object.entries(f.custom))for(const h of f.properties){const m=f.prefix?`${f.prefix}-${i}-${d}`:`${i}-${d}`;n.add(R(`.${m}`,h,p))}}for(const[i,a]of Object.entries(e)){if(!("$path"in a))continue;const c=mn(a.$path,t.utilities);if(c.length!==0)for(const f of c){if(f.custom)continue;const d=gn(a,f);if(d.length===0)continue;const p=a.$path.split("."),m=(f.stripLevels?p.slice(f.stripLevels):p).join("-");for(const $ of d)if(f.directions)for(const g of $n($,m,p,f))n.add(g);else n.add(R(`.${Ve($,void 0,m,f)}`,$,`var(--${p.join("-")})`))}}const o=Array.from(n);o.sort();const s=o.join(`
34
+
35
+ `);return{output:[{path:`${t.output.css}/${ae}/${ce}`,css:s}],errors:[]}}r(An,"generateCSSUtilityClasses");async function En(e,t,n){const o=Nt(e,t),{tokens:s}=bt(o),i=it(s,n),{output:a}=await yt(i,n);return{output:a}}r(En,"generateCSSVariables");const j=["reset","global","compositions","blocks","utilities"];async function te(e,t){const n=[],o=await B([E(e,"**/*.css"),E(e,"**/*.scss"),E(e,"**/*.sass"),E(e,"**/*.less")],{ignore:[E(e,F)]});for(const s of o){const i=Tn(s,e);if(i){const a=Y(e,s);n.push({path:a,layer:i,relativePath:a})}}return n}r(te,"discoverAllFiles");function Tn(e,t){const n=Y(t,e);if(n.includes("global/")||n.startsWith("global/"))return Pe(e).includes("reset")?"reset":"global";if(n.includes("compositions/")||n.startsWith("compositions/"))return"compositions";if(n.includes("blocks/")||n.startsWith("blocks/"))return"blocks";if(n.includes("utilities/")||n.startsWith("utilities/"))return"utilities"}r(Tn,"categorizeFile");function bn(e){return e.sort((t,n)=>{const o=j.indexOf(t.layer),s=j.indexOf(n.layer);return o!==s?o-s:t.path.localeCompare(n.path)})}r(bn,"sortFilesByLayer");function Nn(){return`@layer ${j.join(", ")};
36
+ `}r(Nn,"getLayerDefinitions");function xe(e){const t=[];t.push(Nn());const n=e.reduce((o,s)=>{const i=o[s.layer]??[];return o[s.layer]=[...i,s],o},{});for(const o of j){const s=n[o];if(!(!s||s.length===0))for(const i of s)t.push(`@import "${i.path}" layer(${i.layer});`)}return t.join(`
37
+ `)}r(xe,"generateIndexContent");async function Sn(e,t){const n=E(e,F),o=await te(e),s=bn(o),i=xe(s);return await _.writeFile(n,i),Y(process.cwd(),n)}r(Sn,"generateIndex");async function Ln(e,t){const n=E(e,F);if(!O(n))return!0;try{const o=await _.stat(n),s=await te(e,t);for(const i of s){const a=E(e,i.path);if(O(a)&&(await _.stat(a)).mtime>o.mtime)return!0}return!1}catch{return!0}}r(Ln,"shouldRegenerateIndex");class Ce extends Map{static{r(this,"DefaultMap")}constructor(t){super(),this.factory=t}get(t){let n=super.get(t);return n===void 0&&(n=this.factory(t,this),this.set(t,n)),n}}const _n=process.env.DEBUG==="true";class Dn{static{r(this,"Instrumentation")}constructor(t=n=>void process.stderr.write(`${n}
38
+ `)){this.defaultFlush=t}#t=new Ce(()=>({value:0}));#n=new Ce(()=>({value:0n}));#e=[];hit(t){this.#t.get(t).value++}start(t){const n=this.#e.map(s=>s.label).join("//"),o=`${n}${n.length===0?"":"//"}${t}`;this.#t.get(o).value++,this.#n.get(o),this.#e.push({id:o,label:t,namespace:n,value:process.hrtime.bigint()})}end(t){const n=process.hrtime.bigint();if(this.#e.length===0)throw new Error("Timer stack is empty");const o=this.#e.length-1,s=this.#e[o];if(!s)throw new Error("Timer stack is corrupted");if(s.label!==t)throw new Error(`Mismatched timer label: ${t}`);const i=this.#e.pop();if(!i)throw new Error("Timer stack is empty");const a=n-i.value;this.#n.get(i.id).value+=a}report(t=this.defaultFlush){const n=[];let o=!1;for(let s=this.#e.length-1;s>=0;s--){const i=this.#e[s];i&&this.end(i.label)}for(const[s,{value:i}]of this.#t.entries()){if(this.#n.has(s))continue;n.length===0&&(o=!0,n.push("Hits:"));const a=s.split("//").length;n.push(`${" ".repeat(a)}${s} \xD7 ${i}`)}if(this.#n.size>0){o&&n.push(`
39
+ Timers:`);for(const[s,{value:i}]of this.#n){const a=s.split("//").length,c=`${(Number(i)/1e6).toFixed(2)}ms`;n.push(`${" ".repeat(a-1)}${s.split("//").pop()} [${c}] ${this.#t.get(s).value===1?"":`\xD7 ${this.#t.get(s).value}`}`.trimEnd())}}t(`
40
+ ${n.join(`
41
+ `)}
42
+ `)}[Symbol.dispose](){_n&&this.report()}}export{N as DEFAULT_CONFIG,qe as DEFAULT_DESIGN_TOKENS_PATH,Ke as DEFAULT_STYLES_PATH,ce as DEFAULT_UTILITIES_FILENAME,K as DEFAULT_VARIABLES_FILENAME,H as GLOBAL_DIR,Dn as Instrumentation,S as SUGARCUBE_CONFIG_FILE,F as SUGARCUBE_FILE,He as TOKENS_FILE_SUFFIX,ae as UTILITIES_DIR,b as VARIABLES_FILE_SUFFIX,an as configSchema,te as discoverAllFiles,An as generateCSSUtilityClasses,En as generateCSSVariables,Sn as generateIndex,xe as generateIndexContent,pn as getTokenPathsFromConfig,Fe as internalConfigSchema,ln as loadConfig,ve as normalizeConfig,we as parseAndValidateConfig,Ln as shouldRegenerateIndex,sn as tokenProcessingPipeline,Q as userConfigSchema,ke as validateConfig,dn as writeCSSUtilitiesToDisk,hn as writeCSSVariablesToDisk};
package/package.json CHANGED
@@ -1,43 +1,45 @@
1
1
  {
2
2
  "name": "@sugarcube-org/core",
3
- "version": "0.0.1-alpha.4",
3
+ "version": "0.0.1-alpha.6",
4
4
  "publishConfig": {
5
5
  "access": "public"
6
6
  },
7
7
  "description": "Core functionality for sugarcube",
8
- "license": "AGPL-3.0",
8
+ "license": "UNLICENSED",
9
9
  "main": "./dist/index.js",
10
10
  "types": "./dist/index.d.ts",
11
11
  "type": "module",
12
12
  "exports": {
13
13
  ".": "./dist/index.js"
14
14
  },
15
+ "engines": {
16
+ "node": ">=18.0.0"
17
+ },
15
18
  "files": [
16
19
  "dist",
17
20
  "README.md"
18
21
  ],
19
22
  "devDependencies": {
20
- "@vitest/coverage-istanbul": "2.1.2",
21
23
  "pkgroll": "^2.5.1",
22
24
  "tsx": "^4.19.2"
23
25
  },
24
26
  "dependencies": {
25
27
  "@types/culori": "^2.1.1",
26
- "@types/picomatch": "^3.0.1",
27
28
  "culori": "^4.0.1",
28
29
  "fast-glob": "^3.3.2",
29
- "globby": "^14.0.2",
30
- "picomatch": "^4.0.2",
30
+ "pathe": "^2.0.3",
31
31
  "zod": "^3.21.4"
32
32
  },
33
33
  "scripts": {
34
34
  "build": "pkgroll --minify",
35
+ "build:clean": "rm -rf dist && pkgroll --minify",
35
36
  "dev": "pkgroll --watch",
36
- "test": "vitest --no-watch",
37
+ "test": "vitest run",
37
38
  "test:watch": "vitest",
38
39
  "test:coverage": "vitest run --coverage",
39
40
  "test:bench": "vitest bench --no-watch",
40
- "type-check": "tsc --noEmit",
41
- "ci": "pnpm type-check && pnpm test"
41
+ "test:bench:save": "vitest bench --no-watch --outputJson benchmarks/$(date +%Y-%m-%d)-results.json",
42
+ "test:bench:compare": "./scripts/bench-compare.sh",
43
+ "type-check": "tsc --noEmit"
42
44
  }
43
45
  }