@greensight/gts 1.0.0-alpha.12 → 1.0.0-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/index.cjs +2 -2
  2. package/index.mjs +3 -3
  3. package/package.json +1 -1
package/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
- "use strict";var ee=Object.defineProperty;var re=(s,e,r)=>e in s?ee(s,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[e]=r;var b=(s,e,r)=>re(s,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("path"),te=require("ts-import"),P=require("node:fs"),$=require("node:fs/promises"),x=require("node:path"),h=class h{static resolveReadPath(e){if(!e||!e.trim())throw new Error("File path must be a non-empty string");return x.resolve(h.baseDir,e)}static resolveWritePath(e,r){const t=x.resolve(h.baseDir,r??"");return{targetDir:t,targetPath:x.resolve(t,e)}}static handleReadError(e,r){throw e.code==="ENOENT"?new Error(`File not found: ${r}`):new Error(`Failed to read file "${r}": ${e.message??String(e)}`)}static async read(e,r="utf8"){const t=h.resolveReadPath(e);try{return await $.readFile(t,{encoding:r})}catch(o){h.handleReadError(o,t)}}static async readBuffer(e){const r=h.resolveReadPath(e);try{return await $.readFile(r)}catch(t){h.handleReadError(t,r)}}static async readJson(e){const r=h.resolveReadPath(e);try{const t=await $.readFile(r,{encoding:"utf8"});try{return JSON.parse(t)}catch(o){throw new Error(`Failed to parse JSON from "${r}": ${o.message}`)}}catch(t){h.handleReadError(t,r)}}static async write(e,r="",t={}){const{directory:o,overwrite:n=!0}=t,{targetDir:a,targetPath:i}=h.resolveWritePath(e,o);if(!n&&P.existsSync(i))throw new Error(`File ${i} already exists`);return await $.mkdir(a,{recursive:!0}),await $.writeFile(i,r,{encoding:"utf8"}),i}static async writeWithExtension(e,r,t="",o){const n=r.startsWith(".")?r:`.${r}`,a=`${e}${n}`;return h.write(a,t,o)}static exists(e){const r=h.resolveReadPath(e);return P.existsSync(r)}static async delete(e,r){const{targetPath:t}=h.resolveWritePath(e,r);P.existsSync(t)&&await $.rm(t,{force:!0})}};b(h,"baseDir",process.cwd());let y=h;const k=class k{static async create(){if(y.exists(k.configFileName))throw new Error("The file already exists");await y.write(k.configFileName,"",{overwrite:!1})}async load(){try{const e=await te.tsImport.compile(`${v.resolve(process.cwd(),k.configFileName)}`);if(!e)throw new Error;return e.default}catch(e){console.error("Cannot find module gts.config.ts",e)}}};b(k,"configFileName","gts.config.ts");let E=k;const oe=s=>{const e=new URLSearchParams;return Object.keys(s).forEach(r=>{Array.isArray(s[r])?s[r].forEach(t=>e.append(`${r}[]`,t)):e.append(r,s[r])}),e},se=(s,e=50)=>{const r=[];for(let t=0;t<s.length;t+=e)r.push(s.slice(t,t+e));return r};class V{constructor(e,r){b(this,"figmaToken");b(this,"fileId");b(this,"onTimeMeasureHandler");this.figmaToken=e,this.fileId=r}setOnTimeMeasureHandler(e){this.onTimeMeasureHandler=e}static async returnJSON(e){const r=await e.json();if(!e.ok){let t="Request failed";throw new Error(t)}return r}async performControlledRequest(e,{params:r={},timeout:t=3e4,abortController:o=new AbortController}={}){var g;if(!this.figmaToken||!this.fileId)throw new Error("Добавьте figmaToken и figmaId");const n=Object.entries(r).reduce((u,[p,w])=>typeof w<"u"?{...u,[p]:w}:u,{}),a=`https://api.figma.com/v1${e}${n&&Object.keys(n).length?`?${oe(n)}`:""}`;console.log("endpoinWithParams=",a);const i=setTimeout(()=>o.abort(),t),l={"Content-Type":"application/json",...this.figmaToken&&{"X-Figma-Token":this.figmaToken}},c={method:"GET",headers:l,signal:o.signal},f=performance.now(),d=await fetch(`${a}`,c);clearTimeout(i);const m=performance.now()-f;return(g=this.onTimeMeasureHandler)==null||g.call(this,a,l,m),d}async request(e,r){var o;const t=await this.performControlledRequest(e,{...r});return(o=t.headers.get("content-type"))!=null&&o.includes("application/json")?V.returnJSON(t):t}async getComponents(){return this.request(`/files/${this.fileId}/components`)}async getStyles(){return this.request(`/files/${this.fileId}/styles`)}async getNodes(e){const r=se(e).map(n=>this.request(`/files/${this.fileId}/nodes`,{params:{ids:n.join(",")}})),t=await Promise.all(r);return{...t[0],nodes:t.reduce((n,a)=>({...n,...a.nodes}),{})}}}const z=(s,e)=>{const r=Array.isArray(e)?e:e.split(".");let t=s;for(const o of r){if(t==null||typeof t!="object")return;t=t[o]}return t},X=(s,e)=>{if(!e||typeof e!="object")return s;if(!s||typeof s!="object")return e;const r={...s};for(const t in e)e.hasOwnProperty(t)&&(typeof e[t]=="object"&&e[t]!==null&&typeof r[t]=="object"&&r[t]!==null?r[t]=X(r[t],e[t]):r[t]=e[t]);return r};class Y{constructor(e){b(this,"tokensDir");b(this,"manifestPath");b(this,"variables");b(this,"styles");b(this,"loaded",!1);this.tokensDir=e||"",this.manifestPath=v.join(this.tokensDir,"manifest.json")}isLoaded(){return this.loaded&&!!this.variables&&!!this.styles}normalizeKey(e){const r=e.trim();return r&&r.replace(/[-_\s]+/g," ").split(" ").filter(t=>t.length).map((t,o)=>{const n=t.charAt(0),a=t.slice(1);return o===0?t:n.toUpperCase()+a}).join("")}parseVariableString(e){if(typeof e!="string")return e;const r=/^\{(.+)\}$/,t=e.match(r);if(t){const o=t[1].trim();return`{${this.normalizeKey(o)}}`}return e}createVariableFileList(e){return Object.entries(e).flatMap(([r,t])=>Object.entries(t.modes).flatMap(([o,n])=>n.map(a=>({fileName:a,modeName:this.normalizeKey(o.trim()),collectionName:r}))))}parseValue(e){return e&&(typeof e=="string"?this.parseVariableString(e):typeof e!="object"?e:(Array.isArray(e)&&e.map(r=>this.parseValue(r)),Object.entries(e).reduce((r,[t,o])=>({...r,[t]:this.parseValue(o)}),{})))}getTokensFromFile(e,r){return Object.entries(e).reduce((t,[o,n])=>"$type"in n&&"$value"in n?{...t,[this.normalizeKey(o)]:{type:n.$type,description:n.$description,value:r?{[this.normalizeKey(r)]:this.parseValue(n.$value)}:this.parseValue(n.$value)}}:{...t,[this.normalizeKey(o)]:this.getTokensFromFile(n,r)},{})}processTokensFile(e,r,t){const o=this.normalizeKey(t),n=this.getTokensFromFile(e,r);return{[o]:n}}async loadVariableFiles(e){return Promise.all(e.map(async({fileName:r,modeName:t,collectionName:o})=>{try{const n=v.join(this.tokensDir,r),a=await y.readJson(n);return this.processTokensFile(a,t,o)}catch(n){return console.warn(`Failed to load variable file: ${v.join(this.tokensDir,r)}`,n),{}}}))}mergeVariables(e){return e.reduce((r,t)=>X(r,t),{})}async loadTokenVariables(e){try{const r=this.createVariableFileList(e),t=await this.loadVariableFiles(r);return this.mergeVariables(t)}catch(r){throw new Error(`Failed to load token variables from ${this.tokensDir}: ${r}`)}}createStyleFileList(e){return Object.entries(e).flatMap(([r,t])=>(t==null?void 0:t.map(o=>({styleType:r,fileName:o})))||[])}async loadStyleFiles(e){return(await Promise.all(e.map(async({styleType:t,fileName:o})=>{try{const n=v.join(this.tokensDir,o),a=await y.readJson(n);return{styleType:t,styleTokens:a}}catch(n){return console.warn(`Failed to load style file: ${v.join(this.tokensDir,o)}`,n),{styleType:t,styleTokens:{}}}}))).reduce((t,o)=>({...t,[o.styleType]:this.getTokensFromFile(o.styleTokens,"")}),{})}async loadStyles(e){if(!e)return{};const r=this.createStyleFileList(e);return await this.loadStyleFiles(r)}async load(){if(this.loaded)return;const e=await y.readJson(this.manifestPath);if(!e)throw new Error(`Failed to load manifest file from: ${this.manifestPath}`);this.variables=await this.loadTokenVariables(e.collections),this.styles=await this.loadStyles(e.styles),this.loaded=!0}getVariables(){if(!this.loaded||!this.variables)throw new Error("Tokens not loaded. Call load() first.");return this.variables}getStyles(){if(!this.loaded||!this.styles)throw new Error("Tokens not loaded. Call load() first.");return this.styles}isVariableReference(e){return typeof e!="string"?!1:/^\{.+\}$/.test(e)}getVariablePath(e){return e.slice(1,-1)}getToken(e){if(!this.loaded||!this.variables)throw new Error("Tokens not loaded. Call load() first.");const r=z(this.variables,e);if(r&&typeof r=="object")return r;for(const[,t]of Object.entries(this.variables)){const o=z(t,e);if(o!=null&&o.value)return o}}}const ne=async()=>{const e=await new E().load();if(!e)throw new Error("Заполнить ошибку через нейронку");const{figmaToken:r,fileId:t,modules:o,manifest:n}=e,a=new V(r,t),i=new Y(n);n&&y.exists(n)&&await i.load(),await Promise.all(o.map(l=>l.executor({figmaApiClient:a,tokenManagerClient:i})))},ae=async()=>{await E.create(),console.log("\x1B[32m%s\x1B[0m","✔️ Configuration file created gts.config.ts")},ie=({r:s,g:e,b:r})=>{const t=o=>`0${o.toString(16)}`.slice(-2);return`#${t(s)}${t(e)}${t(r)}`},j=({opacity:s,r:e,g:r,b:t})=>{const o=[e,r,t].map(n=>Math.round(n*255));return s<1?`rgba(${o[0]}, ${o[1]}, ${o[2]}, ${s})`:ie({r:o[0],g:o[1],b:o[2]})},K=(s,e=0)=>{const r=Math.atan2(s[1].y-s[0].y,s[1].x-s[0].x);return Math.round(r*180/Math.PI)+e},M=s=>s.reduce((e,r)=>{const t=Number((r.position*100).toFixed(1));return[...e,`${j({opacity:r.color.a,r:r.color.r,g:r.color.g,b:r.color.b})}${t>0&&t<100?` ${t}%`:""}`]},[]).join(", "),U=s=>{const e=s[0].x,r=s[0].y,t=(e*100).toFixed(2),o=(r*100).toFixed(2);return{centerX:t,centerY:o}},le=s=>{const{gradientHandlePositions:e,gradientStops:r}=s,t=K(e,90),o=M(r);return`linear-gradient(${t}deg, ${o})`},ce=s=>{const e=s[0].x,r=s[0].y,t=s[1].x,o=s[1].y,n=s[2].x,a=s[2].y,i=(Math.sqrt((n-e)**2+(a-r)**2)*100).toFixed(2),l=(Math.sqrt((t-e)**2+(o-r)**2)*100).toFixed(2);return{radiusX:i,radiusY:l}},de=s=>{const{gradientHandlePositions:e,gradientStops:r}=s,{centerX:t,centerY:o}=U(e),{radiusX:n,radiusY:a}=ce(e),i=M(r);return`radial-gradient(${n}% ${a}% at ${t}% ${o}%, ${i})`},ue=s=>{const{gradientHandlePositions:e,gradientStops:r}=s,t=K(e,30),{centerX:o,centerY:n}=U(e),a=M(r);return`conic-gradient(from ${t}deg at ${o}% ${n}%, ${a})`},fe=s=>{const e=s.type;return e==="SOLID"?j({opacity:s.color.a,r:s.color.r,g:s.color.g,b:s.color.b}):e==="GRADIENT_LINEAR"?le(s):e==="GRADIENT_RADIAL"?de(s):e==="GRADIENT_ANGULAR"?ue(s):""},B=(s,e)=>{if(!e.length)return"";const r=e.map(t=>` ${t}`).join(`
1
+ "use strict";var ee=Object.defineProperty;var re=(s,e,r)=>e in s?ee(s,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):s[e]=r;var b=(s,e,r)=>re(s,typeof e!="symbol"?e+"":e,r);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const v=require("path"),te=require("ts-import"),P=require("node:fs"),$=require("node:fs/promises"),x=require("node:path"),h=class h{static resolveReadPath(e){if(!e||!e.trim())throw new Error("File path must be a non-empty string");return x.resolve(h.baseDir,e)}static resolveWritePath(e,r){const t=x.resolve(h.baseDir,r??"");return{targetDir:t,targetPath:x.resolve(t,e)}}static handleReadError(e,r){throw e.code==="ENOENT"?new Error(`File not found: ${r}`):new Error(`Failed to read file "${r}": ${e.message??String(e)}`)}static async read(e,r="utf8"){const t=h.resolveReadPath(e);try{return await $.readFile(t,{encoding:r})}catch(o){h.handleReadError(o,t)}}static async readBuffer(e){const r=h.resolveReadPath(e);try{return await $.readFile(r)}catch(t){h.handleReadError(t,r)}}static async readJson(e){const r=h.resolveReadPath(e);try{const t=await $.readFile(r,{encoding:"utf8"});try{return JSON.parse(t)}catch(o){throw new Error(`Failed to parse JSON from "${r}": ${o.message}`)}}catch(t){h.handleReadError(t,r)}}static async write(e,r="",t={}){const{directory:o,overwrite:n=!0}=t,{targetDir:a,targetPath:i}=h.resolveWritePath(e,o);if(!n&&P.existsSync(i))throw new Error(`File ${i} already exists`);return await $.mkdir(a,{recursive:!0}),await $.writeFile(i,r,{encoding:"utf8"}),i}static async writeWithExtension(e,r,t="",o){const n=r.startsWith(".")?r:`.${r}`,a=`${e}${n}`;return h.write(a,t,o)}static exists(e){const r=h.resolveReadPath(e);return P.existsSync(r)}static async delete(e,r){const{targetPath:t}=h.resolveWritePath(e,r);P.existsSync(t)&&await $.rm(t,{force:!0})}};b(h,"baseDir",process.cwd());let y=h;const k=class k{static async create(){if(y.exists(k.configFileName))throw new Error("The file already exists");await y.write(k.configFileName,"",{overwrite:!1})}async load(){try{const e=await te.tsImport.compile(`${v.resolve(process.cwd(),k.configFileName)}`);if(!e)throw new Error;return e.default}catch(e){console.error("Cannot find module gts.config.ts",e)}}};b(k,"configFileName","gts.config.ts");let E=k;const oe=s=>{const e=new URLSearchParams;return Object.keys(s).forEach(r=>{Array.isArray(s[r])?s[r].forEach(t=>e.append(`${r}[]`,t)):e.append(r,s[r])}),e},se=(s,e=50)=>{const r=[];for(let t=0;t<s.length;t+=e)r.push(s.slice(t,t+e));return r};class V{constructor(e,r){b(this,"figmaToken");b(this,"fileId");b(this,"onTimeMeasureHandler");this.figmaToken=e,this.fileId=r}setOnTimeMeasureHandler(e){this.onTimeMeasureHandler=e}static async returnJSON(e){const r=await e.json();if(!e.ok){let t="Request failed";throw new Error(t)}return r}async performControlledRequest(e,{params:r={},timeout:t=3e4,abortController:o=new AbortController}={}){var g;if(!this.figmaToken||!this.fileId)throw new Error("Добавьте figmaToken и figmaId");const n=Object.entries(r).reduce((u,[p,w])=>typeof w<"u"?{...u,[p]:w}:u,{}),a=`https://api.figma.com/v1${e}${n&&Object.keys(n).length?`?${oe(n)}`:""}`;console.log("endpoinWithParams=",a);const i=setTimeout(()=>o.abort(),t),l={"Content-Type":"application/json",...this.figmaToken&&{"X-Figma-Token":this.figmaToken}},c={method:"GET",headers:l,signal:o.signal},f=performance.now(),d=await fetch(`${a}`,c);clearTimeout(i);const m=performance.now()-f;return(g=this.onTimeMeasureHandler)==null||g.call(this,a,l,m),d}async request(e,r){var o;const t=await this.performControlledRequest(e,{...r});return(o=t.headers.get("content-type"))!=null&&o.includes("application/json")?V.returnJSON(t):t}async getComponents(){return this.request(`/files/${this.fileId}/components`)}async getStyles(){return this.request(`/files/${this.fileId}/styles`)}async getNodes(e){const r=se(e).map(n=>this.request(`/files/${this.fileId}/nodes`,{params:{ids:n.join(",")}})),t=await Promise.all(r);return{...t[0],nodes:t.reduce((n,a)=>({...n,...a.nodes}),{})}}}const z=(s,e)=>{const r=Array.isArray(e)?e:e.split(".");let t=s;for(const o of r){if(t==null||typeof t!="object")return;t=t[o]}return t},X=(s,e)=>{if(!e||typeof e!="object")return s;if(!s||typeof s!="object")return e;const r={...s};for(const t in e)e.hasOwnProperty(t)&&(typeof e[t]=="object"&&e[t]!==null&&typeof r[t]=="object"&&r[t]!==null?r[t]=X(r[t],e[t]):r[t]=e[t]);return r};class Y{constructor(e){b(this,"tokensDir");b(this,"manifestPath");b(this,"variables");b(this,"styles");b(this,"loaded",!1);this.tokensDir=e||"",this.manifestPath=v.join(this.tokensDir,"manifest.json")}isLoaded(){return this.loaded&&!!this.variables&&!!this.styles}normalizeKey(e){const r=e.trim();return r&&r.replace(/[-_\s]+/g," ").split(" ").filter(t=>t.length).map((t,o)=>{const n=t.charAt(0),a=t.slice(1);return o===0?t.toLowerCase():n.toUpperCase()+a}).join("")}parseVariableString(e){if(typeof e!="string")return e;const r=/^\{(.+)\}$/,t=e.match(r);if(t){const o=t[1].trim();return`{${this.normalizeKey(o)}}`}return e}createVariableFileList(e){return Object.entries(e).flatMap(([r,t])=>Object.entries(t.modes).flatMap(([o,n])=>n.map(a=>({fileName:a,modeName:this.normalizeKey(o.trim()),collectionName:r}))))}parseValue(e){return e&&(typeof e=="string"?this.parseVariableString(e):typeof e!="object"?e:(Array.isArray(e)&&e.map(r=>this.parseValue(r)),Object.entries(e).reduce((r,[t,o])=>({...r,[t]:this.parseValue(o)}),{})))}getTokensFromFile(e,r){return Object.entries(e).reduce((t,[o,n])=>"$type"in n&&"$value"in n?{...t,[this.normalizeKey(o)]:{type:n.$type,description:n.$description,value:r?{[this.normalizeKey(r)]:this.parseValue(n.$value)}:this.parseValue(n.$value)}}:{...t,[this.normalizeKey(o)]:this.getTokensFromFile(n,r)},{})}processTokensFile(e,r,t){const o=this.normalizeKey(t),n=this.getTokensFromFile(e,r);return{[o]:n}}async loadVariableFiles(e){return Promise.all(e.map(async({fileName:r,modeName:t,collectionName:o})=>{try{const n=v.join(this.tokensDir,r),a=await y.readJson(n);return this.processTokensFile(a,t,o)}catch(n){return console.warn(`Failed to load variable file: ${v.join(this.tokensDir,r)}`,n),{}}}))}mergeVariables(e){return e.reduce((r,t)=>X(r,t),{})}async loadTokenVariables(e){try{const r=this.createVariableFileList(e),t=await this.loadVariableFiles(r);return this.mergeVariables(t)}catch(r){throw new Error(`Failed to load token variables from ${this.tokensDir}: ${r}`)}}createStyleFileList(e){return Object.entries(e).flatMap(([r,t])=>(t==null?void 0:t.map(o=>({styleType:r,fileName:o})))||[])}async loadStyleFiles(e){return(await Promise.all(e.map(async({styleType:t,fileName:o})=>{try{const n=v.join(this.tokensDir,o),a=await y.readJson(n);return{styleType:t,styleTokens:a}}catch(n){return console.warn(`Failed to load style file: ${v.join(this.tokensDir,o)}`,n),{styleType:t,styleTokens:{}}}}))).reduce((t,o)=>({...t,[o.styleType]:this.getTokensFromFile(o.styleTokens,"")}),{})}async loadStyles(e){if(!e)return{};const r=this.createStyleFileList(e);return await this.loadStyleFiles(r)}async load(){if(this.loaded)return;const e=await y.readJson(this.manifestPath);if(!e)throw new Error(`Failed to load manifest file from: ${this.manifestPath}`);this.variables=await this.loadTokenVariables(e.collections),this.styles=await this.loadStyles(e.styles),this.loaded=!0}getVariables(){if(!this.loaded||!this.variables)throw new Error("Tokens not loaded. Call load() first.");return this.variables}getStyles(){if(!this.loaded||!this.styles)throw new Error("Tokens not loaded. Call load() first.");return this.styles}isVariableReference(e){return typeof e!="string"?!1:/^\{.+\}$/.test(e)}getVariablePath(e){return e.slice(1,-1)}getToken(e){if(!this.loaded||!this.variables)throw new Error("Tokens not loaded. Call load() first.");const r=z(this.variables,e);if(r&&typeof r=="object")return r;for(const[,t]of Object.entries(this.variables)){const o=z(t,e);if(o!=null&&o.value)return o}}}const ne=async()=>{const e=await new E().load();if(!e)throw new Error("Заполнить ошибку через нейронку");const{figmaToken:r,fileId:t,modules:o,manifest:n}=e,a=new V(r,t),i=new Y(n);n&&y.exists(n)&&await i.load(),await Promise.all(o.map(l=>l.executor({figmaApiClient:a,tokenManagerClient:i})))},ae=async()=>{await E.create(),console.log("\x1B[32m%s\x1B[0m","✔️ Configuration file created gts.config.ts")},ie=({r:s,g:e,b:r})=>{const t=o=>`0${o.toString(16)}`.slice(-2);return`#${t(s)}${t(e)}${t(r)}`},j=({opacity:s,r:e,g:r,b:t})=>{const o=[e,r,t].map(n=>Math.round(n*255));return s<1?`rgba(${o[0]}, ${o[1]}, ${o[2]}, ${s})`:ie({r:o[0],g:o[1],b:o[2]})},K=(s,e=0)=>{const r=Math.atan2(s[1].y-s[0].y,s[1].x-s[0].x);return Math.round(r*180/Math.PI)+e},M=s=>s.reduce((e,r)=>{const t=Number((r.position*100).toFixed(1));return[...e,`${j({opacity:r.color.a,r:r.color.r,g:r.color.g,b:r.color.b})}${t>0&&t<100?` ${t}%`:""}`]},[]).join(", "),U=s=>{const e=s[0].x,r=s[0].y,t=(e*100).toFixed(2),o=(r*100).toFixed(2);return{centerX:t,centerY:o}},le=s=>{const{gradientHandlePositions:e,gradientStops:r}=s,t=K(e,90),o=M(r);return`linear-gradient(${t}deg, ${o})`},ce=s=>{const e=s[0].x,r=s[0].y,t=s[1].x,o=s[1].y,n=s[2].x,a=s[2].y,i=(Math.sqrt((n-e)**2+(a-r)**2)*100).toFixed(2),l=(Math.sqrt((t-e)**2+(o-r)**2)*100).toFixed(2);return{radiusX:i,radiusY:l}},de=s=>{const{gradientHandlePositions:e,gradientStops:r}=s,{centerX:t,centerY:o}=U(e),{radiusX:n,radiusY:a}=ce(e),i=M(r);return`radial-gradient(${n}% ${a}% at ${t}% ${o}%, ${i})`},ue=s=>{const{gradientHandlePositions:e,gradientStops:r}=s,t=K(e,30),{centerX:o,centerY:n}=U(e),a=M(r);return`conic-gradient(from ${t}deg at ${o}% ${n}%, ${a})`},fe=s=>{const e=s.type;return e==="SOLID"?j({opacity:s.color.a,r:s.color.r,g:s.color.g,b:s.color.b}):e==="GRADIENT_LINEAR"?le(s):e==="GRADIENT_RADIAL"?de(s):e==="GRADIENT_ANGULAR"?ue(s):""},B=(s,e)=>{if(!e.length)return"";const r=e.map(t=>` ${t}`).join(`
2
2
  `);return`${s} {
3
3
  ${r}
4
4
  }`},ge=s=>`.${s.replace(/\s+/g,"-").toLowerCase()}`,he=s=>s.replaceAll(/ /g,"").split("/").at(-1),ye=s=>`--${s}`,me=s=>s.reduce((e,r)=>{const t=ye(r.name);return typeof r.value=="object"?Object.entries(r.value).forEach(([o,n])=>{e[o]||(e[o]=[]),e[o].push(`${t}: ${n};`)}):e.root.push(`${t}: ${r.value};`),e},{root:[]}),be=s=>{const e=B(":root",s.root),r=Object.entries(s).reduce((t,[o,n])=>{if(o==="root"||!n.length)return t;const a=B(ge(o),n);return a&&t.push(a),t},[]).join(`
5
5
 
6
6
  `);return[e,r].filter(Boolean).join(`
7
7
 
8
- `)},pe=s=>{const e=s.reduce((r,t)=>({...r,[t.name]:t.value}),{});return JSON.stringify(e)},we=async(s,e,r,t,o,n)=>{await Promise.all([y.delete(o,r),y.delete(n,t)]);const a=y.write(o,s,{directory:r}),i=y.write(n,e,{directory:t});await Promise.all([a,i])},R=async({colorTokens:s,jsonDir:e,stylesDir:r,jsonFileName:t,cssFileName:o})=>{const n=me(s),a=be(n),i=pe(s);await we(i,a,e,r,t,o)},$e=({input:s,output:{jsonDir:e,stylesDir:r,jsonFileName:t="colors.json",cssFileName:o="colors.css"}})=>({name:"styles/colors",executor:async({figmaApiClient:n})=>{try{console.log("[styles/colors] Fetching styles from Figma...");const i=(await n.getStyles()).meta.styles,l=(s==null?void 0:s.variablePaths)||[],c=i.filter(u=>u.style_type==="FILL");if(console.log(`[styles/colors] Found ${c.length} color styles`),c.length===0){console.warn("[styles/colors] No color styles found in Figma file");return}console.log(`[styles/colors] Fetching ${c.length} color nodes from Figma...`);const f=await n.getNodes(c.map(u=>u.node_id)),d=Object.entries(f.nodes);let m=[];if(l.length>1){console.log(`[styles/colors] Reading ${l.length} variable files...`);try{m=await Promise.all(l.map(async u=>{try{return await y.readJson(u)}catch(p){throw console.error(`[styles/colors] Failed to read variable file: ${u}`,p),p}}))}catch(u){throw console.error("[styles/colors] Error reading variable files:",u),new Error(`Failed to read variable files: ${u.message}`)}}console.log(`[styles/colors] Processing ${d.length} color nodes...`);const g=d.reduce((u,[,p])=>{var w,N,C;try{const{document:F}=p,A=he(F.name);if(F.type!=="RECTANGLE")return u;const S=(w=F.fills)==null?void 0:w[0];if(!S)return u;if(S.type==="SOLID"&&m.length>1){const L=(C=(N=S.boundVariables)==null?void 0:N.color)==null?void 0:C.id;if(L){const D=m.reduce((q,G)=>{var W;const J=(W=Object.entries(G).find(([,T])=>T.$extensions["com.figma.variableId"]===L))==null?void 0:W[1];if(J){const{components:T,alpha:Z}=J.$value,_=j({opacity:Z,r:T[0],g:T[1],b:T[2]});return{...q,[G.$extensions["com.figma.modeName"]]:_}}return q},{});if(Object.keys(D).length>1)return[...u,{name:A,value:D}]}}const I=fe(S);return I?[...u,{name:A,value:I}]:u}catch(F){return console.warn("[styles/colors] Error processing color node:",F),u}},[]);if(console.log(`[styles/colors] Generated ${g.length} color tokens`),g.length===0){console.warn("[styles/colors] No color tokens generated. Check your Figma styles configuration.");return}console.log(`[styles/colors] Writing files to ${e} and ${r}...`),await R({colorTokens:g,jsonDir:e,stylesDir:r,jsonFileName:t,cssFileName:o}),console.log("[styles/colors] ✅ Successfully generated color files")}catch(a){const i=a instanceof Error?a.message:String(a);throw console.error("[styles/colors] ❌ Failed to generate colors from styles:",i),a instanceof Error&&a.stack&&console.error("[styles/colors] Stack trace:",a.stack),a}}}),ve=({input:{variablePaths:s},output:{jsonDir:e,stylesDir:r,jsonFileName:t="colors.json",cssFileName:o="colors.css"}})=>({name:"variables/colors",executor:async()=>{try{if(!s.length)throw new Error("At least one variable file path is required");console.log(`[variables/colors] Reading ${s.length} variable files...`);const n=await Promise.all(s.map(async l=>{try{return console.log(`[variables/colors] Reading file: ${l}`),await y.readJson(l)}catch(c){throw console.error(`[variables/colors] Failed to read variable file: ${l}`,c),new Error(`Failed to read variable file "${l}": ${c.message}`)}}));console.log(`[variables/colors] Processing ${n.length} variable files...`);const a=new Map;n.forEach((l,c)=>{try{if(!l.$extensions||!l.$extensions["com.figma.modeName"]){console.warn(`[variables/colors] File ${s[c]} is missing modeName in extensions`);return}const f=l.$extensions["com.figma.modeName"];Object.entries(l).forEach(([d,m])=>{if(d!=="$extensions")try{const g=m;if(!g||g.$type!=="color")return;if(!g.$value||!g.$value.components){console.warn(`[variables/colors] Variable "${d}" in mode "${f}" has invalid structure`);return}const{components:u,alpha:p}=g.$value,w=j({opacity:p??1,r:u[0],g:u[1],b:u[2]});a.has(d)||a.set(d,{}),a.get(d)[f]=w}catch(g){console.warn(`[variables/colors] Error processing variable "${d}" in mode "${f}":`,g)}})}catch(f){console.error(`[variables/colors] Error processing file ${s[c]}:`,f)}});const i=Array.from(a.entries()).map(([l,c])=>({name:l,value:Object.keys(c).length>1?c:Object.values(c)[0]}));if(console.log(`[variables/colors] Generated ${i.length} color tokens`),i.length===0){console.warn("[variables/colors] No color tokens generated. Check your variable files structure.");return}console.log(`[variables/colors] Writing files to ${e} and ${r}...`),await R({colorTokens:i,jsonDir:e,stylesDir:r,jsonFileName:t,cssFileName:o}),console.log("[variables/colors] ✅ Successfully generated color files")}catch(n){const a=n instanceof Error?n.message:String(n);throw console.error("[variables/colors] ❌ Failed to generate colors from variables:",a),n instanceof Error&&n.stack&&console.error("[variables/colors] Stack trace:",n.stack),n}}}),H=(s,e)=>Object.keys(s).reduce((r,t)=>{const o=s[t],n=e?`${e}-${t}`:t;if(o&&typeof o=="object"&&"type"in o&&"value"in o){const i=Object.keys(o.value),l=i.length>1?o.value:o.value[i[0]],c={[n]:l};return{...r,...c}}const a=H(o,n);return{...r,...a}},{}),ke=s=>`cl-${s}`,O=(s,e,r)=>{const{type:t,value:o}=s;if(t!=="color")return;if(typeof o=="string"){if(!e.isVariableReference(o))return{...s,value:o};const i=e.getToken(e.getVariablePath(o)),l=i?O(i,e,r):void 0;return l!=null&&l.value?{...s,...i}:void 0}const a=Object.keys(o).reduce((i,l)=>{if(r&&l!==r)return i;const c=o[l];if(typeof c!="string")return i;if(!e.isVariableReference(c))return{...i,[l]:c};const f=e.getToken(e.getVariablePath(c)),d=f?O(f,e,l):void 0;return d!=null&&d.value?{...i,...d.value}:i},{});if(Object.keys(a).length)return{...s,value:a}},Q=(s,e)=>Object.keys(s).reduce((r,t)=>{const o=s[t];if(o.type&&o.value){const a=O(o,e);return a?{...r,[t]:a}:r}const n=Q(o,e);return n?{...r,[t]:n}:r},{}),Fe=({input:s={},output:{jsonDir:e,stylesDir:r,jsonFileName:t="colors.json",cssFileName:o="colors.css"}})=>({name:"colors/tokenManager",executor:async({tokenManagerClient:n})=>{try{console.log("[colors/tokenManager] Generating colors from TokenManager...");const{includeVariables:a,includeStyles:i=!0}=s;if(!(a!=null&&a.length)&&!i)throw new Error("Either includeVariables or includeStyles must be enabled");if(!n.isLoaded())throw new Error("TokenManager is not loaded. Tokens must be loaded before using this module.");const l=[],c=n.getVariables();if(i){const d=n.getStyles();console.log("[colors/tokenManager] Processing styles for colors..."),d.color&&l.push(d.color)}if(a!=null&&a.length){console.log(`[colors/tokenManager] Processing ${a.length} variable groups...`);const d=a.map(m=>c[m]).filter(Boolean);l.push(...d)}const f=l.map(d=>Q(d,n)).flatMap(d=>Object.entries(H(d,"")).reduce((m,[g,u])=>[...m,{name:ke(g),value:u}],[]));if(f.length===0){console.warn("[colors/tokenManager] No color tokens generated");return}console.log(`[colors/tokenManager] Generated ${f.length} color tokens`),console.log(`[colors/tokenManager] Writing files to ${e} and ${r}...`),await R({colorTokens:f,jsonDir:e,stylesDir:r,jsonFileName:t,cssFileName:o}),console.log("[colors/tokenManager] ✅ Successfully generated color files")}catch(a){const i=a instanceof Error?a.message:String(a);throw console.error("[colors/tokenManager] ❌ Failed to generate colors:",i),a instanceof Error&&a.stack&&console.error("[colors/tokenManager] Stack trace:",a.stack),a}}});exports.TokenManager=Y;exports.colorsFromStyles=$e;exports.colorsFromTokenManager=Fe;exports.colorsFromVariables=ve;exports.generate=ne;exports.init=ae;
8
+ `)},pe=s=>{const e=s.reduce((r,t)=>({...r,[t.name]:t.value}),{});return JSON.stringify(e)},we=async(s,e,r,t,o,n)=>{await Promise.all([y.delete(o,r),y.delete(n,t)]);const a=y.write(o,s,{directory:r}),i=y.write(n,e,{directory:t});await Promise.all([a,i])},R=async({colorTokens:s,jsonDir:e,stylesDir:r,jsonFileName:t,cssFileName:o})=>{const n=me(s),a=be(n),i=pe(s);await we(i,a,e,r,t,o)},$e=({input:s,output:{jsonDir:e,stylesDir:r,jsonFileName:t="colors.json",cssFileName:o="colors.css"}})=>({name:"styles/colors",executor:async({figmaApiClient:n})=>{try{console.log("[styles/colors] Fetching styles from Figma...");const i=(await n.getStyles()).meta.styles,l=(s==null?void 0:s.variablePaths)||[],c=i.filter(u=>u.style_type==="FILL");if(console.log(`[styles/colors] Found ${c.length} color styles`),c.length===0){console.warn("[styles/colors] No color styles found in Figma file");return}console.log(`[styles/colors] Fetching ${c.length} color nodes from Figma...`);const f=await n.getNodes(c.map(u=>u.node_id)),d=Object.entries(f.nodes);let m=[];if(l.length>1){console.log(`[styles/colors] Reading ${l.length} variable files...`);try{m=await Promise.all(l.map(async u=>{try{return await y.readJson(u)}catch(p){throw console.error(`[styles/colors] Failed to read variable file: ${u}`,p),p}}))}catch(u){throw console.error("[styles/colors] Error reading variable files:",u),new Error(`Failed to read variable files: ${u.message}`)}}console.log(`[styles/colors] Processing ${d.length} color nodes...`);const g=d.reduce((u,[,p])=>{var w,C,N;try{const{document:F}=p,A=he(F.name);if(F.type!=="RECTANGLE")return u;const S=(w=F.fills)==null?void 0:w[0];if(!S)return u;if(S.type==="SOLID"&&m.length>1){const L=(N=(C=S.boundVariables)==null?void 0:C.color)==null?void 0:N.id;if(L){const D=m.reduce((q,G)=>{var W;const J=(W=Object.entries(G).find(([,T])=>T.$extensions["com.figma.variableId"]===L))==null?void 0:W[1];if(J){const{components:T,alpha:Z}=J.$value,_=j({opacity:Z,r:T[0],g:T[1],b:T[2]});return{...q,[G.$extensions["com.figma.modeName"]]:_}}return q},{});if(Object.keys(D).length>1)return[...u,{name:A,value:D}]}}const I=fe(S);return I?[...u,{name:A,value:I}]:u}catch(F){return console.warn("[styles/colors] Error processing color node:",F),u}},[]);if(console.log(`[styles/colors] Generated ${g.length} color tokens`),g.length===0){console.warn("[styles/colors] No color tokens generated. Check your Figma styles configuration.");return}console.log(`[styles/colors] Writing files to ${e} and ${r}...`),await R({colorTokens:g,jsonDir:e,stylesDir:r,jsonFileName:t,cssFileName:o}),console.log("[styles/colors] ✅ Successfully generated color files")}catch(a){const i=a instanceof Error?a.message:String(a);throw console.error("[styles/colors] ❌ Failed to generate colors from styles:",i),a instanceof Error&&a.stack&&console.error("[styles/colors] Stack trace:",a.stack),a}}}),ve=({input:{variablePaths:s},output:{jsonDir:e,stylesDir:r,jsonFileName:t="colors.json",cssFileName:o="colors.css"}})=>({name:"variables/colors",executor:async()=>{try{if(!s.length)throw new Error("At least one variable file path is required");console.log(`[variables/colors] Reading ${s.length} variable files...`);const n=await Promise.all(s.map(async l=>{try{return console.log(`[variables/colors] Reading file: ${l}`),await y.readJson(l)}catch(c){throw console.error(`[variables/colors] Failed to read variable file: ${l}`,c),new Error(`Failed to read variable file "${l}": ${c.message}`)}}));console.log(`[variables/colors] Processing ${n.length} variable files...`);const a=new Map;n.forEach((l,c)=>{try{if(!l.$extensions||!l.$extensions["com.figma.modeName"]){console.warn(`[variables/colors] File ${s[c]} is missing modeName in extensions`);return}const f=l.$extensions["com.figma.modeName"];Object.entries(l).forEach(([d,m])=>{if(d!=="$extensions")try{const g=m;if(!g||g.$type!=="color")return;if(!g.$value||!g.$value.components){console.warn(`[variables/colors] Variable "${d}" in mode "${f}" has invalid structure`);return}const{components:u,alpha:p}=g.$value,w=j({opacity:p??1,r:u[0],g:u[1],b:u[2]});a.has(d)||a.set(d,{}),a.get(d)[f]=w}catch(g){console.warn(`[variables/colors] Error processing variable "${d}" in mode "${f}":`,g)}})}catch(f){console.error(`[variables/colors] Error processing file ${s[c]}:`,f)}});const i=Array.from(a.entries()).map(([l,c])=>({name:l,value:Object.keys(c).length>1?c:Object.values(c)[0]}));if(console.log(`[variables/colors] Generated ${i.length} color tokens`),i.length===0){console.warn("[variables/colors] No color tokens generated. Check your variable files structure.");return}console.log(`[variables/colors] Writing files to ${e} and ${r}...`),await R({colorTokens:i,jsonDir:e,stylesDir:r,jsonFileName:t,cssFileName:o}),console.log("[variables/colors] ✅ Successfully generated color files")}catch(n){const a=n instanceof Error?n.message:String(n);throw console.error("[variables/colors] ❌ Failed to generate colors from variables:",a),n instanceof Error&&n.stack&&console.error("[variables/colors] Stack trace:",n.stack),n}}}),H=(s,e)=>Object.keys(s).reduce((r,t)=>{const o=s[t],n=e?`${e}-${t}`:t;if(o&&typeof o=="object"&&"type"in o&&"value"in o){const i=Object.keys(o.value),l=i.length>1?o.value:o.value[i[0]],c={[n]:l};return{...r,...c}}const a=H(o,n);return{...r,...a}},{}),ke=s=>`cl-${s}`,O=(s,e,r)=>{const{type:t,value:o}=s;if(t!=="color")return;if(typeof o=="string"){if(!e.isVariableReference(o))return{...s,value:o};const i=e.getToken(e.getVariablePath(o)),l=i?O(i,e,r):void 0;return l!=null&&l.value?{...s,...i}:void 0}const a=Object.keys(o).reduce((i,l)=>{if(r&&l!==r)return i;const c=o[l];if(typeof c!="string")return i;if(!e.isVariableReference(c))return{...i,[l]:c};const f=e.getToken(e.getVariablePath(c)),d=f?O(f,e,l):void 0;return d!=null&&d.value?{...i,...d.value}:i},{});if(Object.keys(a).length)return{...s,value:a}},Q=(s,e)=>Object.keys(s).reduce((r,t)=>{const o=s[t];if(o.type&&o.value){const a=O(o,e);return a?{...r,[t]:a}:r}const n=Q(o,e);return n?{...r,[t]:n}:r},{}),Fe=({input:s={},output:{jsonDir:e,stylesDir:r,jsonFileName:t="colors.json",cssFileName:o="colors.css"}})=>({name:"colors/tokenManager",executor:async({tokenManagerClient:n})=>{try{console.log("[colors/tokenManager] Generating colors from TokenManager...");const{includeVariables:a,includeStyles:i=!0}=s;if(!(a!=null&&a.length)&&!i)throw new Error("Either includeVariables or includeStyles must be enabled");if(!n.isLoaded())throw new Error("TokenManager is not loaded. Tokens must be loaded before using this module.");const l=[],c=n.getVariables();if(i){const d=n.getStyles();console.log("[colors/tokenManager] Processing styles for colors..."),d.color&&l.push(d.color)}if(a!=null&&a.length){console.log(`[colors/tokenManager] Processing ${a.length} variable groups...`);const d=a.map(m=>c[m]).filter(Boolean);l.push(...d)}const f=l.map(d=>Q(d,n)).flatMap(d=>Object.entries(H(d,"")).reduce((m,[g,u])=>[...m,{name:ke(g),value:u}],[]));if(f.length===0){console.warn("[colors/tokenManager] No color tokens generated");return}console.log(`[colors/tokenManager] Generated ${f.length} color tokens`),console.log(`[colors/tokenManager] Writing files to ${e} and ${r}...`),await R({colorTokens:f,jsonDir:e,stylesDir:r,jsonFileName:t,cssFileName:o}),console.log("[colors/tokenManager] ✅ Successfully generated color files")}catch(a){const i=a instanceof Error?a.message:String(a);throw console.error("[colors/tokenManager] ❌ Failed to generate colors:",i),a instanceof Error&&a.stack&&console.error("[colors/tokenManager] Stack trace:",a.stack),a}}});exports.TokenManager=Y;exports.colorsFromStyles=$e;exports.colorsFromTokenManager=Fe;exports.colorsFromVariables=ve;exports.generate=ne;exports.init=ae;
package/index.mjs CHANGED
@@ -200,7 +200,7 @@ class ie {
200
200
  const r = e.trim();
201
201
  return r && r.replace(/[-_\s]+/g, " ").split(" ").filter((t) => t.length).map((t, o) => {
202
202
  const n = t.charAt(0), a = t.slice(1);
203
- return o === 0 ? t : n.toUpperCase() + a;
203
+ return o === 0 ? t.toLowerCase() : n.toUpperCase() + a;
204
204
  }).join("");
205
205
  }
206
206
  /**
@@ -510,14 +510,14 @@ ${r}
510
510
  }
511
511
  console.log(`[styles/colors] Processing ${d.length} color nodes...`);
512
512
  const g = d.reduce((u, [, p]) => {
513
- var w, N, C;
513
+ var w, C, N;
514
514
  try {
515
515
  const { document: k } = p, A = me(k.name);
516
516
  if (k.type !== "RECTANGLE") return u;
517
517
  const T = (w = k.fills) == null ? void 0 : w[0];
518
518
  if (!T) return u;
519
519
  if (T.type === "SOLID" && y.length > 1) {
520
- const L = (C = (N = T.boundVariables) == null ? void 0 : N.color) == null ? void 0 : C.id;
520
+ const L = (N = (C = T.boundVariables) == null ? void 0 : C.color) == null ? void 0 : N.id;
521
521
  if (L) {
522
522
  const D = y.reduce((G, J) => {
523
523
  var z;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@greensight/gts",
3
- "version": "1.0.0-alpha.12",
3
+ "version": "1.0.0-alpha.13",
4
4
  "description": "Generate design tokens from Figma",
5
5
  "keywords": [
6
6
  "figma",