@mcastiello/figmatic
Version:
2 lines (1 loc) • 32.2 kB
JavaScript
import{EventBus as e}from"@mcastiello/event-bus";function t(){return t=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var o in n)({}).hasOwnProperty.call(n,o)&&(e[o]=n[o])}return e},t.apply(null,arguments)}function n(e,t){if(null==e)return{};var n={};for(var o in e)if({}.hasOwnProperty.call(e,o)){if(-1!==t.indexOf(o))continue;n[o]=e[o]}return n}var o,a,s,i,r,l,c,d,h,u,p,g,f,m,S,T,E,A,D,I,y,w,N,C,b,k,O,L,R,v,F,M,x,P,B,G,$,_,V,H,W,U;!function(e){e.BooleanOperation="BOOLEAN_OPERATION",e.Canvas="CANVAS",e.Component="COMPONENT",e.ComponentSet="COMPONENT_SET",e.Document="DOCUMENT",e.Ellipse="ELLIPSE",e.Frame="FRAME",e.Generic="NODE",e.Group="GROUP",e.Instance="INSTANCE",e.Line="LINE",e.Rectangle="RECTANGLE",e.RegularPolygon="REGULAR_POLYGON",e.Section="SECTION",e.Slice="SLICE",e.Star="STAR",e.Text="TEXT",e.Vector="VECTOR",e.WashiTape="WASHI_TAPE"}(o||(o={})),function(e){e.VariableAlias="VARIABLE_ALIAS"}(a||(a={})),function(e){e.Scale="SCALE",e.Width="WIDTH",e.Height="HEIGHT"}(s||(s={})),function(e){e.Solid="SOLID",e.GradientLinear="GRADIENT_LINEAR",e.GradientRadial="GRADIENT_RADIAL",e.GradientAngular="GRADIENT_ANGULAR",e.GradientDiamond="GRADIENT_DIAMOND",e.Image="IMAGE",e.Emoji="EMOJI",e.Video="VIDEO"}(i||(i={})),function(e){e.PassThrough="PASS_THROUGH",e.Normal="NORMAL",e.Darken="DARKEN",e.Multiply="MULTIPLY",e.LinearBurn="LINEAR_BURN",e.ColorBurn="COLOR_BURN",e.Lighten="LIGHTEN",e.Screen="SCREEN",e.LinearDodge="LINEAR_DODGE",e.ColorDodge="COLOR_DODGE",e.Overlay="OVERLAY",e.SoftLight="SOFT_LIGHT",e.HardLight="HARD_LIGHT",e.Difference="DIFFERENCE",e.Exclusion="EXCLUSION",e.Hue="HUE",e.Saturation="SATURATION",e.Color="COLOR",e.Luminosity="LUMINOSITY"}(r||(r={})),function(e){e.Fill="FILL",e.Fit="FIT",e.Tile="TILE",e.Stretch="STRETCH"}(l||(l={})),function(e){e.Inside="INSIDE",e.Outside="OUTSIDE",e.Center="CENTER"}(c||(c={})),function(e){e.Top="TOP",e.Bottom="BOTTOM",e.Center="CENTER",e.TopBottom="TOP_BOTTOM",e.Scale="SCALE"}(d||(d={})),function(e){e.Left="LEFT",e.Right="RIGHT",e.Center="CENTER",e.LeftRight="LEFT_RIGHT",e.Scale="SCALE"}(h||(h={})),function(e){e.Inherit="INHERIT",e.Stretch="STRETCH",e.Min="MIN",e.Center="CENTER",e.Max="MAX"}(u||(u={})),function(e){e.None="NONE",e.Horizontal="HORIZONTAL",e.Vertical="VERTICAL"}(p||(p={})),function(e){e.Fixed="FIXED",e.Hug="HUG",e.Fill="FILL"}(g||(g={})),function(e){e.NoWrap="NO_WRAP",e.Wrap="WRAP"}(f||(f={})),function(e){e.Auto="AUTO",e.Absolute="ABSOLUTE"}(m||(m={})),function(e){e.Columns="COLUMNS",e.Rows="ROWS",e.Grid="GRID"}(S||(S={})),function(e){e.Fixed="FIXED",e.Auto="AUTO"}(T||(T={})),function(e){e.Auto="AUTO",e.Min="MIN",e.Center="CENTER",e.Max="MAX",e.SpaceBetween="SPACE_BETWEEN",e.Baseline="BASELINE"}(E||(E={})),function(e){e.None="NONE",e.Horizontal="HORIZONTAL_SCROLLING",e.Vertical="VERTICAL_SCROLLING",e.Both="HORIZONTAL_AND_VERTICAL_SCROLLING"}(A||(A={})),function(e){e.InnerShadow="INNER_SHADOW",e.DropShadow="DROP_SHADOW",e.LayerBlur="LAYER_BLUR",e.BackgroundBlur="BACKGROUND_BLUR"}(D||(D={})),function(e){e.Alpha="ALPHA",e.Vector="VECTOR",e.Luminance="LUMINANCE"}(I||(I={})),function(e){e.Fill="FILL",e.Text="TEXT",e.Effect="EFFECT",e.Grid="GRID"}(y||(y={})),function(e){e.ReadyForDev="READY_FOR_DEV",e.Completed="COMPLETED"}(w||(w={})),function(e){e.Width="width",e.Height="height",e.MaxWidth="maxWidth",e.MinWidth="minWidth",e.MaxHeight="maxHeight",e.MinHeight="minHeight",e.Fills="fills",e.Strokes="strokes",e.Effects="effects",e.StrokeWeight="strokeWeight",e.CornerRadius="cornerRadius",e.TextStyleId="textStyleId",e.TextAlignHorizontal="textAlignHorizontal",e.FontFamily="fontFamily",e.FontStyle="fontStyle",e.FontSize="fontSize",e.FontWeight="fontWeight",e.LineHeight="lineHeight",e.LetterSpacing="letterSpacing",e.ItemSpacing="itemSpacing",e.Padding="padding",e.LayoutMode="layoutMode",e.AlignItems="alignItems",e.Opacity="opacity",e.MainComponent="mainComponent"}(N||(N={})),function(e){e.None="NONE",e.Round="ROUND",e.Square="SQUARE",e.LineArrow="LINE_ARROW",e.TriangleArrow="TRIANGLE_ARROW",e.DiamondFilled="DIAMOND_FILLED",e.CircleFilled="CIRCLE_FILLED",e.TriangleFilled="TRIANGLE_FILLED",e.WashiTape1="WASHI_TAPE_1",e.WashiTape2="WASHI_TAPE_2",e.WashiTape3="WASHI_TAPE_3",e.WashiTape4="WASHI_TAPE_4",e.WashiTape5="WASHI_TAPE_5",e.WashiTape6="WASHI_TAPE_6"}(C||(C={})),function(e){e.Bevel="BEVEL",e.Miter="MITER",e.Round="ROUND"}(b||(b={})),function(e){e.Exclude="EXCLUDE",e.Intersect="INTERSECT",e.Subtract="SUBTRACT",e.Union="UNION"}(k||(k={})),function(e){e.Lower="LOWER",e.Original="ORIGINAL",e.SmallCaps="SMALL_CAPS",e.SmallCapsForced="SMALL_CAPS_FORCED",e.Title="TITLE",e.Upper="UPPER"}(O||(O={})),function(e){e.None="NONE",e.Strikethrough="STRIKETHROUGH",e.Underline="UNDERLINE"}(L||(L={})),function(e){e.Height="HEIGHT",e.None="NONE",e.WidthHeight="WIDTH_AND_HEIGHT"}(R||(R={})),function(e){e.Disabled="DISABLED",e.Enabled="ENABLED"}(v||(v={})),function(e){e.Left="LEFT",e.Right="RIGHT",e.Center="CENTER",e.Justified="JUSTIFIED"}(F||(F={})),function(e){e.Top="TOP",e.Center="CENTER",e.Bottom="BOTTOM"}(M||(M={})),function(e){e.Url="URL",e.Node="NODE"}(x||(x={})),function(e){e.Pixels="PIXELS",e.FontSize="FONT_SIZE_%",e.Intrinsic="INTRINSIC_%"}(P||(P={})),function(e){e.Bold="BOLD",e.Normal="NORMAL"}(B||(B={})),function(e){e.Italic="ITALIC",e.Normal="NORMAL"}(G||(G={})),function(e){e.Ordered="ORDERED",e.Unordered="UNORDERED",e.None="NONE"}($||($={})),function(e){e.Boolean="BOOLEAN",e.InstanceSwap="INSTANCE_SWAP",e.Text="TEXT",e.Variant="VARIANT"}(_||(_={})),function(e){e.Boolean="BOOLEAN",e.Float="FLOAT",e.String="STRING",e.Color="COLOR"}(V||(V={})),function(e){e.AllFills="ALL_FILLS",e.AllScopes="ALL_SCOPES",e.CornerRadius="CORNER_RADIUS",e.EffectColor="EFFECT_COLOR",e.EffectFloat="EFFECT_FLOAT",e.FontFamily="FONT_FAMILY",e.FontSize="FONT_SIZE",e.FontStyle="FONT_STYLE",e.FontWeight="FONT_WEIGHT",e.FrameFill="FRAME_FILL",e.Gap="GAP",e.LetterSpacing="LETTER_SPACING",e.LineHeight="LINE_HEIGHT",e.Opacity="OPACITY",e.ParagraphIndent="PARAGRAPH_INDENT",e.ParagraphSpacing="PARAGRAPH_SPACING",e.ShapeFill="SHAPE_FILL",e.StrokeColor="STROKE_COLOR",e.StrokeFloat="STROKE_FLOAT",e.TextContent="TEXT_CONTENT",e.TextFill="TEXT_FILL",e.WidthHeight="WIDTH_HEIGHT"}(H||(H={})),function(e){e.JPG="jpg",e.PDF="pdf",e.PNG="png",e.SVG="svg"}(W||(W={})),function(e){e.Fill="fill",e.Fills="fills",e.Stroke="stroke",e.Strokes="strokes",e.Effect="effect",e.Text="text"}(U||(U={}));const j=e=>Object.values(o).includes(e),z=e=>"object"==typeof e&&Object.hasOwn(e,"type"),X=e=>"string"==typeof(null==e?void 0:e.type)&&j(e.type),J=(e,t)=>"string"==typeof(null==e?void 0:e.type)&&e.type===t&&j(e.type),Z=(e,t)=>!!e&&e.type===t,Y=e=>!!e&&Object.hasOwn(e,"styles"),K=e=>!!e&&Object.hasOwn(e,"exportSettings");var q,Q,ee;!function(e){e.Figmatic="figmatic"}(q||(q={})),function(e){e.Message="message",e.LoadStarted="loadStarted",e.LoadCompleted="loadCompleted",e.SwitchBranchStarted="switchBranchStarted",e.SwitchBranchCompleted="switchBranchCompleted",e.BranchDownloadStarted="branchDownloadStarted",e.BranchDownloadCompleted="branchDownloadCompleted",e.BranchDownloadFailed="branchDownloadFailed",e.TokensDownloadStarted="tokensDownloadStarted",e.TokensDownloadCompleted="tokensDownloadCompleted",e.TokensDownloadFailed="tokensDownloadFailed",e.GraphicDownloadStarted="graphicDownloadStarted",e.GraphicDownloadCompleted="graphicDownloadCompleted",e.GraphicDownloadFailed="graphicDownloadFailed",e.ParseNodesStarted="parseNodesStarted",e.ParseNodesCompleted="parseNodesCompleted",e.ParseNodesFailed="parseNodesFailed",e.ParseComponentsStarted="parseComponentsStarted",e.ParseComponentsCompleted="parseComponentsCompleted",e.ParseComponentsFailed="parseComponentsFailed",e.ParseTokensStarted="parseTokensStarted",e.ParseTokensCompleted="parseTokensCompleted",e.ParseTokensFailed="parseTokensFailed"}(Q||(Q={})),function(e){e.Debug="debug",e.Info="info",e.Warning="warning",e.Error="error"}(ee||(ee={}));const te={cacheEvents:!0,publishAsynchronously:!0},ne=new Map,oe=new Map,ae=new Map,se=new Map,ie=new Map;class re extends Map{getByType(e){return Array.from(this.values()).filter(t=>Z(t,e))}getByName(e){const t=[];if(e instanceof RegExp){const n=Array.from(new Set(Array.from(ne.keys()).filter(t=>e.test(t)).map(e=>ne.get(e)||[]).reduce((e,t)=>[...e,...t],[])));t.push(...n)}else{const n=ne.get(e)||[];t.push(...n)}return(null==t?void 0:t.map(e=>this.get(e)).filter(e=>!!e))||[]}clear(){super.clear(),ne.clear()}get(e){return super.get(e)}}const le=new re;class ce{constructor(e){this.data=void 0,this.data=e}get definition(){return this.data}get variantNodes(){if(0===this.data.variants.length){const e=le.get(this.data.nodeId);return e?[e]:[]}return this.data.variants.map(({nodeId:e})=>le.get(e)).filter(e=>void 0!==e)}}const de=new class{constructor(){this.bus=new e(te)}get channel(){return this.bus.getChannel(q.Figmatic)}log(e,t=ee.Info,n=Date.now(),o){this.channel.publish(Q.Message,{message:e,severity:t,timestamp:n,data:o})}};class he extends Map{constructor(...e){super(...e),this.plugins=new Map}registerExportPlugin(e,t="default"){this.plugins.set(t,e)}getPlugin(e){return this.plugins.get(e)}async generateExport(e="default"){const t={},n=this.plugins.get(e);if(n){try{de.log("Export tokens",ee.Debug);const e=await n.processor.generateTokens();t[e.name]=e.content}catch(e){de.log("Error while generating tokens",ee.Error,Date.now(),{error:e})}for(const e of this.values())try{de.log(`Export component "${e.definition.name}"`,ee.Debug);const o=await n.processor.generateComponent(e);t[o.name]=o.content}catch(t){de.log(`Error while exporting component "${e.definition.name}"`,ee.Error,Date.now(),{error:t})}}return t}}const ue=new he;class pe{constructor(e){this.color=void 0,this.h=void 0,this.s=void 0,this.l=void 0,this.color=t({a:1},e);const n=Math.max(this.color.r,this.color.g,this.color.b),o=Math.min(this.color.r,this.color.g,this.color.b);let a=0,s=0;const i=(n+o)/2;if(n==o)a=s=0;else{const e=n-o;switch(s=i>.5?e/(2-n-o):e/(n+o),n){case this.color.r:a=(this.color.g-this.color.b)/e+(this.color.g<this.color.b?6:0);break;case this.color.g:a=(this.color.b-this.color.r)/e+2;break;case this.color.b:a=(this.color.r-this.color.g)/e+4}a/=6}this.h=a,this.s=s,this.l=i}get red(){return Math.round(255*this.color.r)}get green(){return Math.round(255*this.color.g)}get blue(){return Math.round(255*this.color.b)}get alpha(){return this.color.a}get hue(){return this.h}get saturation(){return this.s}get lightness(){return this.s}get hsl(){return`hsl(${this.hue}, ${this.saturation}, ${this.lightness})`}get hsla(){return`hsla(${this.hue}, ${this.saturation}, ${this.lightness}, ${this.alpha})`}get rgb(){return`rgb(${this.red}, ${this.green}, ${this.blue})`}get rgba(){return`rgba(${this.red}, ${this.green}, ${this.blue}, ${this.alpha})`}get hex(){return`#${this.red.toString(16).padStart(2,"0")}${this.green.toString(16).padStart(2,"0")}${this.blue.toString(16).padStart(2,"0")}`}toString(e=!1){return e?1!==this.alpha?this.hsla:this.hsl:1!==this.alpha?this.rgba:this.hex}}const ge=[o.BooleanOperation,o.Ellipse,o.Line,o.Rectangle,o.RegularPolygon,o.Slice,o.Star,o.Vector,o.WashiTape],fe={[W.JPG]:"image/jpeg",[W.PNG]:"image/png",[W.SVG]:"image/svg+xml",[W.PDF]:"application/pdf"},me={[U.Fill]:"fills",[U.Fills]:"fills",[U.Stroke]:"strokes",[U.Strokes]:"strokes",[U.Text]:"style",[U.Effect]:"effects"},Se="https://api.figma.com/v1",Te=new class{constructor(){this.token=void 0,this.fileName=void 0,this.batchSize=25}setToken(e){this.token=e}setBatchSize(e){this.batchSize=e}getBatchSize(){return this.batchSize}async getFigmaFile(e){if(this.token){this.fileName=e;const t=await fetch(`${Se}/files/${this.fileName}`,{method:"GET",headers:{"Content-Type":"application/json","Accept-Charset":"UTF-8","X-Figma-Token":this.token}});return await t.json()}}async getLocalVariables(){if(this.token){const e=await fetch(`${Se}/files/${this.fileName}/variables/local`,{method:"GET",headers:{"Content-Type":"application/json","Accept-Charset":"UTF-8","X-Figma-Token":this.token}});return await e.json()}}async getPublishedVariables(){if(this.token){const e=await fetch(`${Se}/files/${this.fileName}/variables/published`,{method:"GET",headers:{"Content-Type":"application/json","Accept-Charset":"UTF-8","X-Figma-Token":this.token}});return await e.json()}}calculateSize(e){return(e instanceof ArrayBuffer?e.byteLength:e.length)/1024}calculateTotalSize(e){return`${e.reduce((e,t)=>e+this.calculateSize(t),0).toFixed(2)}Kb`}async downloadBatchOfGraphicNodes(e,t=W.SVG,n=1){const o={};if(this.token){de.log(`Creating export for ${e.length} graphic nodes`,ee.Debug);const a=await fetch(`${Se}/images/${this.fileName}?ids=${e}&scale=${n}&format=${t}`,{method:"GET",headers:{"Content-Type":"application/json","Accept-Charset":"UTF-8","X-Figma-Token":this.token}});de.log("Export created",ee.Debug);const s=await a.json();de.log(`Preparing download of ${Object.keys(s).length} image files`,ee.Debug);for(const[e,n]of Object.entries(s.images))if(de.log(`Download of file ${n}`,ee.Debug),n){const a=await fetch(n,{method:"GET",headers:{"Content-Type":fe[t],"Accept-Charset":"UTF-8"}});o[e]=t===W.SVG?await a.text():await a.arrayBuffer(),de.log(`Download completed: ${this.calculateTotalSize([o[e]])}`,ee.Debug)}}return o}async downloadGraphicNodes(e,n=W.SVG,o=1){let a={};if(this.token){const s=[];for(;e.length>0;)s.push(e.splice(0,this.batchSize));de.log(`Graphic nodes will be downloaded in ${s.length} batches`,ee.Debug);for(let e=0;e<s.length;e++)de.log(`Start exporting batch ${e+1}...`,ee.Debug),a=t({},a,await this.downloadBatchOfGraphicNodes(s[e],n,o))}return a}};class Ee{log(e,t=ee.Info,n){de.log(e,t,Date.now(),n)}}class Ae extends Ee{async getSvgData(e,t=1){try{const n=await Te.downloadGraphicNodes([e],W.SVG,t),o=Object.values(n).shift();if("string"==typeof o)return o}catch(t){this.log(`Download of graphic node "${e}" failed`,ee.Error,{error:t})}}async getImageData(e,t,n=1){try{const o=await Te.downloadGraphicNodes([e],t,n),a=Object.values(o).shift();if(a instanceof ArrayBuffer)return a}catch(t){this.log(`Download of graphic node "${e}" failed`,ee.Error,{error:t})}}}class De{constructor(e,t){this.data=void 0,this.childrenIds=void 0,this.data=e,this.childrenIds=t}get children(){return this.childrenIds.map(e=>ie.get(e)).filter(e=>!!e)}get name(){return this.data.styles.name}get definition(){return this.data}}class Ie{log(e,t=ee.Info,n){de.log(e,t,Date.now(),n)}getParsedNode(e){return ie.get(e)}}class ye extends Map{getByCollection(e){var t;const n=oe.get(e);return(null==n||null==(t=n.variableIds)?void 0:t.map(e=>this.get(e)).filter(e=>!!e))||[]}getCollection(e){return oe.get(e)}getCollections(){return Array.from(oe.values())}setStyle(e,t){ae.set(e,t)}getStyle(e){const n=se.get(e),o=ae.get(e);if(n&&o)return t({id:e},n,{data:o})}getStyles(){return Array.from(se.keys()).map(e=>this.getStyle(e)).filter(e=>!!e)}getByKey(e){var t;if(e=(null==(t=e.split("/").shift())?void 0:t.replace("VariableID:",""))||"")return Array.from(this.values()).find(t=>t.key===e)}getModeName(e){var t;return null==(t=this.getCollections().reduce((e,t)=>[...e,...t.modes],[]).find(t=>t.modeId===e))?void 0:t.name}resolveTokenVariable(e){const n=this.get(e)||this.getByKey(e);return n?Object.keys(n.valuesByMode).reduce((e,o)=>{const a=n.valuesByMode[o];if(z(a)){const n=this.resolveTokenVariable(a.id);return t({},e,Object.keys(n).reduce((e,a)=>t({},e,{[a!==o?`${o}+${a}`:a]:null==n?void 0:n[a]}),{}))}return t({},e,{[o]:"object"==typeof a?new pe(a):a})},{}):{}}clear(){super.clear(),oe.clear(),se.clear(),ae.clear()}}const we=new ye,Ne=["id","type","children"];class Ce{get DefaultValues(){return{componentPropertyReferences:{},explicitVariableModes:{},rotation:0,visible:!0}}constructor(e,o){if(this.nodeId=void 0,this.nodeType=void 0,this.data=void 0,this.childrenIds=void 0,this.parentId=void 0,X(e)){const{id:a,type:s,children:i}=e,r=n(e,Ne);this.nodeId=a,this.nodeType=s,this.parentId=o,this.data=t({},this.DefaultValues,r),this.childrenIds=null==i?void 0:i.map(({id:e})=>e)}}get id(){return this.nodeId}get type(){return this.nodeType}get name(){var e;return null==(e=this.data)?void 0:e.name}get definition(){return this.data}get valid(){return!!this.nodeId}get children(){var e;return(null==(e=this.childrenIds)?void 0:e.map(e=>le.get(e)).filter(e=>!!e&&e.valid))||[]}get parent(){return this.parentId?le.get(this.parentId):void 0}get isGraphicNode(){var e;return ge.includes(this.nodeType)||K(this.data)&&(null==(e=this.data.exportSettings)?void 0:e.length)>0}getTokens(e){var t;if(null!=(t=this.data)&&t.boundVariables){const t=this.data.boundVariables[e];return(Array.isArray(t)?t:t?[t]:[]).map(({id:e})=>we.get(e)).filter(e=>!!e)}return[]}isDescendant(e){return!!e&&!!this.parent&&(this.parent.id===e||this.parent.isDescendant(e))}getNodesByType(e){return le.getByType(e).filter(e=>e.isDescendant(this.id))}get styles(){const e=t({},this.data);return Y(e)?Object.keys(e.styles).reduce((n,o)=>{var a;const s=null==(a=e.styles)?void 0:a[o],i=e[me[o]],r=Array.isArray(i)?i[0]:i;return s&&r?t({},n,{[s]:r}):n},{}):{}}}class be extends Ce{get DefaultValues(){return t({},super.DefaultValues,{effects:[],exportSettings:[],fills:[],isMask:!1,layoutGrow:0,locked:!1,opacity:1,preserveRatio:!1,strokeCap:C.None,strokeJoin:b.Miter,strokeMiterAngle:28.96,strokes:[]})}}class ke extends Ce{get DefaultValues(){return t({},super.DefaultValues,{exportSettings:[]})}}class Oe extends Ce{get DefaultValues(){return t({},super.DefaultValues,{annotations:[],componentPropertyDefinitions:{},counterAxisAlignContent:E.Auto,counterAxisAlignItems:E.Min,counterAxisSpacing:0,effects:[],exportSettings:[],fills:[],isMask:!1,isMaskOutline:!1,itemReverseZIndex:!1,itemSpacing:0,layoutMode:p.None,layoutPositioning:m.Auto,layoutWrap:f.NoWrap,locked:!1,opacity:1,overflowDirection:A.None,paddingBottom:0,paddingLeft:0,paddingRight:0,paddingTop:0,preserveRatio:!1,primaryAxisAlignItems:E.Min,primaryAxisSizingMode:T.Auto,strokes:[],strokesIncludedInLayout:!1,styles:{}})}}class Le extends Ce{get DefaultValues(){return t({},super.DefaultValues,{annotations:[],componentPropertyDefinitions:{},counterAxisAlignContent:E.Auto,counterAxisAlignItems:E.Min,counterAxisSpacing:0,effects:[],exportSettings:[],fills:[],isMask:!1,isMaskOutline:!1,itemReverseZIndex:!1,itemSpacing:0,layoutMode:p.None,layoutPositioning:m.Auto,layoutWrap:f.NoWrap,locked:!1,opacity:1,overflowDirection:A.None,paddingBottom:0,paddingLeft:0,paddingRight:0,paddingTop:0,preserveRatio:!1,primaryAxisAlignItems:E.Min,primaryAxisSizingMode:T.Auto,strokes:[],strokesIncludedInLayout:!1,styles:{}})}}class Re extends Ce{}class ve extends Ce{get DefaultValues(){return t({},super.DefaultValues,{effects:[],exportSettings:[],fills:[],isMask:!1,layoutGrow:0,locked:!1,opacity:1,preserveRatio:!1,strokeCap:C.None,strokeJoin:b.Miter,strokeMiterAngle:28.96,strokes:[]})}}class Fe extends Ce{get DefaultValues(){return t({},super.DefaultValues,{annotations:[],counterAxisAlignContent:E.Auto,counterAxisAlignItems:E.Min,counterAxisSpacing:0,effects:[],exportSettings:[],fills:[],isMask:!1,isMaskOutline:!1,itemReverseZIndex:!1,itemSpacing:0,layoutMode:p.None,layoutPositioning:m.Auto,layoutWrap:f.NoWrap,locked:!1,opacity:1,overflowDirection:A.None,paddingBottom:0,paddingLeft:0,paddingRight:0,paddingTop:0,preserveRatio:!1,primaryAxisAlignItems:E.Min,primaryAxisSizingMode:T.Auto,strokes:[],strokesIncludedInLayout:!1,styles:{}})}}class Me extends Ce{get DefaultValues(){return t({},super.DefaultValues,{annotations:[],counterAxisAlignContent:E.Auto,counterAxisAlignItems:E.Min,counterAxisSpacing:0,effects:[],exportSettings:[],fills:[],isMask:!1,isMaskOutline:!1,itemReverseZIndex:!1,itemSpacing:0,layoutMode:p.None,layoutPositioning:m.Auto,layoutWrap:f.NoWrap,locked:!1,opacity:1,overflowDirection:A.None,paddingBottom:0,paddingLeft:0,paddingRight:0,paddingTop:0,preserveRatio:!1,primaryAxisAlignItems:E.Min,primaryAxisSizingMode:T.Auto,strokes:[],strokesIncludedInLayout:!1,styles:{}})}}const xe=["children"];class Pe extends Ce{get DefaultValues(){return t({},super.DefaultValues,{annotations:[],componentProperties:{},counterAxisAlignContent:E.Auto,counterAxisAlignItems:E.Min,counterAxisSpacing:0,effects:[],exportSettings:[],exposedInstances:[],fills:[],isExposedInstance:!1,isMask:!1,isMaskOutline:!1,itemReverseZIndex:!1,itemSpacing:0,layoutMode:p.None,layoutPositioning:m.Auto,layoutWrap:f.NoWrap,locked:!1,opacity:1,overflowDirection:A.None,overrides:[],paddingBottom:0,paddingLeft:0,paddingRight:0,paddingTop:0,preserveRatio:!1,primaryAxisAlignItems:E.Min,primaryAxisSizingMode:T.Auto,strokes:[],strokesIncludedInLayout:!1,styles:{}})}constructor(e,t){let o=[];if(X(e)){const{children:t}=e;e=n(e,xe),o=(null==t?void 0:t.map(({id:e})=>e))||[]}super(e,t),this.overrideIds=void 0,this.overrideIds=o}get overrides(){var e;return null==(e=this.overrideIds)?void 0:e.map(e=>le.get(e)).filter(e=>!!e&&e.valid)}get component(){var e;return null!=(e=this.data)&&e.componentId?le.get(this.data.componentId):void 0}}class Be extends Ce{get DefaultValues(){return t({},super.DefaultValues,{effects:[],exportSettings:[],fills:[],isMask:!1,layoutGrow:0,locked:!1,opacity:1,preserveRatio:!1,strokeCap:C.None,strokeJoin:b.Miter,strokeMiterAngle:28.96,strokes:[]})}}class Ge extends Ce{get DefaultValues(){return t({},super.DefaultValues,{effects:[],exportSettings:[],fills:[],isMask:!1,layoutGrow:0,locked:!1,opacity:1,preserveRatio:!1,strokeCap:C.None,strokeJoin:b.Miter,strokeMiterAngle:28.96,strokes:[]})}}class $e extends Ce{get DefaultValues(){return t({},super.DefaultValues,{effects:[],exportSettings:[],fills:[],isMask:!1,layoutGrow:0,locked:!1,opacity:1,preserveRatio:!1,strokeCap:C.None,strokeJoin:b.Miter,strokeMiterAngle:28.96,strokes:[]})}}class _e extends Ce{get DefaultValues(){return t({},super.DefaultValues,{fills:[],strokes:[]})}}class Ve extends Ce{get DefaultValues(){return t({},super.DefaultValues,{effects:[],exportSettings:[],fills:[],isMask:!1,layoutGrow:0,locked:!1,opacity:1,preserveRatio:!1,strokeCap:C.None,strokeJoin:b.Miter,strokeMiterAngle:28.96,strokes:[]})}}class He extends Ce{get DefaultValues(){return t({},super.DefaultValues,{locked:!1,exportSettings:[],preserveRatio:!1,layoutGrow:0,opacity:1,fills:[],strokes:[],effects:[],isMask:!1,strokeCap:C.None,strokeJoin:b.Miter,strokeMiterAngle:28.96})}get content(){var e;return(null==(e=this.data)?void 0:e.characters)||""}}class We extends Ce{get DefaultValues(){return t({},super.DefaultValues,{locked:!1,exportSettings:[],preserveRatio:!1,layoutGrow:0,opacity:1,fills:[],strokes:[],effects:[],isMask:!1,strokeCap:C.None,strokeJoin:b.Miter,strokeMiterAngle:28.96})}}class Ue extends Ce{get DefaultValues(){return t({},super.DefaultValues,{effects:[],exportSettings:[],fills:[],isMask:!1,layoutGrow:0,locked:!1,opacity:1,preserveRatio:!1,strokeCap:C.None,strokeJoin:b.Miter,strokeMiterAngle:28.96,strokes:[]})}}const je=new class{parseComponents(e,t={},n={}){[...Object.keys(n).filter(e=>!n[e].componentSetId).map(t=>({nodeId:t,name:n[t].name,description:n[t].description,variants:[],fileName:e})),...Object.keys(t).map(o=>{const a=Object.keys(n).filter(e=>n[e].componentSetId===o).map(e=>({nodeId:e,name:n[e].name,description:n[e].description}));return{nodeId:o,name:t[o].name,description:t[o].description,variants:a,fileName:e}})].forEach(e=>{const t=new ce(e);ue.set(e.nodeId,t),e.variants.forEach(({nodeId:e})=>ue.set(e,t))})}parseNodes(e,t,n){let a;if(J(e,o.BooleanOperation)&&(a=new be(e,n)),J(e,o.Canvas)&&(!X(e)||t&&0!==t.length&&!t.some(t=>t instanceof RegExp?t.test(e.name):t.toLowerCase()===e.name.toLowerCase())||(a=new ke(e,n))),J(e,o.ComponentSet)&&(a=new Le(e,n)),J(e,o.Component)&&(a=new Oe(e,n)),J(e,o.Document)&&(a=new Re(e,n)),J(e,o.Ellipse)&&(a=new ve(e,n)),J(e,o.Frame)&&(a=new Fe(e,n)),J(e,o.Group)&&(a=new Me(e,n)),J(e,o.Instance)&&(a=new Pe(e,n)),J(e,o.Line)&&(a=new Be(e,n)),J(e,o.Rectangle)&&(a=new Ge(e,n)),J(e,o.RegularPolygon)&&(a=new $e(e,n)),J(e,o.Section)&&(a=new _e(e,n)),J(e,o.Star)&&(a=new Ve(e,n)),J(e,o.Text)&&(a=new He(e,n)),J(e,o.Vector)&&(a=new We(e,n)),J(e,o.WashiTape)&&(a=new Ue(e,n)),a&&a.id){const n=a.id;if(le.set(n,a),a.name){const e=ne.get(a.name)||[];ne.set(a.name,[...e,n])}var s;Object.entries(a.styles).map(([e,t])=>{we.setStyle(e,t)}),X(e)&&(null==(s=e.children)||s.forEach(e=>this.parseNodes(e,t,n)))}}parseTokens(e,t={}){null!=e&&e.meta&&(Object.values(e.meta.variables).forEach(e=>{we.set(e.id,e)}),Object.values(e.meta.variableCollections).forEach(e=>{oe.set(e.id,e)}),Object.entries(t).forEach(([e,t])=>{se.set(e,t)}))}async generateParsedNodes(e){for(const n of le.values()){const o=n.type,a=n.id;if(o&&a&&Z(n,o))if(n.isGraphicNode&&e.graphicParser){var t;if(null==(t=n.parent)||!t.isGraphicNode){const t=await e.graphicParser.parse(n);ie.set(a,new De(t,[]))}}else{const t=e.parsers[o];if(t){const e=await t.parse(n),o=n.children.map(e=>e.id).filter(e=>!!e)||[],s=new De(e,o);ie.set(a,s)}}}}},ze=new class{constructor(){this.file=void 0,this.branch=void 0,this.pageFilters=void 0,this.data=new Map,this.variables=new Map}getDuration(e,t){const n=t-e;return`${Math.floor(n/1e3/60).toString().padStart(2,"0")}:${Math.floor(n/1e3%60).toString().padStart(2,"0")}.${Math.floor(n%1e3).toString().padStart(3,"0")}`}subscribe(e,t,n){return de.channel.subscribe(e,t,n)}async load(e,t,n){this.file=e,this.branch=void 0,this.pageFilters=n,Te.setToken(t);const o=Date.now();de.channel.publish(Q.LoadStarted),de.log(`Load Figma file "${e}" started`,ee.Info,o),this.data.get(e)||await this.downloadSelectedBranch(),this.parseFigmaFile();const a=Date.now();de.channel.publish(Q.LoadCompleted),de.log(`Loading completed:\n\t- Duration: ${this.getDuration(o,a)}`,ee.Info,a)}get selectedBranch(){return this.branch||this.file}get graphicBatchSize(){return Te.getBatchSize()}set graphicBatchSize(e){Te.setBatchSize(e)}async downloadBranch(e){try{de.channel.publish(Q.BranchDownloadStarted,{branch:e}),de.log(`Download of branch "${e}" started`,ee.Debug);const t=await Te.getFigmaFile(e);if(!t)throw new Error("File not downloaded");this.data.set(e,t),de.channel.publish(Q.BranchDownloadCompleted,{branch:e}),de.log(`Download of branch "${e}" completed`,ee.Debug)}catch(t){de.channel.publish(Q.BranchDownloadFailed,t),de.log(`Download of branch "${e}" failed`,ee.Error,Date.now(),{error:t})}try{var n,o,a,s;de.channel.publish(Q.TokensDownloadStarted,{branch:e}),de.log(`Download of tokens for "${e}" started`,ee.Debug);const i=await Te.getLocalVariables(),r=await Te.getPublishedVariables();this.variables.set(e,{meta:{variables:t({},null==r||null==(n=r.meta)?void 0:n.variables,null==i||null==(o=i.meta)?void 0:o.variables),variableCollections:t({},null==r||null==(a=r.meta)?void 0:a.variableCollections,null==i||null==(s=i.meta)?void 0:s.variableCollections)}}),de.channel.publish(Q.TokensDownloadCompleted,{branch:e}),de.log(`Download of tokens for branch "${e}" completed`,ee.Debug)}catch(t){de.channel.publish(Q.TokensDownloadFailed,t),de.log(`Download of tokens for branch "${e}" failed`,ee.Error,Date.now(),{error:t})}}async downloadSelectedBranch(){if(this.selectedBranch)return this.downloadBranch(this.selectedBranch)}parseFigmaFile(){if(this.selectedBranch){const e=this.data.get(this.selectedBranch),t=this.variables.get(this.selectedBranch);if(e){try{const t=Date.now();de.channel.publish(Q.ParseNodesStarted),de.log(`Parsing of nodes for "${this.selectedBranch}" started`,ee.Debug,t,{filters:this.pageFilters}),je.parseNodes(e.document,this.pageFilters);const n=Date.now();de.channel.publish(Q.ParseNodesCompleted),de.log(`Parsing of nodes for "${this.selectedBranch}" completed:\n\t- Total nodes: ${le.size}\n\t- Pages: ${le.getByType(o.Canvas).length}\n\t- Duration: ${this.getDuration(t,n)}`,ee.Info,n,{filters:this.pageFilters})}catch(e){de.channel.publish(Q.ParseNodesFailed,e),de.log(`Parsing of nodes for branch "${this.selectedBranch}" failed`,ee.Error,Date.now(),{error:e})}try{de.channel.publish(Q.ParseComponentsStarted),de.log(`Parsing of components for "${this.selectedBranch}" started`,ee.Debug),je.parseComponents(this.selectedBranch,e.componentSets,e.components),de.channel.publish(Q.ParseComponentsCompleted),de.log(`Parsing of components for "${this.selectedBranch}" completed:\n\t- Total components: ${ue.size}`)}catch(e){de.channel.publish(Q.ParseComponentsFailed,e),de.log(`Parsing of components for branch "${this.selectedBranch}" failed`,ee.Error,Date.now(),{error:e})}try{de.channel.publish(Q.ParseTokensStarted),de.log(`Parsing of tokens for "${this.selectedBranch}" started`,ee.Debug),t&&je.parseTokens(t,e.styles),de.channel.publish(Q.ParseTokensCompleted),de.log(`Parsing of tokens for "${this.selectedBranch}" completed:\n\t- Total tokens: ${we.size}\n\t- Collections: ${we.getCollections().length}\n\t- Styles: ${we.getStyles().length}`,ee.Info)}catch(e){de.channel.publish(Q.ParseTokensFailed,e),de.log(`Parsing of tokens for branch "${this.selectedBranch}" failed`,ee.Error,Date.now(),{error:e})}}}}clear(){le.clear(),ue.clear(),we.clear()}async downloadGraphics(e,t=W.SVG,n=1){if(this.selectedBranch)try{const o=Date.now(),a=e.map(({name:e,id:t})=>e||t).filter(e=>!!e);de.channel.publish(Q.GraphicDownloadStarted,{nodes:a,format:t,scale:n}),de.log("Download of graphic elements started",ee.Info,o);const s=e.map(e=>e.id).filter(e=>!!e),i=await Te.downloadGraphicNodes(s,t,n),r=Date.now();return de.channel.publish(Q.GraphicDownloadCompleted,{nodes:a,format:t,scale:n}),de.log(`Download of graphic elements completed:\n\t- Total downloads: ${Object.keys(i).length}\n\t- Duration: ${this.getDuration(o,r)}\n\t- Total Size: ${Te.calculateTotalSize(Object.values(i))}`,ee.Info,o),i}catch(e){de.channel.publish(Q.GraphicDownloadFailed,e),de.log("Download of graphic elements failed",ee.Error,Date.now(),{error:e})}return{}}async selectBranch(e){if(e!==this.branch&&this.file){if(e){const t=this.data.get(this.file);null!=t&&t.branches.map(({name:e})=>e).includes(e)&&(this.branch=e)}else this.branch=void 0;if(this.selectedBranch&&!this.data.get(this.selectedBranch)){const e=Date.now();de.channel.publish(Q.SwitchBranchStarted,{branch:this.selectedBranch}),de.log(`Switch to branch "${this.selectedBranch}" started`,ee.Info,e),await this.downloadSelectedBranch(),this.parseFigmaFile();const t=Date.now();de.channel.publish(Q.SwitchBranchCompleted,{branch:this.selectedBranch}),de.log(`Switch to branch "${this.selectedBranch}" completed: ${this.getDuration(e,t)}`,ee.Info,t)}}}registerExportPlugin(e,t="default"){ue.registerExportPlugin(e,t)}async generateExport(e="default"){const t=ue.getPlugin(e);if(t&&this.selectedBranch){const n=Date.now();de.log("Start parsing nodes",ee.Info,n),await je.generateParsedNodes(t);const o=Date.now();de.log(`Parsing of nodes completed\n\t- Total nodes parsed: ${ie.size}\n\t- Duration: ${this.getDuration(n,o)}`,ee.Info,o),de.log("Start generating exported files",ee.Info,o);const a=await ue.generateExport(e),s=Date.now();return de.log(`Export completed\n\t- Total files generated: ${Object.values(a).length}\n\t- Duration: ${this.getDuration(o,s)}`,ee.Info,s),a}return{}}};export{N as AnnotationProperty,E as AxisAlign,T as AxisSizing,r as BlendMode,k as BooleanOperation,_ as ComponentPropertyType,s as ConstraintType,w as DevStatusType,D as EffectType,W as ExportFormat,ze as Figmatic,Q as FigmaticEvents,ee as FigmaticSeverity,G as FontStyle,B as FontWeight,Ae as GraphicParser,h as HorizontalLayoutConstrain,x as HyperlinkType,u as LayoutAlign,S as LayoutGridPattern,p as LayoutMode,m as LayoutPositioning,g as LayoutSizing,f as LayoutWrap,P as LineHeightUnit,$ as LineType,I as MaskType,o as NodeType,le as NodesCollection,A as OverflowDirection,i as PaintType,Ee as Parser,Ie as Processor,a as PropertyTypes,l as ScaleMode,c as StrokeAlign,C as StrokeCap,b as StrokeJoin,y as StyleType,F as TextAlignHorizontal,M as TextAlignVertical,R as TextAutoResize,O as TextCase,L as TextDecoration,v as TextTruncation,U as TokenStyleTypes,we as TokensCollection,H as VariableScope,V as VariableType,d as VerticalLayoutConstraint,K as isExportableNode,X as isNodeData,j as isNodeType,Y as isStyledNode,Z as isTypedNode,J as isTypedNodeData,z as isVariableAlias};