@spiffcommerce/core 39.2.1 → 39.2.2

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.cjs CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";var Sr=Object.create;var dn=Object.defineProperty;var vr=Object.getOwnPropertyDescriptor;var Er=Object.getOwnPropertyNames;var br=Object.getPrototypeOf,Ir=Object.prototype.hasOwnProperty;var Br=(i,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Er(t))!Ir.call(i,n)&&n!==e&&dn(i,n,{get:()=>t[n],enumerable:!(a=vr(t,n))||a.enumerable});return i};var Pr=(i,t,e)=>(e=i!=null?Sr(br(i)):{},Br(t||!i||!i.__esModule?dn(e,"default",{value:i,enumerable:!0}):e,i));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("@apollo/client/core"),xr=require("@apollo/client/link/context"),Fr=require("@apollo/client/link/error"),Dr=require("preact-render-to-string"),kr=require("@apollo/client/link/remove-typename"),Mr=require("exifr/dist/mini.umd.cjs"),Vn=require("css"),Tr=require("fuse.js"),Qa=require("pith"),pa=require("lodash.chunk"),Pt=require("lodash.clonedeep"),B=require("preact/jsx-runtime"),fa=require("opentype.js"),Nr=require("html-entities"),Qr=require("handlebars"),Rr=require("data-uri-to-buffer"),we=require("@aws-sdk/client-cognito-identity-provider"),Or=require("dinero.js"),$r=require("currency-codes"),Un=require("lodash.debounce"),ae=require("lodash.isequal"),Ca=require("unicode-default-word-boundary"),Ln=require("qrcode"),Vr=require("svg-path-bbox");require("fs");require("path");const Ur=require("lodash.omit");function Lr(i){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const e in i)if(e!=="default"){const a=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,a.get?a:{enumerable:!0,get:()=>i[e]})}}return t.default=i,Object.freeze(t)}const un=Lr($r);var ne=(i=>(i.Data="Data",i.Font="Font",i.Frame="Frame",i.Illustration="Illustration",i.Image="Image",i.Model="Model",i.Material="Material",i.Color="Color",i.QuestionnaireCollateral="QuestionnaireCollateral",i.RequestCollateral="RequestCollateral",i.SignupCollateral="SignupCollateral",i.Video="Video",i.ColorProfile="ColorProfile",i.Environment="Environment",i))(ne||{}),zn=(i=>(i.AND="AND",i.OR="OR",i))(zn||{}),z=(i=>(i.FileUpload="FileUpload",i.Option="Option",i.ColorOption="ColorOption",i.Text="Text",i))(z||{}),E=(i=>(i.Information="Information",i.Bulk="Bulk",i.DigitalContent="DigitalContent",i.Finish="Finish",i.Frame="Frame",i.Illustration="Illustration",i.Introduction="Introduction",i.Material="Material",i.Model="Model",i.Module="Module",i.Picture="Picture",i.Photo="Photo",i.ProductOverlay="ProductOverlay",i.Question="Question",i.Shape="Shape",i.SilentIllustration="SilentIllustration",i.Text="Text",i))(E||{}),qn=(i=>(i.Color="Color",i.Colors="Colors",i.Selection="Selection",i.Selections="Selections",i.Text="Text",i.Upload="Upload",i))(qn||{}),Rt=(i=>(i.ThreeD="ThreeD",i.FreeDesign="FreeDesign",i.Print="Print",i))(Rt||{}),D=(i=>(i.Frame="frame",i.Group="group",i.Image="image",i.Pattern="pattern",i.Illustration="illustration",i.Textbox="textbox",i))(D||{}),Gn=(i=>(i.Default="Default",i.FirstTransaction="FirstTransaction",i.OneToOne="OneToOne",i))(Gn||{}),Ra=(i=>(i.Pending="Pending",i.Failed="Failed",i.Validated="Validated",i.Overridden="Overridden",i))(Ra||{}),jn=(i=>(i.Hyperlink="Hyperlink",i.Edit="Edit",i.Approve="Approve",i))(jn||{}),Hn=(i=>(i.Hub="Hub",i.Shopify="Shopify",i))(Hn||{}),Ue=(i=>(i.BackgroundRemover="BackgroundRemover",i.ConversionAccelerator="Conversion Accelerator",i.ProcessBuilder="ProcessBuilder",i))(Ue||{}),Wn=(i=>(i[i.Orbit=0]="Orbit",i[i.Pan=1]="Pan",i))(Wn||{}),Oa=(i=>(i.Owner="Owner",i.Approver="Approver",i.Editor="Editor",i.Viewer="Viewer",i))(Oa||{}),xt=(i=>(i.Autosize="Autosize",i.Traditional="Traditional",i))(xt||{}),Y=(i=>(i[i.North=0]="North",i[i.Northeast=1]="Northeast",i[i.East=2]="East",i[i.Southeast=3]="Southeast",i[i.South=4]="South",i[i.Southwest=5]="Southwest",i[i.West=6]="West",i[i.Northwest=7]="Northwest",i))(Y||{}),Yn=(i=>(i.Pixel="px",i.Millimeter="mm",i.Centimeter="cm",i))(Yn||{});class Jn extends Error{constructor(t){super(t),this.name=this.constructor.name}}class le extends Jn{constructor(t){super(`ConfigurationError - ${t}`)}}class ie extends le{constructor(t){super(`Option not Configured: ${t.stepTitle}`),this.optionId=t?.optionId||"N/A"}}class J extends le{constructor(t){super(`Panel not Found: ${t.panelId}`),this.panelId=t?.panelId||"N/A"}}class yt extends le{constructor(t){super(`Asset not found for variant: ${t.name}`),this.variant=t}}class Ot extends le{constructor(t){super(`Resource not found for asset: ${t.name}`),this.asset=t}}class lt extends le{constructor(t,e){super(`Workflow Misconfiguration: ${t.stepName} - ${e}`),this.step=t}}class Le extends Jn{constructor(t){super(`ImplementationError - ${t}`)}}class R extends Le{constructor(t){super(`Unhandled Behavior Encountered: ${t}`)}}class Bt extends Le{constructor(t){super(`Parsing Error: ${t}`)}}class ft extends Le{constructor(t){super(`Client Error: ${t}`)}}class ze extends Le{constructor(t){super(`Resource Generation Failed: ${t}`)}}class zr{get(t){return localStorage.getItem(t)||void 0}set(t,e){localStorage.setItem(t,e)}remove(t){localStorage.removeItem(t)}getMap(t){const e=this.get(t);if(e)return new Map(JSON.parse(e))}setMap(t,e){const a=JSON.stringify([...e.entries()]);this.set(t,a)}}class An{constructor(){this.storage=new Map}get(t){return this.storage.get(t)||void 0}set(t,e){this.storage.set(t,e)}remove(t){this.storage.delete(t)}getMap(t){const e=this.get(t);if(e)return new Map(JSON.parse(e))}setMap(t,e){const a=JSON.stringify([...e.entries()]);this.set(t,a)}}const qr=()=>{try{return localStorage?new zr:new An}catch{return console.warn("Local storage was unavilable due to browser security settings. Using in-memory storage instead."),new An}},Q=qr();class Gr{constructor(){this.defaultServerUrl="https://api.au.spiffcommerce.com",this.defaultServicesApiUrl="https://services.au.spiffcommerce.com",this.defaultHubUrl="https://hub.au.spiffcommerce.com",this.serverUrl=this.defaultServerUrl,this.servicesApiUrl=this.defaultServicesApiUrl,this.hubUrl=this.defaultHubUrl,this.serverUrlCallbacks=[]}getServerUrl(){return this.serverUrl}getServicesApiUrl(){return this.servicesApiUrl}getHubUrl(){return this.hubUrl}setServerUrl(t){this.serverUrl=t,this.serverUrlCallbacks.forEach(e=>e())}setServicesApiUrl(t){this.servicesApiUrl=t}setHubUrl(t){this.hubUrl=t}addServerUrlCallback(t){this.serverUrlCallbacks.push(t)}}const mt=new Gr;let wa,ya;function jr(i){wa=i}function Hr(i){ya=i}function ce(){return wa?new wa().window:(console.log("DOM constructor is not registered. Assuming browser environment. If not, please register DOM constructor before calling this function."),window)}function it(i,t){if(!ya){if(typeof window<"u"&&window.fetch)return window.fetch(i,t);if(typeof global<"u"&&global.fetch)return global.fetch(i,t);throw new Error("Fetch implementation is not registered. Please register it before calling this function.")}return ya(i,t)}const Kn=new Map,hn=new Map,gn=new Map,_n=async i=>{const t=hn.get(i);if(t)return t;const a=(async()=>{const n=await it(i);return Kn.set(i,n.headers?.get("content-type")||""),await n.arrayBuffer()})();return hn.set(i,a),a},Wr=async i=>{const t=gn.get(i);if(t)return t;const a=(async()=>await(await it(i)).text())();return gn.set(i,a),a},Ut=i=>i.every(t=>t!=="undefined"),ye=i=>Ut([typeof document])?document.createElement(i):ce().document.createElement(i),Yr=(i,t)=>{if(Ut([typeof document]))return document.createElementNS(i,t);const a=ce().document.createElement(t);return a.setAttribute("xmlns",i),a},ct=()=>{if(Ut([typeof DOMParser]))return new DOMParser;const i=ce();return new i.DOMParser},Jr=()=>Ut([typeof DOMParser])?DOMParser:ce().DOMParser,qe=(i,t)=>new Promise((e,a)=>{t?_n(i).then(e).catch(a):it(i).then(n=>{n.arrayBuffer().then(e).catch(a)}).catch(n=>{a(n)})}),et=(i,t)=>new Promise((e,a)=>{t?Wr(i).then(e).catch(a):it(i).then(n=>{n.text().then(e).catch(a)}).catch(a)}),Xn=i=>Dr.renderToStaticMarkup(i),ea=new Map,Kr=async(i,t)=>{if(Ut([typeof FontFace])){if(ea.has(t))return ea.get(t);const e=i.names.fullName.en,a=new FontFace(e,`url(${t})`);document.fonts.add(a);const n=a.load();return ea.set(t,n),n}},bt=()=>{if(Ut([typeof XMLSerializer]))return new XMLSerializer;const i=ce();return new i.XMLSerializer},mn=i=>btoa(i),Ge=i=>{function t(){const a=new Uint8Array(i),n=4;if(a.length>=n){const r=new Array(n);for(let l=0;l<n;l++)r[l]=new Uint8Array(i)[l].toString(16);const o=r.join("").toUpperCase();switch(o){case"89504E47":return"image/png";case"47494638":return"image/gif";case"25504446":return"application/pdf";case"504B0304":return"application/zip"}switch(o.slice(0,4)){case"FFD8":return"image/jpeg"}}return null}const e=t();return e||"image/svg+xml"},_r=async i=>{const t=await _n(i),e=Kn.get(i)||Ge(t);return await to(new Blob([t],{type:e}))},Xr=i=>{let t="";const e=i.byteLength;for(let a=0;a<e;a++)t+=String.fromCharCode(i[a]);return t},Zr=async i=>{const t=Ge(i),e=new Uint8Array(i),a=Xr(e),n=btoa(a);return`data:${t};base64,${n}`},je=i=>`data:image/svg+xml;base64,${btoa(i)}`,Zn=i=>{const t=i.replace(/\r?\n/g,""),e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");const a=t.substring(5,e).split(";");let n=!1;for(let o=1;o<a.length;o++)a[o]==="base64"&&(n=!0);const r=decodeURI(t.substring(e+1));return n?new Uint8Array(atob(r).split("").map(s=>s.charCodeAt(0))).buffer:new Uint8Array(r.split("").map(s=>s.charCodeAt(0))).buffer},to=i=>new Promise((t,e)=>{const a=new FileReader;a.onload=function(n){const r=n.target;!r||!r.result?e():t(r.result.toString())},a.readAsDataURL(i)});let eo,$a;const ao=i=>{$a=i},no=()=>$a;let ti;const ei=i=>{ti=i},io=()=>new Promise(i=>{const t=mt.getHubUrl(),e=a=>{a.origin===t&&(window.removeEventListener("message",e),i(a.data))};window.parent!==window&&(window.addEventListener("message",e,!1),window.parent.postMessage("ready",t))}),ro=async()=>{const i={applicationKey:$a,customerToken:eo,bearer:ti};return typeof window<"u"&&(window.location.href.includes("/workflows/product/")||window.location.href.includes("hub=true"))?{...await io(),...i}:i};async function oo(i,t){const e=mt.getServerUrl(),a=e.includes(".aumelbdev.spiffcommerce.com")?"https://moonlight.aumelbdev.spiffcommerce.com":e.includes(".us.spiffcommerce.com")?"https://moonlight.us.spiffcommerce.com":"https://moonlight.au.spiffcommerce.com";let n=await it(i,{...t,redirect:"manual"});return(n.type==="opaqueredirect"||n.status===307)&&(typeof i!="string"&&"url"in i?n=await it({...i,url:`${a}/graphql`},t):n=await it(`${a}/graphql`,t)),n}class so{constructor(){this.shadowGraphqlClient=this.constructShadowGraphqlClient(),mt.addServerUrlCallback(()=>{this.shadowGraphqlClient=this.constructShadowGraphqlClient()})}setSpiffCommerceClient(t){this.spiffClient=t,this.shadowGraphqlClient=this.constructShadowGraphqlClient()}getShadowGraphqlClient(){return this.shadowGraphqlClient}constructShadowGraphqlClient(){const t=C.createHttpLink({uri:`${mt.getServerUrl()}/graphql`,fetch:oo}),e=xr.setContext(async(r,o)=>{const{headers:s}=o,l=s||{},c=await ro();let d=o.bearer??c.bearer,u=!1;if(this.spiffClient){try{d=await this.spiffClient.loggedInBearerToken()}catch{}try{o.skipIntegrationCheck||(u=await this.spiffClient.getBetaEnabled())}catch{}}const A=o.partnerId??c.partnerId,h=o.activeIntegration??c.activeIntegration,g=o.transactionOwnerId,p=o.customerToken??c.customerToken,m=o.applicationKey??c.applicationKey,f=o.bundleOwnerId;try{if(window&&window.__SENTRY__){const S=window.__SENTRY__.hub;if(S){const w=S.traceHeaders();Object.entries(w).forEach(([F,b])=>{l[F]=b})}}}catch{}return d&&(l.Authorization=`Bearer ${d}`),A&&(l.partnerId=A),h&&(l.activeIntegration=h),g&&(l.transactionOwnerId=g),p&&(l.customerToken=p),m&&(l["X-Application-Key"]=m),f&&(l.bundleOwnerId=f),u&&(l["X-Spiff-Beta"]="true"),l["Allow-Moonlight-Redirect"]="true",{headers:l}}),a=Fr.onError(({operation:r,graphQLErrors:o,networkError:s})=>{const l=o||[],c=r.getContext();s&&!c?.fetchOptions?.signal?.aborted&&console.log("GraphQL Network error"),l.forEach(()=>console.log("GraphQL Error: "+r.operationName))}),n=kr.removeTypenameFromVariables();return new C.ApolloClient({link:C.from([n,a,e,t]),cache:new C.InMemoryCache,name:"Core"})}}const y=new so;let Sa,va;const St=(i,t,e)=>{if(Sa!==void 0)return Sa(i,t,e);try{const a=ai(!0);return Va(a),a.createCanvas(i,t,e)}catch{throw new Error("Canvas module not set")}},de=(i,t)=>{if(va!==void 0)return va(i,t);try{const e=ai(!0);return Va(e),e.loadImage(i,t)}catch{throw new Error("Canvas module not set")}};function Va(i){Sa=i?.createCanvas,va=i?.loadImage}function ai(i){try{if(document.createElement("canvas").getContext("2d"))return{createCanvas:(e,a,n)=>{const r=document.createElement("canvas");return e!=null&&(r.width=e),a!=null&&(r.height=a),r},loadImage:(e,a)=>new Promise((n,r)=>{const o=document.createElement("img");a!==!1&&(o.crossOrigin="Anonymous"),o.onload=()=>{n(o)},o.onerror=r,o.src=e})}}catch(t){throw t}}let aa;function Ua(){return aa===void 0&&(aa=Jr()),aa}let Se=null;const lo=i=>new Promise(t=>{if(Ge(i)!=="image/jpeg")return t(1);Mr.orientation(i).then(a=>t(a||1)).catch(()=>t(1))}),co=async()=>{if(Se!==null)return!Se;const t=await de("data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAAAAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/xABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAAAAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQvoP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXwH/9k=");return Se=t.width===2&&t.height===3,!Se},uo=i=>{const e=i.naturalWidth/i.naturalHeight;return i.naturalHeight<=8192&&i.naturalWidth<=8192?[i.naturalWidth,i.naturalHeight]:i.naturalHeight>i.naturalWidth?[e*8192,8192]:[8192,8192/e]},Ao=async i=>{const t=await Zr(i),e=await de(t),[a,n]=uo(e);if(!await co()){const u=St(a,n);return u.getContext("2d")?.drawImage(e,0,0,a,n),u}const o=await lo(i),[s,l]=o>4?[n,a]:[a,n],c=St(s,l),d=c.getContext("2d");switch(o){case 2:d.translate(s,0),d.scale(-1,1);break;case 3:d.translate(s,l),d.rotate(Math.PI);break;case 4:d.translate(0,l),d.scale(1,-1);break;case 5:d.rotate(-.5*Math.PI),d.scale(-1,1);break;case 6:d.rotate(-.5*Math.PI),d.translate(-s,0);break;case 7:d.rotate(-.5*Math.PI),d.translate(-s,l),d.scale(1,-1);break;case 8:d.rotate(.5*Math.PI),d.translate(0,-l);break}return d.drawImage(e,0,0,s,l),c},ue=async i=>{const t=await Ao(i);return Ge(i)==="image/jpeg"?{dataUrl:t.toDataURL("image/jpeg",1),height:t.height,width:t.width}:{dataUrl:t.toDataURL(),height:t.height,width:t.width}},re=["Yellow C","Yellow 012 C","Orange 021 C","Warm Red C","Red 032 C","Rubine Red C","Rhodamine Red C","Purple C","Violet C","Blue 072 C","Reflex Blue C","Process Blue C","Green C","Black C","Yellow 0131 C","Red 0331 C","Magenta 0521 C","Violet 0631 C","Blue 0821 C","Green 0921 C","Black 0961 C","801 C","802 C","803 C","804 C","805 C","806 C","807 C","871 C","872 C","873 C","874 C","875 C","876 C","877 C","Medium Yellow C","Bright Orange C","Bright Red C","Strong Red C","Pink C","Medium Purple C","Dark Blue C","Medium Blue C","Bright Green C","Neutral Black C","100 C","101 C","102 C","103 C","104 C","105 C","7401 C","7402 C","7403 C","7404 C","7405 C","7406 C","7407 C","106 C","107 C","108 C","109 C","110 C","111 C","112 C","113 C","114 C","115 C","116 C","117 C","118 C","119 C","127 C","128 C","129 C","130 C","131 C","132 C","133 C","1205 C","1215 C","1225 C","1235 C","1245 C","1255 C","1265 C","120 C","121 C","122 C","123 C","124 C","125 C","126 C","7548 C","7549 C","7550 C","7551 C","7552 C","7553 C","7554 C","7555 C","7556 C","7557 C","7558 C","7559 C","7560 C","7561 C","134 C","135 C","136 C","137 C","138 C","139 C","140 C","1345 C","1355 C","1365 C","1375 C","1385 C","1395 C","1405 C","141 C","142 C","143 C","144 C","145 C","146 C","147 C","7408 C","7409 C","7410 C","7411 C","7412 C","7413 C","7414 C","7562 C","7563 C","7564 C","7565 C","7566 C","7567 C","7568 C","7569 C","7570 C","7571 C","7572 C","7573 C","7574 C","7575 C","712 C","713 C","714 C","715 C","716 C","717 C","718 C","148 C","149 C","150 C","151 C","152 C","153 C","154 C","155 C","156 C","157 C","158 C","159 C","160 C","161 C","1485 C","1495 C","1505 C","1525 C","1535 C","1545 C","1555 C","1565 C","1575 C","1585 C","1595 C","1605 C","1615 C","162 C","163 C","164 C","165 C","166 C","167 C","168 C","7576 C","7577 C","7578 C","7579 C","7580 C","7581 C","7582 C","1625 C","1635 C","1645 C","1655 C","1665 C","1675 C","1685 C","169 C","170 C","171 C","172 C","173 C","174 C","175 C","7583 C","7584 C","7585 C","7586 C","7587 C","7588 C","7589 C","7590 C","7591 C","7592 C","7593 C","7594 C","7595 C","7596 C","7597 C","7598 C","7599 C","7600 C","7601 C","7602 C","7603 C","7604 C","7605 C","7606 C","7607 C","7608 C","7609 C","7610 C","7611 C","7612 C","7613 C","7614 C","7615 C","7616 C","7617 C","7520 C","7521 C","7522 C","7523 C","7524 C","7525 C","7526 C","489 C","488 C","487 C","486 C","485 C","484 C","483 C","176 C","177 C","178 C","179 C","180 C","181 C","1765 C","1775 C","1785 C","1788 C","1795 C","1805 C","1815 C","1767 C","1777 C","1787 C","1797 C","1807 C","1817 C","7618 C","7619 C","7620 C","7621 C","7622 C","7623 C","7624 C","7625 C","7626 C","7627 C","7628 C","7629 C","7630 C","7631 C","7415 C","7416 C","7417 C","7418 C","7419 C","7420 C","7421 C","182 C","183 C","184 C","185 C","186 C","187 C","188 C","196 C","197 C","198 C","199 C","200 C","201 C","202 C","189 C","190 C","191 C","192 C","193 C","194 C","195 C","1895 C","1905 C","1915 C","1925 C","1935 C","1945 C","1955 C","705 C","706 C","707 C","708 C","709 C","710 C","711 C","698 C","699 C","700 C","701 C","702 C","703 C","704 C","203 C","204 C","205 C","206 C","207 C","208 C","209 C","210 C","211 C","212 C","213 C","214 C","215 C","216 C","7422 C","7423 C","7424 C","7425 C","7426 C","7427 C","7428 C","7632 C","7633 C","7634 C","7635 C","7636 C","7637 C","7638 C","217 C","218 C","219 C","220 C","221 C","222 C","7639 C","7640 C","7641 C","7642 C","7643 C","7644 C","7645 C","223 C","224 C","225 C","226 C","227 C","228 C","229 C","230 C","231 C","232 C","233 C","234 C","235 C","670 C","671 C","672 C","673 C","674 C","675 C","676 C","677 C","678 C","679 C","680 C","681 C","682 C","683 C","684 C","685 C","686 C","687 C","688 C","689 C","690 C","510 C","509 C","508 C","507 C","506 C","505 C","504 C","7429 C","7430 C","7431 C","7432 C","7433 C","7434 C","7435 C","691 C","692 C","693 C","694 C","695 C","696 C","697 C","496 C","495 C","494 C","493 C","492 C","491 C","490 C","503 C","502 C","501 C","500 C","499 C","498 C","497 C","5035 C","5025 C","5015 C","5005 C","4995 C","4985 C","4975 C","236 C","237 C","238 C","239 C","240 C","241 C","242 C","2365 C","2375 C","2385 C","2395 C","2405 C","2415 C","2425 C","243 C","244 C","245 C","246 C","247 C","248 C","249 C","7646 C","7647 C","7648 C","7649 C","7650 C","7651 C","7652 C","250 C","251 C","252 C","253 C","254 C","255 C","517 C","516 C","515 C","514 C","513 C","512 C","511 C","7436 C","7437 C","7438 C","7439 C","7440 C","7441 C","7442 C","2562 C","2572 C","2582 C","2592 C","2602 C","2612 C","2622 C","7653 C","7654 C","7655 C","7656 C","7657 C","7658 C","7659 C","524 C","523 C","522 C","521 C","520 C","519 C","518 C","5245 C","5235 C","5225 C","5215 C","5205 C","5195 C","5185 C","5175 C","5165 C","5155 C","5145 C","5135 C","5125 C","5115 C","531 C","530 C","529 C","528 C","527 C","526 C","525 C","256 C","257 C","258 C","259 C","260 C","261 C","262 C","2563 C","2573 C","2583 C","2593 C","2603 C","2613 C","2623 C","7660 C","7661 C","7662 C","7663 C","7664 C","7665 C","7666 C","2567 C","2577 C","2587 C","2597 C","2607 C","2617 C","2627 C","263 C","264 C","265 C","266 C","267 C","268 C","269 C","2635 C","2645 C","2655 C","2665 C","2685 C","2695 C","270 C","271 C","272 C","273 C","274 C","275 C","276 C","2705 C","2715 C","2725 C","2735 C","2745 C","2755 C","2765 C","7667 C","7668 C","7669 C","7670 C","7671 C","7672 C","7673 C","7443 C","7444 C","7445 C","7446 C","7447 C","7448 C","7449 C","7674 C","7675 C","7676 C","7677 C","7678 C","7679 C","7680 C","663 C","664 C","665 C","666 C","667 C","668 C","669 C","5315 C","5305 C","5295 C","5285 C","5275 C","5265 C","5255 C","538 C","537 C","536 C","535 C","534 C","533 C","532 C","7541 C","7542 C","7543 C","7544 C","7545 C","7546 C","7547 C","552 C","551 C","550 C","549 C","548 C","547 C","546 C","5455 C","5445 C","5435 C","5425 C","5415 C","5405 C","5395 C","642 C","643 C","644 C","645 C","646 C","647 C","648 C","649 C","650 C","651 C","652 C","653 C","654 C","655 C","656 C","657 C","658 C","659 C","660 C","661 C","662 C","7450 C","7451 C","7452 C","7453 C","7454 C","7455 C","7456 C","2706 C","2716 C","2726 C","2736 C","2746 C","2756 C","2766 C","2708 C","2718 C","2728 C","2738 C","2748 C","2758 C","2768 C","2707 C","2717 C","2727 C","2747 C","2757 C","2767 C","277 C","278 C","279 C","280 C","281 C","282 C","283 C","284 C","285 C","286 C","287 C","288 C","289 C","7681 C","7682 C","7683 C","7684 C","7685 C","7686 C","7687 C","545 C","544 C","543 C","542 C","541 C","540 C","539 C","290 C","291 C","292 C","293 C","294 C","295 C","296 C","2905 C","2915 C","2925 C","2935 C","2945 C","2955 C","2965 C","297 C","298 C","299 C","300 C","301 C","302 C","303 C","7688 C","7689 C","7690 C","7691 C","7692 C","7693 C","7694 C","2975 C","2985 C","2995 C","3005 C","3015 C","3025 C","3035 C","7695 C","7696 C","7697 C","7698 C","7699 C","7700 C","7701 C","7457 C","7458 C","7459 C","7460 C","7461 C","7462 C","7463 C","304 C","305 C","306 C","307 C","308 C","309 C","635 C","636 C","637 C","638 C","639 C","640 C","641 C","7702 C","7703 C","7704 C","7705 C","7706 C","7707 C","7708 C","628 C","629 C","630 C","631 C","632 C","633 C","634 C","310 C","311 C","312 C","313 C","314 C","315 C","316 C","3105 C","3115 C","3125 C","3135 C","3145 C","3155 C","3165 C","7709 C","7710 C","7711 C","7712 C","7713 C","7714 C","7715 C","317 C","318 C","319 C","320 C","321 C","322 C","323 C","7464 C","7465 C","7466 C","7467 C","7468 C","7469 C","7470 C","7471 C","7472 C","7473 C","7474 C","7475 C","7476 C","7477 C","5523 C","5513 C","5503 C","5493 C","5483 C","5473 C","5463 C","7716 C","7717 C","7718 C","7719 C","7720 C","7721 C","7722 C","324 C","325 C","326 C","327 C","328 C","329 C","330 C","3242 C","3252 C","3262 C","3272 C","3282 C","3292 C","3302 C","3245 C","3255 C","3265 C","3275 C","3285 C","3295 C","3305 C","3248 C","3258 C","3268 C","3278 C","3288 C","3298 C","3308 C","566 C","565 C","564 C","563 C","562 C","561 C","560 C","573 C","572 C","571 C","570 C","569 C","568 C","567 C","559 C","558 C","557 C","556 C","555 C","554 C","553 C","5595 C","5585 C","5575 C","5565 C","5555 C","5545 C","5535 C","5665 C","5655 C","5645 C","5635 C","5625 C","5615 C","5605 C","5527 C","5517 C","5507 C","5497 C","5487 C","5477 C","5467 C","621 C","622 C","623 C","624 C","625 C","626 C","627 C","331 C","332 C","333 C","334 C","335 C","336 C","337 C","338 C","339 C","340 C","341 C","342 C","343 C","7723 C","7724 C","7725 C","7726 C","7727 C","7728 C","7729 C","3375 C","3385 C","3395 C","3405 C","3415 C","3425 C","3435 C","344 C","345 C","346 C","347 C","348 C","349 C","350 C","351 C","352 C","353 C","354 C","355 C","356 C","357 C","7478 C","7479 C","7480 C","7481 C","7482 C","7483 C","7484 C","7730 C","7731 C","7732 C","7733 C","7734 C","7735 C","7736 C","7737 C","7738 C","7739 C","7740 C","7741 C","7742 C","7743 C","358 C","359 C","360 C","361 C","362 C","363 C","364 C","7485 C","7486 C","7487 C","7488 C","7489 C","7490 C","7491 C","365 C","366 C","367 C","368 C","369 C","370 C","371 C","372 C","373 C","374 C","375 C","376 C","377 C","378 C","580 C","579 C","578 C","577 C","576 C","575 C","574 C","5807 C","5797 C","5787 C","5777 C","5767 C","5757 C","5747 C","5875 C","5865 C","5855 C","5845 C","5835 C","5825 C","5815 C","5803 C","5793 C","5783 C","5773 C","5763 C","5753 C","5743 C","7492 C","7493 C","7494 C","7495 C","7496 C","7497 C","7498 C","7744 C","7745 C","7746 C","7747 C","7748 C","7749 C","7750 C","379 C","380 C","381 C","382 C","383 C","384 C","385 C","386 C","387 C","388 C","389 C","390 C","391 C","392 C","587 C","586 C","585 C","584 C","583 C","582 C","581 C","393 C","394 C","395 C","396 C","397 C","398 C","399 C","3935 C","3945 C","3955 C","3965 C","3975 C","3985 C","3995 C","600 C","601 C","602 C","603 C","604 C","605 C","606 C","607 C","608 C","609 C","610 C","611 C","612 C","613 C","461 C","460 C","459 C","458 C","457 C","456 C","455 C","614 C","615 C","616 C","617 C","618 C","619 C","620 C","7751 C","7752 C","7753 C","7754 C","7755 C","7756 C","7757 C","7758 C","7759 C","7760 C","7761 C","7762 C","7763 C","7764 C","7765 C","7766 C","7767 C","7768 C","7769 C","7770 C","7771 C","4545 C","4535 C","4525 C","4515 C","4505 C","4495 C","4485 C","454 C","453 C","452 C","451 C","450 C","449 C","448 C","7499 C","7500 C","7501 C","7502 C","7503 C","7504 C","7505 C","468 C","467 C","466 C","465 C","464 C","463 C","462 C","7506 C","7507 C","7508 C","7509 C","7510 C","7511 C","7512 C","719 C","720 C","721 C","722 C","723 C","724 C","725 C","475 C","474 C","473 C","472 C","471 C","470 C","469 C","726 C","727 C","728 C","729 C","730 C","731 C","732 C","4685 C","4675 C","4665 C","4655 C","4645 C","4635 C","4625 C","7513 C","7514 C","7515 C","7516 C","7517 C","7518 C","7519 C","4755 C","4745 C","4735 C","4725 C","4715 C","4705 C","4695 C","482 C","481 C","480 C","479 C","478 C","477 C","476 C","7527 C","7528 C","7529 C","7530 C","7531 C","7532 C","7533 C","7534 C","7535 C","7536 C","7537 C","7538 C","7539 C","7540 C","427 C","428 C","429 C","430 C","431 C","432 C","433 C","420 C","421 C","422 C","423 C","424 C","425 C","426 C","441 C","442 C","443 C","444 C","445 C","446 C","447 C","413 C","414 C","415 C","416 C","417 C","418 C","419 C","400 C","401 C","402 C","403 C","404 C","405 C","406 C","407 C","408 C","409 C","410 C","411 C","412 C","434 C","435 C","436 C","437 C","438 C","439 C","440 C","Warm Gray 1 C","Warm Gray 2 C","Warm Gray 3 C","Warm Gray 4 C","Warm Gray 5 C","Warm Gray 6 C","Warm Gray 7 C","Warm Gray 8 C","Warm Gray 9 C","Warm Gray 10 C","Warm Gray 11 C","Cool Gray 1 C","Cool Gray 2 C","Cool Gray 3 C","Cool Gray 4 C","Cool Gray 5 C","Cool Gray 6 C","Cool Gray 7 C","Cool Gray 8 C","Cool Gray 9 C","Cool Gray 10 C","Cool Gray 11 C","Black 2 C","Black 3 C","Black 4 C","Black 5 C","Black 6 C","Black 7 C"],$t=["FEDD00","FFD700","FE5000","F9423A","EF3340","CE0058","E10098","BB29BB","440099","10069F","001489","0085CA","00AB84","2D2926","F2F0A1","FCAEBB","F1B2DC","BF9BDE","74D1EA","9DE7D7","9E978E","009ACE","44D62C","FFE900","FFAA4D","FF7276","FF3EB5","EA27C2","84754E","85714D","866D4B","8B6F4E","87674F","8B634B","8A8D8F","FFD900","FF5E00","F93822","CE0056","D62598","4E008E","00239C","0084CA","00B08B","222223","F6EB61","F7EA48","FCE300","C5A900","AF9800","897A27","F5E1A4","ECD898","EED484","F4DA40","F2CD00","F1C400","CBA052","F9E547","FBE122","FEDB00","FFD100","DAAA00","AA8A00","9C8412","FAE053","FBDD40","FDDA24","FFCD00","C99700","AC8400","897322","F3DD6D","F3D54E","F3D03E","F2A900","CC8A00","A07400","6C571B","F8E08E","FBD872","FFC845","FFB81C","C69214","AD841F","886B25","FBDB65","FDD757","FED141","FFC72C","EAAA00","B58500","9A7611","FFC600","FFB500","D19000","B47E00","73531D","5A4522","4B3D2A","D29F13","B78B20","9F7D23","967126","8F6A2A","7D622E","6C5D34","FDD26E","FFC658","FFBF3F","FFA300","DE7C00","AF6D04","74531C","FDD086","FFC56E","FFB549","FF9E1B","D57800","996017","6E4C1E","F2C75C","F1BE48","F1B434","ED8B00","CF7F00","A76D11","715C2A","F6BE00","F0B323","FEAD77","E6A65D","D38235","DC8633","C16C18","BD9B60","D69A2D","DB8A06","CD7925","AD6433","89532F","775135","D78825","D3832B","C67D30","B67233","A7662B","9E6A38","835D32","FCC89B","FDBE87","FDAA63","F68D2E","EA7600","D45D00","BE4D00","FECB8B","FFC27B","FFB25B","FF8200","E57200","BE6A14","9B5A1A","EFD19F","EFBE7D","ECA154","E87722","CB6015","A1561C","603D20","FFAE62","FF8F1C","FF6900","B94700","94450B","653819","FFB990","FFA06A","FF7F32","FF6A13","D86018","A65523","8B4720","FFBE9F","FF9D6E","FF7F41","FF671F","E35205","BE531C","73381D","DB864E","E07E3C","DC6B2F","DC582A","C05131","864A33","674736","FFA38B","FF8D6D","FF6A39","FC4C02","DC4405","A9431E","833921","FFB3AB","FF8674","FF5C39","FA4616","CF4520","963821","6B3529","C4622D","BA5826","AF5C37","9E5330","924C2E","7B4D35","5C4738","D4B59E","C07D59","B15533","9D432C","7C3A2D","6B3D2E","5C3D31","D14124","BD472A","B33D26","8D3F2B","83412C","7B4931","674230","E4D5D3","E1BBB4","D6938A","C26E60","A4493D","823B34","683431","DDBCB0","CA9A8E","BC8A7E","A37F74","866761","6B4C4C","583D3E","EABEB0","C09C83","B46A55","AB5C57","A45248","9A6A4F","8A391B","ECC3B2","ECBAA8","EAA794","E8927C","DA291C","9A3324","653024","FFB1BB","FF808B","FF585D","E03C31","BE3A34","81312F","FFA3B5","FF8DA1","F8485E","EE2737","D22630","AF272F","7C2529","FCAFC0","FB637E","F4364C","CB333B","A4343A","643335","C66E4E","C04C36","B7312C","AB2328","93272C","8A2A2B","802F2D","E1523D","C63527","A72B2A","9E2A2B","6D3332","633231","572D2D","E6BAA8","E56A54","E04E39","CD545B","B04A5A","9B2242","651D32","FABBCB","FC9BB3","F65275","E4002B","C8102E","A6192E","76232F","ECC7CD","E89CAE","DF4661","D50032","BA0C2F","9D2235","862633","F8A3BC","F67599","EF426F","E40046","BF0D3E","9B2743","782F40","F5B6CD","F59BBB","EF4A81","E0004D","C5003E","A6093D","8A1538","F5DADF","F7CED7","F9B5C4","F890A5","EF6079","E03E52","CB2C30","F2D4D7","F4C3CC","F2ACB9","E68699","D25B73","B83A4B","9E2A2F","ECB3CB","E782A9","E0457B","CE0037","A50034","861F41","6F263D","F99FC9","F57EB6","F04E98","E31C79","CE0F69","AC145A","7D2248","F4CDD4","E06287","E24585","B52555","A4123F","971B2F","6A2C3E","D6C9CA","C4A4A7","C16784","C63663","BC204B","912F46","7E2D40","EABEDB","E56DB1","DA1884","A50050","910048","6C1D45","936D73","934054","8E2C48","732E4A","672E45","582D40","502B3A","EF95CF","EB6FBD","DF1995","D0006F","AA0061","890C58","672146","F4A6D7","F277C6","E93CAC","C6007E","A20067","840B55","EAD3E2","E6BCD8","DFA0C9","D986BA","C6579A","AE2573","960051","E5CEDB","E3C8D8","DEBED2","C996B6","B06C96","994878","7C2855","E4C6D4","DCB6C9","D0A1BA","BE84A3","A76389","893B67","612141","EBBECB","E8B3C3","E4A9BB","D592AA","84344E","6F2C3F","572932","E2BCCB","DCA9BF","C9809E","B55C80","A73A64","9B3259","872651","E9CDD0","E4BEC3","D7A3AB","C48490","B46B7A","984856","893C47","F2C6CF","F1BDC8","E9A2B2","DC8699","8F3237","7F3035","5D2A2C","E9C4C7","E5BAC1","DAA5AD","C6858F","7A3E3A","6A3735","512F2E","DFC2C3","DBB7BB","CCA1A6","B07C83","9C6169","874B52","3F2021","F1A7DC","EC86D0","E45DBF","DB3EB1","C5299B","AF1685","80225F","EFBAE1","E277CD","D539B5","C800A1","B0008E","9E007E","830065","EAB8E4","E59BDC","DD7FD3","C724B1","BB16A3","A51890","80276C","A56E87","A83D72","991E66","8A1B61","722257","6A2A5B","5E2751","E7BAE4","DD9CDF","C964CF","AD1AAC","981D97","72246C","EBC6DF","E6BEDD","E2ACD7","D48BC8","93328E","833177","612C51","EEDAEA","CCAED0","D59ED7","B288B9","A277A6","9F5CC0","963CBD","D7A9E3","C98BDB","AC4FC6","9B26B6","87189D","772583","653165","948794","A2789C","A15A95","8E3A80","6E2B62","6A3460","5D3754","D5C2D8","C9B1D0","BA9CC5","A57FB2","642F6C","59315F","4B3048","DBCDD3","D0BEC7","C6B0BC","AF95A6","86647A","66435A","4A3041","D8C8D1","D3C0CD","BFA5B8","9B7793","7E5475","693C5E","512A44","DFC8E7","D7B9E4","CAA2DD","B580D1","8031A7","702F8A","572C5F","D6BFDD","C6A1CF","8C4799","6D2077","642667","5D285F","51284F","CBA3D8","B884CB","A05EB5","84329B","702082","671E75","5F2167","9991A4","8D6E97","7A4183","6B3077","653279","5E366E","5C4E63","C1A0DA","A77BCA","8246AF","5C068C","500778","470A68","3C1053","D7C6E6","C1A7E2","9063CD","753BBD","5F259F","582C83","512D6D","C5B4E3","AD96DC","9678D3","7D55C7","330072","2E1A47","B4B5DF","9595D2","7474C1","24135F","211551","201747","221C35","A7A4E0","8B84D7","685BC7","2E008B","280071","250E62","201547","6E7CA0","686E9F","615E9B","565294","514689","4C4184","535486","DDDAE8","B6B8DC","A7A2C3","8986CA","5D4777","4B384C","41273B","878CB4","7C7FAB","7566A0","6F5091","68478D","563D82","523178","E5E1E6","E0DBE3","C6BCD0","A192B2","7C6992","614B79","3F2A56","D8D7DF","C6C4D2","B3B0C4","8D89A5","595478","403A60","1E1A34","C5CFDA","BBC7D6","A2B2C8","8E9FBC","1B365D","1F2A44","1C1F2A","D9E1E2","A4BCC2","98A4AE","768692","425563","253746","131E29","B9D3DC","A3C7D2","8DB9CA","6BA4B8","003D4C","00313C","072B31","BFCED6","B7C9D3","A6BBC8","7A99AC","5B7F95","4F758B","081F2C","D1DDE6","C6D6E3","9BB8D3","7DA1C4","5E8AB4","236192","002E5D","DBE2E9","CED9E5","A7BCD6","7D9BC1","326295","003A70","002554","DDE5ED","C8D8EB","B1C9E8","7BA4DB","407EC9","003594","001A70","BDC5DB","89ABE3","8094DD","7BA6DE","5F8FB4","3A5DAE","606EB2","CBD3EB","9FAEE5","485CC7","1E22AA","171C8F","151F6D","141B4D","B8CCEA","5C88DA","0047BB","06038D","001871","001E62","071D49","C3D7EE","A7C6ED","307FE2","001A72","001E60","13294B","ABCAE9","8BB8E8","418FDE","012169","00205B","041E42","92C1E9","6CACE4","0072CE","0033A0","003087","002D72","0C2340","94A9CB","6787B7","426DA9","385E9D","2C5697","1D4F91","1D428A","C6DAE7","BDD6E6","A4C8E1","7BAFD4","003C71","003057","00263A","B9D9EB","9BCBEB","69B3E7","003DA5","002F6C","002855","041C2C","8DC8E8","62B5E5","009CDE","0057B8","004C97","003865","00263E","71C5E8","41B6E6","00A3E0","005EB8","004B87","003B5C","002A3A","4698CB","298FC2","0076A8","006298","005587","004976","01426A","99D6EA","5BC2E7","00A9E0","0077C8","00629B","004F71","003E51","7BA7BC","6399AE","4E87A0","41748D","34657F","165C7D","005776","BBDDE6","71B2C9","4298B5","0086BF","007DBA","00558C","002B49","9ADBE8","59CBE8","00B5E2","006BA6","00587C","003B49","A4DBE8","8BD3E6","4EC3E0","00AFD7","0095C8","0082BA","0067A0","48A9C5","009CBD","0085AD","007096","006A8E","00617F","005670","B8DDE1","9BD3DD","77C5D5","3EB1C8","0093B2","007396","005F83","6AD1E3","05C3DE","00A9CE","0092BC","007FA3","00677F","004851","68D2DF","00C1D5","00AEC7","008EAA","00778B","006272","004F59","63B1BC","00A7B5","0097A9","00859B","007D8A","007680","006269","B1E4E3","88DBDF","2DCCD3","009CA6","008C95","007377","005F61","A0D1CA","40C1AC","00B0B9","00A3AD","007398","005F86","005A70","7EDDD3","5CB8B2","279989","007681","487A7B","0D5257","244C5A","B6CFD0","ABC7CA","94B7BB","7FA9AE","4F868E","115E67","07272D","00968F","00857D","007672","006D68","00635B","005E5D","005151","9CDBD9","64CCC9","00B2A9","008675","007367","00685E","00534C","71DBD4","2AD2C9","00BFB3","00A499","008578","00594F","004C45","7CE0D3","2CD5C4","00C7B1","00B398","009681","007864","004E42","6DCDB8","49C5B1","00AB8E","009B77","008264","006A52","034638","B9DCD2","A1D6CA","86C8BC","6BBBAE","006F62","00594C","1D3C34","B5E3D8","A5DFD3","98DBCE","6BCABA","00816D","006C5B","173F35","ADCAB8","9ABEAA","85B09A","6FA287","28724F","205C40","284734","BFCEC2","A7BDB1","92ACA0","7F9C90","5C7F71","43695B","183028","BAC5B9","B0BDB0","A3B2A4","94A596","708573","5E7461","22372B","BCC9C5","B1C0BC","9DB0AC","829995","5D7975","3E5D58","18332F","D1E0D7","B7CDC2","9AB9AD","789F90","507F70","285C4D","13322B","A7E6D7","8CE2D0","3CDBC0","009775","007B5F","00664F","8FD6BD","6ECEB2","00B388","00965E","007A53","006747","115740","50A684","00966C","008755","007B4B","006F44","006845","005844","7AE1BF","47D7AC","00C389","00AF66","007749","006341","154734","A0DAB3","91D6AC","71CC98","009A44","00843D","046A38","2C5234","A2E4B8","8FE2B0","80E0A7","00B140","009639","007A33","215732","9BE3BF","26D07C","00BF6F","00B74F","009F4D","275D38","00573F","4B9560","228848","007A3E","007041","286140","36573B","395542","6BA539","48A23F","319B42","3A913F","44883E","4A773C","44693D","ADDC91","A1D884","6CC24A","43B02A","509E2F","4C8C2B","4A7729","D0DEBB","BCE194","8EDD65","78D64B","74AA50","719949","79863C","C2E189","B7DD79","A4D65E","78BE20","64A70B","658D1B","546223","D4EB8E","CDEA80","C5E86C","97D700","84BD00","7A9A01","59621D","C4D6A4","BCD19B","B7CE95","A9C47F","789D4A","67823A","4E5B31","D0D1AB","C6C89B","BABD8B","A2A569","8A8D4A","6D712E","3D441E","D2CE9E","CBC793","C0BB87","AFA96E","A09958","89813D","555025","C3C6A8","B3B995","A3AA83","899064","737B4C","5E6738","3E4827","BFCC80","BBC592","9CAF88","8F993E","76881D","7A7256","5B6236","BABC16","ABAD23","999B30","888D30","7C8034","727337","656635","E2E868","DBE442","CEDC00","C4D600","A8AD00","949300","787121","E9EC6B","E3E935","E0E721","D0DF00","B5BD00","9A9500","827A04","E3E48D","E0E27C","DBDE70","D2D755","B7BF10","8E8C13","625D20","F0EC74","EDE939","ECE81A","E1E000","BFB800","ADA400","A09200","F3EA5D","F3E500","EFDF00","EEDC00","BBA600","9A8700","685C20","F1EB9C","F0E991","F0E87B","EDE04B","EADA24","E1CD00","CFB500","EBE49A","E9E186","E6DE77","E1D555","D7C826","C4B000","B39B00","E9DF97","E4D77E","DECD63","D9C756","B89D18","A28E2A","695B24","DCD59A","D6CF8D","D0C883","C0B561","AC9F3C","9F912A","8A7B19","CAB64B","CFB023","C1A01E","A08629","897630","736635","675E33","D4C304","C4B200","91852C","747136","5D6439","585C3B","535435","BBB323","B4A91F","AA9D2E","8F7E35","716135","635939","4E4934","D5CB9F","CFC493","C5B783","B3A369","998542","8C7732","614F25","CAC7A7","BFBB98","B0AA7E","9B945F","594A25","524727","4A412A","F1E6B2","DFD1A7","D9C89E","CEB888","A89968","94795D","816040","DDCBA4","D3BC8D","C6AA76","B9975B","8B5B29","744F28","5C462B","EFDBB2","FCD299","E1B87F","D6A461","C6893F","B77729","A6631B","EDC8A3","E7B78A","DDA46F","C88242","B36924","934D11","7D3F16","F3CFB3","F1C6A7","F0BF9B","E59E6D","B86125","A45A2A","693F23","E0C09F","D9B48F","CDA077","B58150","9E652E","774212","623412","E0C6AD","DCBFA6","CDA788","BF9474","AD7C59","946037","4F2C1D","E1B7A7","D5A286","C58B68","99552B","85431E","6D4F47","5E4B3C","D7C4B7","CDB5A7","C0A392","AE8A79","956C58","7C4D3A","5B3427","DBC8B6","D3BBA8","C6A992","AA8066","703F2A","623B2A","4E3629","D6D2C4","C5B9AC","B7A99A","A39382","7A6855","63513D","473729","D1CCBD","B7B09C","A69F88","A7ACA2","949A90","8E9089","4B4F54","D0D3D4","C1C6C8","A2AAAD","7C878E","5B6770","333F48","1D252D","C7C9C7","B2B4B2","9EA2A2","898D8D","707372","54585A","25282A","BEC6C4","A2ACAB","919D9D","717C7D","505759","3F4444","373A36","BABBB1","A8A99E","919388","7E7F74","65665C","51534A","212322","C4BFB6","AFA9A0","9D968D","8C857B","776E64","696158","C4BCB7","B2A8A2","978C87","857874","746661","5E514D","382F2D","D0C4C5","C1B2B6","AB989D","7B6469","584446","453536","382E2C","D7D2CB","CBC4BC","BFB8AF","B6ADA5","ACA39A","A59C94","968C83","8C8279","83786F","796E65","6E6259","D9D9D6","D0D0CE","C8C9C7","BBBCBC","B1B3B3","A7A8AA","97999B","888B8D","75787B","63666A","53565A","332F21","212721","31261D","3E2B2E","101820","3D3935"],na=$t.map(i=>[parseInt(i.substring(0,2),16),parseInt(i.substring(2,4),16),parseInt(i.substring(4,6),16)]);function ho(i){const t=re.indexOf(i);return t>=0?$t[t]:""}function ni(i){const t=$t.indexOf(i);return t>=0?re[t]:""}function go(i,t=64){const e=[],a=[],n=ni(i);n&&e.push({pms:n,hex:i,distance:0});const r=parseInt(i.substring(0,2),16),o=parseInt(i.substring(2,4),16),s=parseInt(i.substring(4,6),16);let l,c,d;for(let u=0;u<$t.length;u++){l=na[u][0],c=na[u][1],d=na[u][2];const A=Math.sqrt(Math.pow(r-l,2)+Math.pow(o-c,2)+Math.pow(s-d,2));a.push(A)}for(let u=0;u<a.length;u++)a[u]<=t&&!e.some(A=>A.pms===re[u])&&e.push({pms:re[u],hex:$t[u],distance:a[u]});return e.sort((u,A)=>u.distance-A.distance)}const mo=re.map((i,t)=>({pms:i,hex:$t[t]})),po=new Tr(mo,{keys:["pms"]});function fo(i,t){return po.search(i,t?{limit:t}:void 0)}let Lt=null;function ii(i){if(i.startsWith("#"))return pn(i);if(!document)throw new Error("browserColorToHex is only supported on browsers");if(Lt||(Lt=document.createElement("canvas").getContext("2d")),!Lt)throw new Error("Failed to create canvas context required to convert colors");Lt.fillStyle=i;const t=pn(Lt.fillStyle);return t||console.error(`Unknown browser color ${i}`),t}function pn(i){const t=i.substring(1).toUpperCase();return t.length===6?t:t.length===3?`${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`:""}const ve=i=>{const t=ri(i.spotColor);return t?`${i.browserValue} ${t}`:i.browserValue},ri=i=>{if(!i)return"";if(i.profileName.includes("/")&&i.profileName.includes(".icc")){const t=i.profileName.replace(/\s/g,"-"),e=t.lastIndexOf("/");return`icc-named-color(${t.slice(e+1).slice(0,-4)}, ${i.namedColor})`}return`icc-named-color(${i.profileName}, ${i.namedColor})`},Ea=i=>{const t=i.split(/[ ](?=[^)]*?(?:\(|$))/);if(t.length===0)return{browserValue:"#000000"};if(t.length===1)return{browserValue:t[0]};const e=t[1].match(/\(([^)]+)\)/gm);if(!e)throw new Error("Unhandled state of color value in SVG");const a=e[0].replace(/[() ]/g,"").split(",");return{browserValue:t[0],spotColor:{profileName:a[0],namedColor:a[1]}}},Co=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],wo=["fill","stroke"],Vt=(i,t)=>{t(i),i.children.length>0&&Array.from(i.children).forEach(e=>Vt(e,t))},oi=(i,t)=>{const e=t(i);if(e)return e;const a=i.parentElement;if(a)return oi(a,t)},yo=(i,t)=>{try{return i.matches(t)}catch{return i.classList.contains(t.substring(1))}},He=(i,t=!1)=>{!t&&i.setAttribute("preserveAspectRatio","none");const e=[];Vt(i,a=>{if(a.tagName==="script"){a.remove();return}if(a.tagName==="style"){try{Vn.parse(a.innerHTML).stylesheet?.rules.forEach(o=>{e.push(o)}),a.remove()}catch(r){console.error(r)}return}const n=a.attributes.getNamedItem("style")?.value?.trim();if(n){const r=[];n.split(";").forEach(s=>{const l=s.trim();if(l){const[c,d]=l.split(":"),u=c.toLowerCase();wo.indexOf(u)>-1?a.setAttribute(u,d.trim()):r.push(l)}}),r.length>0?a.setAttribute("style",r.join(";")):a.removeAttribute("style")}}),Vt(i,a=>{e.forEach(n=>{n.selectors?.forEach(r=>{yo(a,r)&&n.declarations?.forEach(o=>{o.property&&o.value&&a.setAttribute(o.property,o.value)})})})})},So=i=>{const t=/pt|pc|mm|cm|in/gm,e=i.getAttribute("viewBox"),a=i.getAttribute("width"),n=i.getAttribute("height");if(!e)throw new Error("viewBox not specified on SVG!");a&&i.setAttribute("width",a.replace(t,"")),n&&i.setAttribute("height",n.replace(t,""))},si=i=>ct().parseFromString(i,"image/svg+xml").firstElementChild,vo=(i,t,e)=>{i.setAttribute("height",`${e}px`),i.setAttribute("width",`${t}px`)},li=(i,t,e)=>{Vt(i,a=>{const n=a.attributes.getNamedItem("fill");n&&n.value!=="none"&&a.classList.forEach(o=>{if(o.startsWith("spiff-fill")){const s=t[o.replace("spiff-fill-","")];if(s)a.setAttribute("fill",e?ve(s):s.browserValue);else{const l=t[o];l&&a.setAttribute("fill",e?ve(l):l.browserValue)}}});const r=a.attributes.getNamedItem("stroke");r&&r.value!=="none"&&a.classList.forEach(o=>{if(o.startsWith("spiff-stroke")){const s=t[o.replace("spiff-stroke-","")];if(s)a.setAttribute("stroke",e?ve(s):s.browserValue);else{const l=t[o];l&&a.setAttribute("fill",e?ve(l):l.browserValue)}}})})},ci=i=>bt().serializeToString(i),La=(i,t,e,a,n)=>{const r=si(i);if(!r)throw new Error("Failed to read SVG.");return vo(r,t,e),li(r,a,n),ci(r)},We=(i,t,e)=>{const a=si(i);if(!a)throw new Error("Failed to read SVG.");return li(a,t,e),ci(a)},Eo=i=>{const t=/<svg.*<\/svg>/s,e=i.match(t)||[],a=e?.length>0?e[0]:"";return ct().parseFromString(a,"image/svg+xml")},rt=async i=>{const e=Eo(i).firstElementChild;if(!e)throw new Error("Failed to read SVG.");He(e);const a={};Vt(e,o=>{if(Co.includes(o.tagName)&&!o.attributes.getNamedItem("fill")){let c="black";const d=o.parentElement;if(d){const u=oi(d,A=>{const g=A.style.fill;if(g)return g;const p=A.getAttribute("fill");if(p)return p});u&&(c=u)}o.setAttribute("fill",c)}const s=o.attributes.getNamedItem("fill");if(s&&s.value!=="none"&&!s.value.startsWith("url(")){const c=Ea(s.value),d=c.browserValue.replace(/\W/g,""),u=`spiff-fill-${d}`;o.setAttribute("fill",c.browserValue),o.classList.add(u),a[d]=c}const l=o.attributes.getNamedItem("stroke");if(l&&l.value!=="none"&&!l.value.startsWith("url(")){const c=Ea(l.value),d=c.browserValue.replace(/\W/g,""),u=`spiff-stroke-${d}`;o.classList.add(u),o.setAttribute("stroke",c.browserValue),a[d]=c}});const r=bt().serializeToString(e);return{colors:a,svg:r}},bo=C.gql`
1
+ "use strict";var Sr=Object.create;var dn=Object.defineProperty;var vr=Object.getOwnPropertyDescriptor;var Er=Object.getOwnPropertyNames;var br=Object.getPrototypeOf,Ir=Object.prototype.hasOwnProperty;var Br=(i,t,e,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Er(t))!Ir.call(i,n)&&n!==e&&dn(i,n,{get:()=>t[n],enumerable:!(a=vr(t,n))||a.enumerable});return i};var Pr=(i,t,e)=>(e=i!=null?Sr(br(i)):{},Br(t||!i||!i.__esModule?dn(e,"default",{value:i,enumerable:!0}):e,i));Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("@apollo/client/core"),xr=require("@apollo/client/link/context"),Fr=require("@apollo/client/link/error"),Dr=require("preact-render-to-string"),kr=require("@apollo/client/link/remove-typename"),Mr=require("exifr/dist/mini.umd.cjs"),Vn=require("css"),Tr=require("fuse.js"),Qa=require("pith"),pa=require("lodash.chunk"),Pt=require("lodash.clonedeep"),B=require("preact/jsx-runtime"),fa=require("opentype.js"),Nr=require("html-entities"),Qr=require("handlebars"),Rr=require("data-uri-to-buffer"),we=require("@aws-sdk/client-cognito-identity-provider"),Or=require("dinero.js"),$r=require("currency-codes"),Un=require("lodash.debounce"),ae=require("lodash.isequal"),Ca=require("unicode-default-word-boundary"),Ln=require("qrcode"),Vr=require("svg-path-bbox");require("fs");require("path");const Ur=require("lodash.omit");function Lr(i){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(i){for(const e in i)if(e!=="default"){const a=Object.getOwnPropertyDescriptor(i,e);Object.defineProperty(t,e,a.get?a:{enumerable:!0,get:()=>i[e]})}}return t.default=i,Object.freeze(t)}const un=Lr($r);var ne=(i=>(i.Data="Data",i.Font="Font",i.Frame="Frame",i.Illustration="Illustration",i.Image="Image",i.Model="Model",i.Material="Material",i.Color="Color",i.QuestionnaireCollateral="QuestionnaireCollateral",i.RequestCollateral="RequestCollateral",i.SignupCollateral="SignupCollateral",i.Video="Video",i.ColorProfile="ColorProfile",i.Environment="Environment",i))(ne||{}),zn=(i=>(i.AND="AND",i.OR="OR",i))(zn||{}),z=(i=>(i.FileUpload="FileUpload",i.Option="Option",i.ColorOption="ColorOption",i.Text="Text",i))(z||{}),E=(i=>(i.Information="Information",i.Bulk="Bulk",i.DigitalContent="DigitalContent",i.Finish="Finish",i.Frame="Frame",i.Illustration="Illustration",i.Introduction="Introduction",i.Material="Material",i.Model="Model",i.Module="Module",i.Picture="Picture",i.Photo="Photo",i.ProductOverlay="ProductOverlay",i.Question="Question",i.Shape="Shape",i.SilentIllustration="SilentIllustration",i.Text="Text",i))(E||{}),qn=(i=>(i.Color="Color",i.Colors="Colors",i.Selection="Selection",i.Selections="Selections",i.Text="Text",i.Upload="Upload",i))(qn||{}),Rt=(i=>(i.ThreeD="ThreeD",i.FreeDesign="FreeDesign",i.Print="Print",i))(Rt||{}),D=(i=>(i.Frame="frame",i.Group="group",i.Image="image",i.Pattern="pattern",i.Illustration="illustration",i.Textbox="textbox",i))(D||{}),Gn=(i=>(i.Default="Default",i.FirstTransaction="FirstTransaction",i.OneToOne="OneToOne",i))(Gn||{}),Ra=(i=>(i.Pending="Pending",i.Failed="Failed",i.Validated="Validated",i.Overridden="Overridden",i))(Ra||{}),jn=(i=>(i.Hyperlink="Hyperlink",i.Edit="Edit",i.Approve="Approve",i))(jn||{}),Hn=(i=>(i.Hub="Hub",i.Shopify="Shopify",i))(Hn||{}),Ue=(i=>(i.BackgroundRemover="BackgroundRemover",i.ConversionAccelerator="Conversion Accelerator",i.ProcessBuilder="ProcessBuilder",i))(Ue||{}),Wn=(i=>(i[i.Orbit=0]="Orbit",i[i.Pan=1]="Pan",i))(Wn||{}),Oa=(i=>(i.Owner="Owner",i.Approver="Approver",i.Editor="Editor",i.Viewer="Viewer",i))(Oa||{}),xt=(i=>(i.Autosize="Autosize",i.Traditional="Traditional",i))(xt||{}),Y=(i=>(i[i.North=0]="North",i[i.Northeast=1]="Northeast",i[i.East=2]="East",i[i.Southeast=3]="Southeast",i[i.South=4]="South",i[i.Southwest=5]="Southwest",i[i.West=6]="West",i[i.Northwest=7]="Northwest",i))(Y||{}),Yn=(i=>(i.Pixel="px",i.Millimeter="mm",i.Centimeter="cm",i))(Yn||{});class Jn extends Error{constructor(t){super(t),this.name=this.constructor.name}}class le extends Jn{constructor(t){super(`ConfigurationError - ${t}`)}}class ie extends le{constructor(t){super(`Option not Configured: ${t.stepTitle}`),this.optionId=t?.optionId||"N/A"}}class J extends le{constructor(t){super(`Panel not Found: ${t.panelId}`),this.panelId=t?.panelId||"N/A"}}class yt extends le{constructor(t){super(`Asset not found for variant: ${t.name}`),this.variant=t}}class Ot extends le{constructor(t){super(`Resource not found for asset: ${t.name}`),this.asset=t}}class lt extends le{constructor(t,e){super(`Workflow Misconfiguration: ${t.stepName} - ${e}`),this.step=t}}class Le extends Jn{constructor(t){super(`ImplementationError - ${t}`)}}class R extends Le{constructor(t){super(`Unhandled Behavior Encountered: ${t}`)}}class Bt extends Le{constructor(t){super(`Parsing Error: ${t}`)}}class ft extends Le{constructor(t){super(`Client Error: ${t}`)}}class ze extends Le{constructor(t){super(`Resource Generation Failed: ${t}`)}}class zr{get(t){return localStorage.getItem(t)||void 0}set(t,e){localStorage.setItem(t,e)}remove(t){localStorage.removeItem(t)}getMap(t){const e=this.get(t);if(e)return new Map(JSON.parse(e))}setMap(t,e){const a=JSON.stringify([...e.entries()]);this.set(t,a)}}class An{constructor(){this.storage=new Map}get(t){return this.storage.get(t)||void 0}set(t,e){this.storage.set(t,e)}remove(t){this.storage.delete(t)}getMap(t){const e=this.get(t);if(e)return new Map(JSON.parse(e))}setMap(t,e){const a=JSON.stringify([...e.entries()]);this.set(t,a)}}const qr=()=>{try{return localStorage?new zr:new An}catch{return console.warn("Local storage was unavilable due to browser security settings. Using in-memory storage instead."),new An}},Q=qr();class Gr{constructor(){this.defaultServerUrl="https://api.au.spiffcommerce.com",this.defaultServicesApiUrl="https://services.au.spiffcommerce.com",this.defaultHubUrl="https://hub.au.spiffcommerce.com",this.serverUrl=this.defaultServerUrl,this.servicesApiUrl=this.defaultServicesApiUrl,this.hubUrl=this.defaultHubUrl,this.serverUrlCallbacks=[]}getServerUrl(){return this.serverUrl}getServicesApiUrl(){return this.servicesApiUrl}getHubUrl(){return this.hubUrl}setServerUrl(t){this.serverUrl=t,this.serverUrlCallbacks.forEach(e=>e())}setServicesApiUrl(t){this.servicesApiUrl=t}setHubUrl(t){this.hubUrl=t}addServerUrlCallback(t){this.serverUrlCallbacks.push(t)}}const gt=new Gr;let wa,ya;function jr(i){wa=i}function Hr(i){ya=i}function ce(){return wa?new wa().window:(console.log("DOM constructor is not registered. Assuming browser environment. If not, please register DOM constructor before calling this function."),window)}function it(i,t){if(!ya){if(typeof window<"u"&&window.fetch)return window.fetch(i,t);if(typeof global<"u"&&global.fetch)return global.fetch(i,t);throw new Error("Fetch implementation is not registered. Please register it before calling this function.")}return ya(i,t)}const Kn=new Map,hn=new Map,gn=new Map,_n=async i=>{const t=hn.get(i);if(t)return t;const a=(async()=>{const n=await it(i);return Kn.set(i,n.headers?.get("content-type")||""),await n.arrayBuffer()})();return hn.set(i,a),a},Wr=async i=>{const t=gn.get(i);if(t)return t;const a=(async()=>await(await it(i)).text())();return gn.set(i,a),a},Ut=i=>i.every(t=>t!=="undefined"),ye=i=>Ut([typeof document])?document.createElement(i):ce().document.createElement(i),Yr=(i,t)=>{if(Ut([typeof document]))return document.createElementNS(i,t);const a=ce().document.createElement(t);return a.setAttribute("xmlns",i),a},ct=()=>{if(Ut([typeof DOMParser]))return new DOMParser;const i=ce();return new i.DOMParser},Jr=()=>Ut([typeof DOMParser])?DOMParser:ce().DOMParser,qe=(i,t)=>new Promise((e,a)=>{t?_n(i).then(e).catch(a):it(i).then(n=>{n.arrayBuffer().then(e).catch(a)}).catch(n=>{a(n)})}),et=(i,t)=>new Promise((e,a)=>{t?Wr(i).then(e).catch(a):it(i).then(n=>{n.text().then(e).catch(a)}).catch(a)}),Xn=i=>Dr.renderToStaticMarkup(i),ea=new Map,Kr=async(i,t)=>{if(Ut([typeof FontFace])){if(ea.has(t))return ea.get(t);const e=i.names.fullName.en,a=new FontFace(e,`url(${t})`);document.fonts.add(a);const n=a.load();return ea.set(t,n),n}},bt=()=>{if(Ut([typeof XMLSerializer]))return new XMLSerializer;const i=ce();return new i.XMLSerializer},mn=i=>btoa(i),Ge=i=>{function t(){const a=new Uint8Array(i),n=4;if(a.length>=n){const r=new Array(n);for(let l=0;l<n;l++)r[l]=new Uint8Array(i)[l].toString(16);const o=r.join("").toUpperCase();switch(o){case"89504E47":return"image/png";case"47494638":return"image/gif";case"25504446":return"application/pdf";case"504B0304":return"application/zip"}switch(o.slice(0,4)){case"FFD8":return"image/jpeg"}}return null}const e=t();return e||"image/svg+xml"},_r=async i=>{const t=await _n(i),e=Kn.get(i)||Ge(t);return await to(new Blob([t],{type:e}))},Xr=i=>{let t="";const e=i.byteLength;for(let a=0;a<e;a++)t+=String.fromCharCode(i[a]);return t},Zr=async i=>{const t=Ge(i),e=new Uint8Array(i),a=Xr(e),n=btoa(a);return`data:${t};base64,${n}`},je=i=>`data:image/svg+xml;base64,${btoa(i)}`,Zn=i=>{const t=i.replace(/\r?\n/g,""),e=t.indexOf(",");if(e===-1||e<=4)throw new TypeError("malformed data: URI");const a=t.substring(5,e).split(";");let n=!1;for(let o=1;o<a.length;o++)a[o]==="base64"&&(n=!0);const r=decodeURI(t.substring(e+1));return n?new Uint8Array(atob(r).split("").map(s=>s.charCodeAt(0))).buffer:new Uint8Array(r.split("").map(s=>s.charCodeAt(0))).buffer},to=i=>new Promise((t,e)=>{const a=new FileReader;a.onload=function(n){const r=n.target;!r||!r.result?e():t(r.result.toString())},a.readAsDataURL(i)});let eo,$a;const ao=i=>{$a=i},no=()=>$a;let ti;const ei=i=>{ti=i},io=()=>new Promise(i=>{const t=gt.getHubUrl(),e=a=>{a.origin===t&&(window.removeEventListener("message",e),i(a.data))};window.parent!==window&&(window.addEventListener("message",e,!1),window.parent.postMessage("ready",t))}),ro=async()=>{const i={applicationKey:$a,customerToken:eo,bearer:ti};return typeof window<"u"&&(window.location.href.includes("/workflows/product/")||window.location.href.includes("hub=true"))?{...await io(),...i}:i};async function oo(i,t){const e=gt.getServerUrl(),a=e.includes(".aumelbdev.spiffcommerce.com")?"https://moonlight.aumelbdev.spiffcommerce.com":e.includes(".us.spiffcommerce.com")?"https://moonlight.us.spiffcommerce.com":"https://moonlight.au.spiffcommerce.com";let n=await it(i,{...t,redirect:"manual"});return(n.type==="opaqueredirect"||n.status===307)&&(typeof i!="string"&&"url"in i?n=await it({...i,url:`${a}/graphql`},t):n=await it(`${a}/graphql`,t)),n}class so{constructor(){this.shadowGraphqlClient=this.constructShadowGraphqlClient(),gt.addServerUrlCallback(()=>{this.shadowGraphqlClient=this.constructShadowGraphqlClient()})}setSpiffCommerceClient(t){this.spiffClient=t,this.shadowGraphqlClient=this.constructShadowGraphqlClient()}getShadowGraphqlClient(){return this.shadowGraphqlClient}constructShadowGraphqlClient(){const t=C.createHttpLink({uri:`${gt.getServerUrl()}/graphql`,fetch:oo}),e=xr.setContext(async(r,o)=>{const{headers:s}=o,l=s||{},c=await ro();let d=o.bearer??c.bearer,u=!1;if(this.spiffClient){try{d=await this.spiffClient.loggedInBearerToken()}catch{}try{o.skipIntegrationCheck||(u=await this.spiffClient.getBetaEnabled())}catch{}}const A=o.partnerId??c.partnerId,h=o.activeIntegration??c.activeIntegration,g=o.transactionOwnerId,p=o.customerToken??c.customerToken,m=o.applicationKey??c.applicationKey,f=o.bundleOwnerId;try{if(window&&window.__SENTRY__){const S=window.__SENTRY__.hub;if(S){const w=S.traceHeaders();Object.entries(w).forEach(([F,b])=>{l[F]=b})}}}catch{}return d&&(l.Authorization=`Bearer ${d}`),A&&(l.partnerId=A),h&&(l.activeIntegration=h),g&&(l.transactionOwnerId=g),p&&(l.customerToken=p),m&&(l["X-Application-Key"]=m),f&&(l.bundleOwnerId=f),u&&(l["X-Spiff-Beta"]="true"),l["Allow-Moonlight-Redirect"]="true",{headers:l}}),a=Fr.onError(({operation:r,graphQLErrors:o,networkError:s})=>{const l=o||[],c=r.getContext();s&&!c?.fetchOptions?.signal?.aborted&&console.log("GraphQL Network error"),l.forEach(()=>console.log("GraphQL Error: "+r.operationName))}),n=kr.removeTypenameFromVariables();return new C.ApolloClient({link:C.from([n,a,e,t]),cache:new C.InMemoryCache,name:"Core"})}}const y=new so;let Sa,va;const St=(i,t,e)=>{if(Sa!==void 0)return Sa(i,t,e);try{const a=ai(!0);return Va(a),a.createCanvas(i,t,e)}catch{throw new Error("Canvas module not set")}},de=(i,t)=>{if(va!==void 0)return va(i,t);try{const e=ai(!0);return Va(e),e.loadImage(i,t)}catch{throw new Error("Canvas module not set")}};function Va(i){Sa=i?.createCanvas,va=i?.loadImage}function ai(i){try{if(document.createElement("canvas").getContext("2d"))return{createCanvas:(e,a,n)=>{const r=document.createElement("canvas");return e!=null&&(r.width=e),a!=null&&(r.height=a),r},loadImage:(e,a)=>new Promise((n,r)=>{const o=document.createElement("img");a!==!1&&(o.crossOrigin="Anonymous"),o.onload=()=>{n(o)},o.onerror=r,o.src=e})}}catch(t){throw t}}let aa;function Ua(){return aa===void 0&&(aa=Jr()),aa}let Se=null;const lo=i=>new Promise(t=>{if(Ge(i)!=="image/jpeg")return t(1);Mr.orientation(i).then(a=>t(a||1)).catch(()=>t(1))}),co=async()=>{if(Se!==null)return!Se;const t=await de("data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAAAAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/xABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAAAAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQvoP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXwH/9k=");return Se=t.width===2&&t.height===3,!Se},uo=i=>{const e=i.naturalWidth/i.naturalHeight;return i.naturalHeight<=8192&&i.naturalWidth<=8192?[i.naturalWidth,i.naturalHeight]:i.naturalHeight>i.naturalWidth?[e*8192,8192]:[8192,8192/e]},Ao=async i=>{const t=await Zr(i),e=await de(t),[a,n]=uo(e);if(!await co()){const u=St(a,n);return u.getContext("2d")?.drawImage(e,0,0,a,n),u}const o=await lo(i),[s,l]=o>4?[n,a]:[a,n],c=St(s,l),d=c.getContext("2d");switch(o){case 2:d.translate(s,0),d.scale(-1,1);break;case 3:d.translate(s,l),d.rotate(Math.PI);break;case 4:d.translate(0,l),d.scale(1,-1);break;case 5:d.rotate(-.5*Math.PI),d.scale(-1,1);break;case 6:d.rotate(-.5*Math.PI),d.translate(-s,0);break;case 7:d.rotate(-.5*Math.PI),d.translate(-s,l),d.scale(1,-1);break;case 8:d.rotate(.5*Math.PI),d.translate(0,-l);break}return d.drawImage(e,0,0,s,l),c},ue=async i=>{const t=await Ao(i);return Ge(i)==="image/jpeg"?{dataUrl:t.toDataURL("image/jpeg",1),height:t.height,width:t.width}:{dataUrl:t.toDataURL(),height:t.height,width:t.width}},re=["Yellow C","Yellow 012 C","Orange 021 C","Warm Red C","Red 032 C","Rubine Red C","Rhodamine Red C","Purple C","Violet C","Blue 072 C","Reflex Blue C","Process Blue C","Green C","Black C","Yellow 0131 C","Red 0331 C","Magenta 0521 C","Violet 0631 C","Blue 0821 C","Green 0921 C","Black 0961 C","801 C","802 C","803 C","804 C","805 C","806 C","807 C","871 C","872 C","873 C","874 C","875 C","876 C","877 C","Medium Yellow C","Bright Orange C","Bright Red C","Strong Red C","Pink C","Medium Purple C","Dark Blue C","Medium Blue C","Bright Green C","Neutral Black C","100 C","101 C","102 C","103 C","104 C","105 C","7401 C","7402 C","7403 C","7404 C","7405 C","7406 C","7407 C","106 C","107 C","108 C","109 C","110 C","111 C","112 C","113 C","114 C","115 C","116 C","117 C","118 C","119 C","127 C","128 C","129 C","130 C","131 C","132 C","133 C","1205 C","1215 C","1225 C","1235 C","1245 C","1255 C","1265 C","120 C","121 C","122 C","123 C","124 C","125 C","126 C","7548 C","7549 C","7550 C","7551 C","7552 C","7553 C","7554 C","7555 C","7556 C","7557 C","7558 C","7559 C","7560 C","7561 C","134 C","135 C","136 C","137 C","138 C","139 C","140 C","1345 C","1355 C","1365 C","1375 C","1385 C","1395 C","1405 C","141 C","142 C","143 C","144 C","145 C","146 C","147 C","7408 C","7409 C","7410 C","7411 C","7412 C","7413 C","7414 C","7562 C","7563 C","7564 C","7565 C","7566 C","7567 C","7568 C","7569 C","7570 C","7571 C","7572 C","7573 C","7574 C","7575 C","712 C","713 C","714 C","715 C","716 C","717 C","718 C","148 C","149 C","150 C","151 C","152 C","153 C","154 C","155 C","156 C","157 C","158 C","159 C","160 C","161 C","1485 C","1495 C","1505 C","1525 C","1535 C","1545 C","1555 C","1565 C","1575 C","1585 C","1595 C","1605 C","1615 C","162 C","163 C","164 C","165 C","166 C","167 C","168 C","7576 C","7577 C","7578 C","7579 C","7580 C","7581 C","7582 C","1625 C","1635 C","1645 C","1655 C","1665 C","1675 C","1685 C","169 C","170 C","171 C","172 C","173 C","174 C","175 C","7583 C","7584 C","7585 C","7586 C","7587 C","7588 C","7589 C","7590 C","7591 C","7592 C","7593 C","7594 C","7595 C","7596 C","7597 C","7598 C","7599 C","7600 C","7601 C","7602 C","7603 C","7604 C","7605 C","7606 C","7607 C","7608 C","7609 C","7610 C","7611 C","7612 C","7613 C","7614 C","7615 C","7616 C","7617 C","7520 C","7521 C","7522 C","7523 C","7524 C","7525 C","7526 C","489 C","488 C","487 C","486 C","485 C","484 C","483 C","176 C","177 C","178 C","179 C","180 C","181 C","1765 C","1775 C","1785 C","1788 C","1795 C","1805 C","1815 C","1767 C","1777 C","1787 C","1797 C","1807 C","1817 C","7618 C","7619 C","7620 C","7621 C","7622 C","7623 C","7624 C","7625 C","7626 C","7627 C","7628 C","7629 C","7630 C","7631 C","7415 C","7416 C","7417 C","7418 C","7419 C","7420 C","7421 C","182 C","183 C","184 C","185 C","186 C","187 C","188 C","196 C","197 C","198 C","199 C","200 C","201 C","202 C","189 C","190 C","191 C","192 C","193 C","194 C","195 C","1895 C","1905 C","1915 C","1925 C","1935 C","1945 C","1955 C","705 C","706 C","707 C","708 C","709 C","710 C","711 C","698 C","699 C","700 C","701 C","702 C","703 C","704 C","203 C","204 C","205 C","206 C","207 C","208 C","209 C","210 C","211 C","212 C","213 C","214 C","215 C","216 C","7422 C","7423 C","7424 C","7425 C","7426 C","7427 C","7428 C","7632 C","7633 C","7634 C","7635 C","7636 C","7637 C","7638 C","217 C","218 C","219 C","220 C","221 C","222 C","7639 C","7640 C","7641 C","7642 C","7643 C","7644 C","7645 C","223 C","224 C","225 C","226 C","227 C","228 C","229 C","230 C","231 C","232 C","233 C","234 C","235 C","670 C","671 C","672 C","673 C","674 C","675 C","676 C","677 C","678 C","679 C","680 C","681 C","682 C","683 C","684 C","685 C","686 C","687 C","688 C","689 C","690 C","510 C","509 C","508 C","507 C","506 C","505 C","504 C","7429 C","7430 C","7431 C","7432 C","7433 C","7434 C","7435 C","691 C","692 C","693 C","694 C","695 C","696 C","697 C","496 C","495 C","494 C","493 C","492 C","491 C","490 C","503 C","502 C","501 C","500 C","499 C","498 C","497 C","5035 C","5025 C","5015 C","5005 C","4995 C","4985 C","4975 C","236 C","237 C","238 C","239 C","240 C","241 C","242 C","2365 C","2375 C","2385 C","2395 C","2405 C","2415 C","2425 C","243 C","244 C","245 C","246 C","247 C","248 C","249 C","7646 C","7647 C","7648 C","7649 C","7650 C","7651 C","7652 C","250 C","251 C","252 C","253 C","254 C","255 C","517 C","516 C","515 C","514 C","513 C","512 C","511 C","7436 C","7437 C","7438 C","7439 C","7440 C","7441 C","7442 C","2562 C","2572 C","2582 C","2592 C","2602 C","2612 C","2622 C","7653 C","7654 C","7655 C","7656 C","7657 C","7658 C","7659 C","524 C","523 C","522 C","521 C","520 C","519 C","518 C","5245 C","5235 C","5225 C","5215 C","5205 C","5195 C","5185 C","5175 C","5165 C","5155 C","5145 C","5135 C","5125 C","5115 C","531 C","530 C","529 C","528 C","527 C","526 C","525 C","256 C","257 C","258 C","259 C","260 C","261 C","262 C","2563 C","2573 C","2583 C","2593 C","2603 C","2613 C","2623 C","7660 C","7661 C","7662 C","7663 C","7664 C","7665 C","7666 C","2567 C","2577 C","2587 C","2597 C","2607 C","2617 C","2627 C","263 C","264 C","265 C","266 C","267 C","268 C","269 C","2635 C","2645 C","2655 C","2665 C","2685 C","2695 C","270 C","271 C","272 C","273 C","274 C","275 C","276 C","2705 C","2715 C","2725 C","2735 C","2745 C","2755 C","2765 C","7667 C","7668 C","7669 C","7670 C","7671 C","7672 C","7673 C","7443 C","7444 C","7445 C","7446 C","7447 C","7448 C","7449 C","7674 C","7675 C","7676 C","7677 C","7678 C","7679 C","7680 C","663 C","664 C","665 C","666 C","667 C","668 C","669 C","5315 C","5305 C","5295 C","5285 C","5275 C","5265 C","5255 C","538 C","537 C","536 C","535 C","534 C","533 C","532 C","7541 C","7542 C","7543 C","7544 C","7545 C","7546 C","7547 C","552 C","551 C","550 C","549 C","548 C","547 C","546 C","5455 C","5445 C","5435 C","5425 C","5415 C","5405 C","5395 C","642 C","643 C","644 C","645 C","646 C","647 C","648 C","649 C","650 C","651 C","652 C","653 C","654 C","655 C","656 C","657 C","658 C","659 C","660 C","661 C","662 C","7450 C","7451 C","7452 C","7453 C","7454 C","7455 C","7456 C","2706 C","2716 C","2726 C","2736 C","2746 C","2756 C","2766 C","2708 C","2718 C","2728 C","2738 C","2748 C","2758 C","2768 C","2707 C","2717 C","2727 C","2747 C","2757 C","2767 C","277 C","278 C","279 C","280 C","281 C","282 C","283 C","284 C","285 C","286 C","287 C","288 C","289 C","7681 C","7682 C","7683 C","7684 C","7685 C","7686 C","7687 C","545 C","544 C","543 C","542 C","541 C","540 C","539 C","290 C","291 C","292 C","293 C","294 C","295 C","296 C","2905 C","2915 C","2925 C","2935 C","2945 C","2955 C","2965 C","297 C","298 C","299 C","300 C","301 C","302 C","303 C","7688 C","7689 C","7690 C","7691 C","7692 C","7693 C","7694 C","2975 C","2985 C","2995 C","3005 C","3015 C","3025 C","3035 C","7695 C","7696 C","7697 C","7698 C","7699 C","7700 C","7701 C","7457 C","7458 C","7459 C","7460 C","7461 C","7462 C","7463 C","304 C","305 C","306 C","307 C","308 C","309 C","635 C","636 C","637 C","638 C","639 C","640 C","641 C","7702 C","7703 C","7704 C","7705 C","7706 C","7707 C","7708 C","628 C","629 C","630 C","631 C","632 C","633 C","634 C","310 C","311 C","312 C","313 C","314 C","315 C","316 C","3105 C","3115 C","3125 C","3135 C","3145 C","3155 C","3165 C","7709 C","7710 C","7711 C","7712 C","7713 C","7714 C","7715 C","317 C","318 C","319 C","320 C","321 C","322 C","323 C","7464 C","7465 C","7466 C","7467 C","7468 C","7469 C","7470 C","7471 C","7472 C","7473 C","7474 C","7475 C","7476 C","7477 C","5523 C","5513 C","5503 C","5493 C","5483 C","5473 C","5463 C","7716 C","7717 C","7718 C","7719 C","7720 C","7721 C","7722 C","324 C","325 C","326 C","327 C","328 C","329 C","330 C","3242 C","3252 C","3262 C","3272 C","3282 C","3292 C","3302 C","3245 C","3255 C","3265 C","3275 C","3285 C","3295 C","3305 C","3248 C","3258 C","3268 C","3278 C","3288 C","3298 C","3308 C","566 C","565 C","564 C","563 C","562 C","561 C","560 C","573 C","572 C","571 C","570 C","569 C","568 C","567 C","559 C","558 C","557 C","556 C","555 C","554 C","553 C","5595 C","5585 C","5575 C","5565 C","5555 C","5545 C","5535 C","5665 C","5655 C","5645 C","5635 C","5625 C","5615 C","5605 C","5527 C","5517 C","5507 C","5497 C","5487 C","5477 C","5467 C","621 C","622 C","623 C","624 C","625 C","626 C","627 C","331 C","332 C","333 C","334 C","335 C","336 C","337 C","338 C","339 C","340 C","341 C","342 C","343 C","7723 C","7724 C","7725 C","7726 C","7727 C","7728 C","7729 C","3375 C","3385 C","3395 C","3405 C","3415 C","3425 C","3435 C","344 C","345 C","346 C","347 C","348 C","349 C","350 C","351 C","352 C","353 C","354 C","355 C","356 C","357 C","7478 C","7479 C","7480 C","7481 C","7482 C","7483 C","7484 C","7730 C","7731 C","7732 C","7733 C","7734 C","7735 C","7736 C","7737 C","7738 C","7739 C","7740 C","7741 C","7742 C","7743 C","358 C","359 C","360 C","361 C","362 C","363 C","364 C","7485 C","7486 C","7487 C","7488 C","7489 C","7490 C","7491 C","365 C","366 C","367 C","368 C","369 C","370 C","371 C","372 C","373 C","374 C","375 C","376 C","377 C","378 C","580 C","579 C","578 C","577 C","576 C","575 C","574 C","5807 C","5797 C","5787 C","5777 C","5767 C","5757 C","5747 C","5875 C","5865 C","5855 C","5845 C","5835 C","5825 C","5815 C","5803 C","5793 C","5783 C","5773 C","5763 C","5753 C","5743 C","7492 C","7493 C","7494 C","7495 C","7496 C","7497 C","7498 C","7744 C","7745 C","7746 C","7747 C","7748 C","7749 C","7750 C","379 C","380 C","381 C","382 C","383 C","384 C","385 C","386 C","387 C","388 C","389 C","390 C","391 C","392 C","587 C","586 C","585 C","584 C","583 C","582 C","581 C","393 C","394 C","395 C","396 C","397 C","398 C","399 C","3935 C","3945 C","3955 C","3965 C","3975 C","3985 C","3995 C","600 C","601 C","602 C","603 C","604 C","605 C","606 C","607 C","608 C","609 C","610 C","611 C","612 C","613 C","461 C","460 C","459 C","458 C","457 C","456 C","455 C","614 C","615 C","616 C","617 C","618 C","619 C","620 C","7751 C","7752 C","7753 C","7754 C","7755 C","7756 C","7757 C","7758 C","7759 C","7760 C","7761 C","7762 C","7763 C","7764 C","7765 C","7766 C","7767 C","7768 C","7769 C","7770 C","7771 C","4545 C","4535 C","4525 C","4515 C","4505 C","4495 C","4485 C","454 C","453 C","452 C","451 C","450 C","449 C","448 C","7499 C","7500 C","7501 C","7502 C","7503 C","7504 C","7505 C","468 C","467 C","466 C","465 C","464 C","463 C","462 C","7506 C","7507 C","7508 C","7509 C","7510 C","7511 C","7512 C","719 C","720 C","721 C","722 C","723 C","724 C","725 C","475 C","474 C","473 C","472 C","471 C","470 C","469 C","726 C","727 C","728 C","729 C","730 C","731 C","732 C","4685 C","4675 C","4665 C","4655 C","4645 C","4635 C","4625 C","7513 C","7514 C","7515 C","7516 C","7517 C","7518 C","7519 C","4755 C","4745 C","4735 C","4725 C","4715 C","4705 C","4695 C","482 C","481 C","480 C","479 C","478 C","477 C","476 C","7527 C","7528 C","7529 C","7530 C","7531 C","7532 C","7533 C","7534 C","7535 C","7536 C","7537 C","7538 C","7539 C","7540 C","427 C","428 C","429 C","430 C","431 C","432 C","433 C","420 C","421 C","422 C","423 C","424 C","425 C","426 C","441 C","442 C","443 C","444 C","445 C","446 C","447 C","413 C","414 C","415 C","416 C","417 C","418 C","419 C","400 C","401 C","402 C","403 C","404 C","405 C","406 C","407 C","408 C","409 C","410 C","411 C","412 C","434 C","435 C","436 C","437 C","438 C","439 C","440 C","Warm Gray 1 C","Warm Gray 2 C","Warm Gray 3 C","Warm Gray 4 C","Warm Gray 5 C","Warm Gray 6 C","Warm Gray 7 C","Warm Gray 8 C","Warm Gray 9 C","Warm Gray 10 C","Warm Gray 11 C","Cool Gray 1 C","Cool Gray 2 C","Cool Gray 3 C","Cool Gray 4 C","Cool Gray 5 C","Cool Gray 6 C","Cool Gray 7 C","Cool Gray 8 C","Cool Gray 9 C","Cool Gray 10 C","Cool Gray 11 C","Black 2 C","Black 3 C","Black 4 C","Black 5 C","Black 6 C","Black 7 C"],$t=["FEDD00","FFD700","FE5000","F9423A","EF3340","CE0058","E10098","BB29BB","440099","10069F","001489","0085CA","00AB84","2D2926","F2F0A1","FCAEBB","F1B2DC","BF9BDE","74D1EA","9DE7D7","9E978E","009ACE","44D62C","FFE900","FFAA4D","FF7276","FF3EB5","EA27C2","84754E","85714D","866D4B","8B6F4E","87674F","8B634B","8A8D8F","FFD900","FF5E00","F93822","CE0056","D62598","4E008E","00239C","0084CA","00B08B","222223","F6EB61","F7EA48","FCE300","C5A900","AF9800","897A27","F5E1A4","ECD898","EED484","F4DA40","F2CD00","F1C400","CBA052","F9E547","FBE122","FEDB00","FFD100","DAAA00","AA8A00","9C8412","FAE053","FBDD40","FDDA24","FFCD00","C99700","AC8400","897322","F3DD6D","F3D54E","F3D03E","F2A900","CC8A00","A07400","6C571B","F8E08E","FBD872","FFC845","FFB81C","C69214","AD841F","886B25","FBDB65","FDD757","FED141","FFC72C","EAAA00","B58500","9A7611","FFC600","FFB500","D19000","B47E00","73531D","5A4522","4B3D2A","D29F13","B78B20","9F7D23","967126","8F6A2A","7D622E","6C5D34","FDD26E","FFC658","FFBF3F","FFA300","DE7C00","AF6D04","74531C","FDD086","FFC56E","FFB549","FF9E1B","D57800","996017","6E4C1E","F2C75C","F1BE48","F1B434","ED8B00","CF7F00","A76D11","715C2A","F6BE00","F0B323","FEAD77","E6A65D","D38235","DC8633","C16C18","BD9B60","D69A2D","DB8A06","CD7925","AD6433","89532F","775135","D78825","D3832B","C67D30","B67233","A7662B","9E6A38","835D32","FCC89B","FDBE87","FDAA63","F68D2E","EA7600","D45D00","BE4D00","FECB8B","FFC27B","FFB25B","FF8200","E57200","BE6A14","9B5A1A","EFD19F","EFBE7D","ECA154","E87722","CB6015","A1561C","603D20","FFAE62","FF8F1C","FF6900","B94700","94450B","653819","FFB990","FFA06A","FF7F32","FF6A13","D86018","A65523","8B4720","FFBE9F","FF9D6E","FF7F41","FF671F","E35205","BE531C","73381D","DB864E","E07E3C","DC6B2F","DC582A","C05131","864A33","674736","FFA38B","FF8D6D","FF6A39","FC4C02","DC4405","A9431E","833921","FFB3AB","FF8674","FF5C39","FA4616","CF4520","963821","6B3529","C4622D","BA5826","AF5C37","9E5330","924C2E","7B4D35","5C4738","D4B59E","C07D59","B15533","9D432C","7C3A2D","6B3D2E","5C3D31","D14124","BD472A","B33D26","8D3F2B","83412C","7B4931","674230","E4D5D3","E1BBB4","D6938A","C26E60","A4493D","823B34","683431","DDBCB0","CA9A8E","BC8A7E","A37F74","866761","6B4C4C","583D3E","EABEB0","C09C83","B46A55","AB5C57","A45248","9A6A4F","8A391B","ECC3B2","ECBAA8","EAA794","E8927C","DA291C","9A3324","653024","FFB1BB","FF808B","FF585D","E03C31","BE3A34","81312F","FFA3B5","FF8DA1","F8485E","EE2737","D22630","AF272F","7C2529","FCAFC0","FB637E","F4364C","CB333B","A4343A","643335","C66E4E","C04C36","B7312C","AB2328","93272C","8A2A2B","802F2D","E1523D","C63527","A72B2A","9E2A2B","6D3332","633231","572D2D","E6BAA8","E56A54","E04E39","CD545B","B04A5A","9B2242","651D32","FABBCB","FC9BB3","F65275","E4002B","C8102E","A6192E","76232F","ECC7CD","E89CAE","DF4661","D50032","BA0C2F","9D2235","862633","F8A3BC","F67599","EF426F","E40046","BF0D3E","9B2743","782F40","F5B6CD","F59BBB","EF4A81","E0004D","C5003E","A6093D","8A1538","F5DADF","F7CED7","F9B5C4","F890A5","EF6079","E03E52","CB2C30","F2D4D7","F4C3CC","F2ACB9","E68699","D25B73","B83A4B","9E2A2F","ECB3CB","E782A9","E0457B","CE0037","A50034","861F41","6F263D","F99FC9","F57EB6","F04E98","E31C79","CE0F69","AC145A","7D2248","F4CDD4","E06287","E24585","B52555","A4123F","971B2F","6A2C3E","D6C9CA","C4A4A7","C16784","C63663","BC204B","912F46","7E2D40","EABEDB","E56DB1","DA1884","A50050","910048","6C1D45","936D73","934054","8E2C48","732E4A","672E45","582D40","502B3A","EF95CF","EB6FBD","DF1995","D0006F","AA0061","890C58","672146","F4A6D7","F277C6","E93CAC","C6007E","A20067","840B55","EAD3E2","E6BCD8","DFA0C9","D986BA","C6579A","AE2573","960051","E5CEDB","E3C8D8","DEBED2","C996B6","B06C96","994878","7C2855","E4C6D4","DCB6C9","D0A1BA","BE84A3","A76389","893B67","612141","EBBECB","E8B3C3","E4A9BB","D592AA","84344E","6F2C3F","572932","E2BCCB","DCA9BF","C9809E","B55C80","A73A64","9B3259","872651","E9CDD0","E4BEC3","D7A3AB","C48490","B46B7A","984856","893C47","F2C6CF","F1BDC8","E9A2B2","DC8699","8F3237","7F3035","5D2A2C","E9C4C7","E5BAC1","DAA5AD","C6858F","7A3E3A","6A3735","512F2E","DFC2C3","DBB7BB","CCA1A6","B07C83","9C6169","874B52","3F2021","F1A7DC","EC86D0","E45DBF","DB3EB1","C5299B","AF1685","80225F","EFBAE1","E277CD","D539B5","C800A1","B0008E","9E007E","830065","EAB8E4","E59BDC","DD7FD3","C724B1","BB16A3","A51890","80276C","A56E87","A83D72","991E66","8A1B61","722257","6A2A5B","5E2751","E7BAE4","DD9CDF","C964CF","AD1AAC","981D97","72246C","EBC6DF","E6BEDD","E2ACD7","D48BC8","93328E","833177","612C51","EEDAEA","CCAED0","D59ED7","B288B9","A277A6","9F5CC0","963CBD","D7A9E3","C98BDB","AC4FC6","9B26B6","87189D","772583","653165","948794","A2789C","A15A95","8E3A80","6E2B62","6A3460","5D3754","D5C2D8","C9B1D0","BA9CC5","A57FB2","642F6C","59315F","4B3048","DBCDD3","D0BEC7","C6B0BC","AF95A6","86647A","66435A","4A3041","D8C8D1","D3C0CD","BFA5B8","9B7793","7E5475","693C5E","512A44","DFC8E7","D7B9E4","CAA2DD","B580D1","8031A7","702F8A","572C5F","D6BFDD","C6A1CF","8C4799","6D2077","642667","5D285F","51284F","CBA3D8","B884CB","A05EB5","84329B","702082","671E75","5F2167","9991A4","8D6E97","7A4183","6B3077","653279","5E366E","5C4E63","C1A0DA","A77BCA","8246AF","5C068C","500778","470A68","3C1053","D7C6E6","C1A7E2","9063CD","753BBD","5F259F","582C83","512D6D","C5B4E3","AD96DC","9678D3","7D55C7","330072","2E1A47","B4B5DF","9595D2","7474C1","24135F","211551","201747","221C35","A7A4E0","8B84D7","685BC7","2E008B","280071","250E62","201547","6E7CA0","686E9F","615E9B","565294","514689","4C4184","535486","DDDAE8","B6B8DC","A7A2C3","8986CA","5D4777","4B384C","41273B","878CB4","7C7FAB","7566A0","6F5091","68478D","563D82","523178","E5E1E6","E0DBE3","C6BCD0","A192B2","7C6992","614B79","3F2A56","D8D7DF","C6C4D2","B3B0C4","8D89A5","595478","403A60","1E1A34","C5CFDA","BBC7D6","A2B2C8","8E9FBC","1B365D","1F2A44","1C1F2A","D9E1E2","A4BCC2","98A4AE","768692","425563","253746","131E29","B9D3DC","A3C7D2","8DB9CA","6BA4B8","003D4C","00313C","072B31","BFCED6","B7C9D3","A6BBC8","7A99AC","5B7F95","4F758B","081F2C","D1DDE6","C6D6E3","9BB8D3","7DA1C4","5E8AB4","236192","002E5D","DBE2E9","CED9E5","A7BCD6","7D9BC1","326295","003A70","002554","DDE5ED","C8D8EB","B1C9E8","7BA4DB","407EC9","003594","001A70","BDC5DB","89ABE3","8094DD","7BA6DE","5F8FB4","3A5DAE","606EB2","CBD3EB","9FAEE5","485CC7","1E22AA","171C8F","151F6D","141B4D","B8CCEA","5C88DA","0047BB","06038D","001871","001E62","071D49","C3D7EE","A7C6ED","307FE2","001A72","001E60","13294B","ABCAE9","8BB8E8","418FDE","012169","00205B","041E42","92C1E9","6CACE4","0072CE","0033A0","003087","002D72","0C2340","94A9CB","6787B7","426DA9","385E9D","2C5697","1D4F91","1D428A","C6DAE7","BDD6E6","A4C8E1","7BAFD4","003C71","003057","00263A","B9D9EB","9BCBEB","69B3E7","003DA5","002F6C","002855","041C2C","8DC8E8","62B5E5","009CDE","0057B8","004C97","003865","00263E","71C5E8","41B6E6","00A3E0","005EB8","004B87","003B5C","002A3A","4698CB","298FC2","0076A8","006298","005587","004976","01426A","99D6EA","5BC2E7","00A9E0","0077C8","00629B","004F71","003E51","7BA7BC","6399AE","4E87A0","41748D","34657F","165C7D","005776","BBDDE6","71B2C9","4298B5","0086BF","007DBA","00558C","002B49","9ADBE8","59CBE8","00B5E2","006BA6","00587C","003B49","A4DBE8","8BD3E6","4EC3E0","00AFD7","0095C8","0082BA","0067A0","48A9C5","009CBD","0085AD","007096","006A8E","00617F","005670","B8DDE1","9BD3DD","77C5D5","3EB1C8","0093B2","007396","005F83","6AD1E3","05C3DE","00A9CE","0092BC","007FA3","00677F","004851","68D2DF","00C1D5","00AEC7","008EAA","00778B","006272","004F59","63B1BC","00A7B5","0097A9","00859B","007D8A","007680","006269","B1E4E3","88DBDF","2DCCD3","009CA6","008C95","007377","005F61","A0D1CA","40C1AC","00B0B9","00A3AD","007398","005F86","005A70","7EDDD3","5CB8B2","279989","007681","487A7B","0D5257","244C5A","B6CFD0","ABC7CA","94B7BB","7FA9AE","4F868E","115E67","07272D","00968F","00857D","007672","006D68","00635B","005E5D","005151","9CDBD9","64CCC9","00B2A9","008675","007367","00685E","00534C","71DBD4","2AD2C9","00BFB3","00A499","008578","00594F","004C45","7CE0D3","2CD5C4","00C7B1","00B398","009681","007864","004E42","6DCDB8","49C5B1","00AB8E","009B77","008264","006A52","034638","B9DCD2","A1D6CA","86C8BC","6BBBAE","006F62","00594C","1D3C34","B5E3D8","A5DFD3","98DBCE","6BCABA","00816D","006C5B","173F35","ADCAB8","9ABEAA","85B09A","6FA287","28724F","205C40","284734","BFCEC2","A7BDB1","92ACA0","7F9C90","5C7F71","43695B","183028","BAC5B9","B0BDB0","A3B2A4","94A596","708573","5E7461","22372B","BCC9C5","B1C0BC","9DB0AC","829995","5D7975","3E5D58","18332F","D1E0D7","B7CDC2","9AB9AD","789F90","507F70","285C4D","13322B","A7E6D7","8CE2D0","3CDBC0","009775","007B5F","00664F","8FD6BD","6ECEB2","00B388","00965E","007A53","006747","115740","50A684","00966C","008755","007B4B","006F44","006845","005844","7AE1BF","47D7AC","00C389","00AF66","007749","006341","154734","A0DAB3","91D6AC","71CC98","009A44","00843D","046A38","2C5234","A2E4B8","8FE2B0","80E0A7","00B140","009639","007A33","215732","9BE3BF","26D07C","00BF6F","00B74F","009F4D","275D38","00573F","4B9560","228848","007A3E","007041","286140","36573B","395542","6BA539","48A23F","319B42","3A913F","44883E","4A773C","44693D","ADDC91","A1D884","6CC24A","43B02A","509E2F","4C8C2B","4A7729","D0DEBB","BCE194","8EDD65","78D64B","74AA50","719949","79863C","C2E189","B7DD79","A4D65E","78BE20","64A70B","658D1B","546223","D4EB8E","CDEA80","C5E86C","97D700","84BD00","7A9A01","59621D","C4D6A4","BCD19B","B7CE95","A9C47F","789D4A","67823A","4E5B31","D0D1AB","C6C89B","BABD8B","A2A569","8A8D4A","6D712E","3D441E","D2CE9E","CBC793","C0BB87","AFA96E","A09958","89813D","555025","C3C6A8","B3B995","A3AA83","899064","737B4C","5E6738","3E4827","BFCC80","BBC592","9CAF88","8F993E","76881D","7A7256","5B6236","BABC16","ABAD23","999B30","888D30","7C8034","727337","656635","E2E868","DBE442","CEDC00","C4D600","A8AD00","949300","787121","E9EC6B","E3E935","E0E721","D0DF00","B5BD00","9A9500","827A04","E3E48D","E0E27C","DBDE70","D2D755","B7BF10","8E8C13","625D20","F0EC74","EDE939","ECE81A","E1E000","BFB800","ADA400","A09200","F3EA5D","F3E500","EFDF00","EEDC00","BBA600","9A8700","685C20","F1EB9C","F0E991","F0E87B","EDE04B","EADA24","E1CD00","CFB500","EBE49A","E9E186","E6DE77","E1D555","D7C826","C4B000","B39B00","E9DF97","E4D77E","DECD63","D9C756","B89D18","A28E2A","695B24","DCD59A","D6CF8D","D0C883","C0B561","AC9F3C","9F912A","8A7B19","CAB64B","CFB023","C1A01E","A08629","897630","736635","675E33","D4C304","C4B200","91852C","747136","5D6439","585C3B","535435","BBB323","B4A91F","AA9D2E","8F7E35","716135","635939","4E4934","D5CB9F","CFC493","C5B783","B3A369","998542","8C7732","614F25","CAC7A7","BFBB98","B0AA7E","9B945F","594A25","524727","4A412A","F1E6B2","DFD1A7","D9C89E","CEB888","A89968","94795D","816040","DDCBA4","D3BC8D","C6AA76","B9975B","8B5B29","744F28","5C462B","EFDBB2","FCD299","E1B87F","D6A461","C6893F","B77729","A6631B","EDC8A3","E7B78A","DDA46F","C88242","B36924","934D11","7D3F16","F3CFB3","F1C6A7","F0BF9B","E59E6D","B86125","A45A2A","693F23","E0C09F","D9B48F","CDA077","B58150","9E652E","774212","623412","E0C6AD","DCBFA6","CDA788","BF9474","AD7C59","946037","4F2C1D","E1B7A7","D5A286","C58B68","99552B","85431E","6D4F47","5E4B3C","D7C4B7","CDB5A7","C0A392","AE8A79","956C58","7C4D3A","5B3427","DBC8B6","D3BBA8","C6A992","AA8066","703F2A","623B2A","4E3629","D6D2C4","C5B9AC","B7A99A","A39382","7A6855","63513D","473729","D1CCBD","B7B09C","A69F88","A7ACA2","949A90","8E9089","4B4F54","D0D3D4","C1C6C8","A2AAAD","7C878E","5B6770","333F48","1D252D","C7C9C7","B2B4B2","9EA2A2","898D8D","707372","54585A","25282A","BEC6C4","A2ACAB","919D9D","717C7D","505759","3F4444","373A36","BABBB1","A8A99E","919388","7E7F74","65665C","51534A","212322","C4BFB6","AFA9A0","9D968D","8C857B","776E64","696158","C4BCB7","B2A8A2","978C87","857874","746661","5E514D","382F2D","D0C4C5","C1B2B6","AB989D","7B6469","584446","453536","382E2C","D7D2CB","CBC4BC","BFB8AF","B6ADA5","ACA39A","A59C94","968C83","8C8279","83786F","796E65","6E6259","D9D9D6","D0D0CE","C8C9C7","BBBCBC","B1B3B3","A7A8AA","97999B","888B8D","75787B","63666A","53565A","332F21","212721","31261D","3E2B2E","101820","3D3935"],na=$t.map(i=>[parseInt(i.substring(0,2),16),parseInt(i.substring(2,4),16),parseInt(i.substring(4,6),16)]);function ho(i){const t=re.indexOf(i);return t>=0?$t[t]:""}function ni(i){const t=$t.indexOf(i);return t>=0?re[t]:""}function go(i,t=64){const e=[],a=[],n=ni(i);n&&e.push({pms:n,hex:i,distance:0});const r=parseInt(i.substring(0,2),16),o=parseInt(i.substring(2,4),16),s=parseInt(i.substring(4,6),16);let l,c,d;for(let u=0;u<$t.length;u++){l=na[u][0],c=na[u][1],d=na[u][2];const A=Math.sqrt(Math.pow(r-l,2)+Math.pow(o-c,2)+Math.pow(s-d,2));a.push(A)}for(let u=0;u<a.length;u++)a[u]<=t&&!e.some(A=>A.pms===re[u])&&e.push({pms:re[u],hex:$t[u],distance:a[u]});return e.sort((u,A)=>u.distance-A.distance)}const mo=re.map((i,t)=>({pms:i,hex:$t[t]})),po=new Tr(mo,{keys:["pms"]});function fo(i,t){return po.search(i,t?{limit:t}:void 0)}let Lt=null;function ii(i){if(i.startsWith("#"))return pn(i);if(!document)throw new Error("browserColorToHex is only supported on browsers");if(Lt||(Lt=document.createElement("canvas").getContext("2d")),!Lt)throw new Error("Failed to create canvas context required to convert colors");Lt.fillStyle=i;const t=pn(Lt.fillStyle);return t||console.error(`Unknown browser color ${i}`),t}function pn(i){const t=i.substring(1).toUpperCase();return t.length===6?t:t.length===3?`${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`:""}const ve=i=>{const t=ri(i.spotColor);return t?`${i.browserValue} ${t}`:i.browserValue},ri=i=>{if(!i)return"";if(i.profileName.includes("/")&&i.profileName.includes(".icc")){const t=i.profileName.replace(/\s/g,"-"),e=t.lastIndexOf("/");return`icc-named-color(${t.slice(e+1).slice(0,-4)}, ${i.namedColor})`}return`icc-named-color(${i.profileName}, ${i.namedColor})`},Ea=i=>{const t=i.split(/[ ](?=[^)]*?(?:\(|$))/);if(t.length===0)return{browserValue:"#000000"};if(t.length===1)return{browserValue:t[0]};const e=t[1].match(/\(([^)]+)\)/gm);if(!e)throw new Error("Unhandled state of color value in SVG");const a=e[0].replace(/[() ]/g,"").split(",");return{browserValue:t[0],spotColor:{profileName:a[0],namedColor:a[1]}}},Co=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],wo=["fill","stroke"],Vt=(i,t)=>{t(i),i.children.length>0&&Array.from(i.children).forEach(e=>Vt(e,t))},oi=(i,t)=>{const e=t(i);if(e)return e;const a=i.parentElement;if(a)return oi(a,t)},yo=(i,t)=>{try{return i.matches(t)}catch{return i.classList.contains(t.substring(1))}},He=(i,t=!1)=>{!t&&i.setAttribute("preserveAspectRatio","none");const e=[];Vt(i,a=>{if(a.tagName==="script"){a.remove();return}if(a.tagName==="style"){try{Vn.parse(a.innerHTML).stylesheet?.rules.forEach(o=>{e.push(o)}),a.remove()}catch(r){console.error(r)}return}const n=a.attributes.getNamedItem("style")?.value?.trim();if(n){const r=[];n.split(";").forEach(s=>{const l=s.trim();if(l){const[c,d]=l.split(":"),u=c.toLowerCase();wo.indexOf(u)>-1?a.setAttribute(u,d.trim()):r.push(l)}}),r.length>0?a.setAttribute("style",r.join(";")):a.removeAttribute("style")}}),Vt(i,a=>{e.forEach(n=>{n.selectors?.forEach(r=>{yo(a,r)&&n.declarations?.forEach(o=>{o.property&&o.value&&a.setAttribute(o.property,o.value)})})})})},So=i=>{const t=/pt|pc|mm|cm|in/gm,e=i.getAttribute("viewBox"),a=i.getAttribute("width"),n=i.getAttribute("height");if(!e)throw new Error("viewBox not specified on SVG!");a&&i.setAttribute("width",a.replace(t,"")),n&&i.setAttribute("height",n.replace(t,""))},si=i=>ct().parseFromString(i,"image/svg+xml").firstElementChild,vo=(i,t,e)=>{i.setAttribute("height",`${e}px`),i.setAttribute("width",`${t}px`)},li=(i,t,e)=>{Vt(i,a=>{const n=a.attributes.getNamedItem("fill");n&&n.value!=="none"&&a.classList.forEach(o=>{if(o.startsWith("spiff-fill")){const s=t[o.replace("spiff-fill-","")];if(s)a.setAttribute("fill",e?ve(s):s.browserValue);else{const l=t[o];l&&a.setAttribute("fill",e?ve(l):l.browserValue)}}});const r=a.attributes.getNamedItem("stroke");r&&r.value!=="none"&&a.classList.forEach(o=>{if(o.startsWith("spiff-stroke")){const s=t[o.replace("spiff-stroke-","")];if(s)a.setAttribute("stroke",e?ve(s):s.browserValue);else{const l=t[o];l&&a.setAttribute("fill",e?ve(l):l.browserValue)}}})})},ci=i=>bt().serializeToString(i),La=(i,t,e,a,n)=>{const r=si(i);if(!r)throw new Error("Failed to read SVG.");return vo(r,t,e),li(r,a,n),ci(r)},We=(i,t,e)=>{const a=si(i);if(!a)throw new Error("Failed to read SVG.");return li(a,t,e),ci(a)},Eo=i=>{const t=/<svg.*<\/svg>/s,e=i.match(t)||[],a=e?.length>0?e[0]:"";return ct().parseFromString(a,"image/svg+xml")},rt=async i=>{const e=Eo(i).firstElementChild;if(!e)throw new Error("Failed to read SVG.");He(e);const a={};Vt(e,o=>{if(Co.includes(o.tagName)&&!o.attributes.getNamedItem("fill")){let c="black";const d=o.parentElement;if(d){const u=oi(d,A=>{const g=A.style.fill;if(g)return g;const p=A.getAttribute("fill");if(p)return p});u&&(c=u)}o.setAttribute("fill",c)}const s=o.attributes.getNamedItem("fill");if(s&&s.value!=="none"&&!s.value.startsWith("url(")){const c=Ea(s.value),d=c.browserValue.replace(/\W/g,""),u=`spiff-fill-${d}`;o.setAttribute("fill",c.browserValue),o.classList.add(u),a[d]=c}const l=o.attributes.getNamedItem("stroke");if(l&&l.value!=="none"&&!l.value.startsWith("url(")){const c=Ea(l.value),d=c.browserValue.replace(/\W/g,""),u=`spiff-stroke-${d}`;o.classList.add(u),o.setAttribute("stroke",c.browserValue),a[d]=c}});const r=bt().serializeToString(e);return{colors:a,svg:r}},bo=C.gql`
2
2
  fragment AssetMetadataFields on Asset {
3
3
  metadata {
4
4
  key
@@ -137,7 +137,7 @@
137
137
  ...AssetFields
138
138
  }
139
139
  }
140
- `,ke=async i=>(await y.getShadowGraphqlClient().query({query:Io,errorPolicy:"all",fetchPolicy:"no-cache",variables:{keys:i}})).data.assets,Do=async i=>(await y.getShadowGraphqlClient().query({query:Bo,errorPolicy:"all",variables:{ids:i}})).data.materials,ko=async(i,t,e,a,n)=>(await y.getShadowGraphqlClient().mutate({mutation:Po,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:i,type:t,mimeType:e,anonymous:a,temporary:n}})).data?.assetCreate;class Mo{constructor(){this.cache=new Map,this.bgrmProcessCache=new Map,this.materialCache=new Map,this.loadImageAsFileInfo=async t=>{const e=await t.arrayBuffer(),a=await ue(e),n=(r,o)=>{const s=atob(r.split(",")[1]),l=[];for(let c=0;c<s.length;c++)l.push(s.charCodeAt(c));return new Blob([new Uint8Array(l)],{type:o})};return{name:t.name.substring(t.name.lastIndexOf("/")+1),blob:n(a.dataUrl,t.type)}}}async getLocalOrFromServer(t){if(this.cache.has(t)){const n=this.cache.get(t);if(!n)throw new R("Failed to get asset from cache!");return n}const a=(async()=>(await ke([t]))[0])();return this.cache.set(t,a),a}async getFromServer(t){const a=(async()=>(await ke([t]))[0])();return this.cache.set(t,a),a}keyFromURL(t){let e;try{e=new URL(t).pathname}catch{e=void 0}return e!==void 0&&e.startsWith("/")&&(e=e.replace("/","")),e?.split("?")[0]}cacheAsset(t){if(!t.key)throw new R("Asset has no key!");this.cache.has(t.key)||this.cache.set(t.key,Promise.resolve(t))}cacheMaterial(t){if(!t.id)throw new R("Material has no id!");this.materialCache.has(t.id)||this.materialCache.set(t.id,Promise.resolve(t))}async getMaterialLocalOrFromServer(t){if(this.materialCache.has(t))return this.materialCache.get(t);const a=(async()=>(await Do([t]))[0])();return this.materialCache.set(t,a),a}async uploadAssetWithProgress(t,e,a,n,r){const o=await this.dispatchCreateAssetRequest(t,e,n,r);if(!o)throw new Error("Failed to create asset.");return await new Promise((s,l)=>{const c=new XMLHttpRequest;c.open("PUT",o.assetResponse.uploadUrl,!0),c.setRequestHeader("Content-Type",o.mimeType),c.setRequestHeader("Cache-Control","public,max-age=31536000,immutable"),c.upload.onprogress=d=>{d.lengthComputable&&a(d.loaded*100/d.total)},c.onload=()=>{const d=o.assetResponse.asset;ut.add(o.assetResponse.asset),s(d)},c.onerror=l,this.postProcessFileUpload(t,o.mimeType).then(d=>c.send(d.blob)).catch(l)}),this.cacheAsset(o.assetResponse.asset),o.assetResponse.asset}async uploadAsset(t,e,a,n){return this.uploadAssetWithProgress(t,e,()=>{},a,n)}async uploadFile(t,e){const n=this.isRaster(t)?ne.Image:ne.Illustration,r=await this.loadImageAsFileInfo(t);return await this.uploadAssetWithProgress(r,n,e,!0)}async removeBackgroundFromAsset(t){const e=t.key;if(this.bgrmProcessCache.has(e))return this.bgrmProcessCache.get(e);if(q.has(qt,e)){const r=this.getLocalOrFromServer(q.get(qt,e));return this.bgrmProcessCache.set(e,r),r}const n=(async()=>{const r=await y.getShadowGraphqlClient().mutate({mutation:xo,fetchPolicy:"no-cache",errorPolicy:"all",variables:{key:e}});if(this.bgrmProcessCache.delete(e),!r.data?.assetRemoveBackground?.key)throw new Error("Failed to remove background from image");return ut.add(r.data.assetRemoveBackground),q.add(qt,e,r.data.assetRemoveBackground.key),this.cache.set(r.data.assetRemoveBackground.key,Promise.resolve(r.data.assetRemoveBackground)),r.data.assetRemoveBackground})();return this.bgrmProcessCache.set(e,n),n}async vectorizeAsset(t,e=void 0){const a=t.key;if(this.bgrmProcessCache.has(a))return this.bgrmProcessCache.get(a);if(q.has(Gt,a)){const o=this.getLocalOrFromServer(q.get(Gt,a));return this.bgrmProcessCache.set(a,o),o}const r=(async()=>{const o=await y.getShadowGraphqlClient().mutate({mutation:Fo,fetchPolicy:"no-cache",errorPolicy:"all",variables:{key:a,options:{maxColorCount:e}}});if(this.bgrmProcessCache.delete(a),!o.data?.assetVectorize?.key)throw new Error("Failed to vectorize image");return ut.add(o.data.assetVectorize),q.add(Gt,a,o.data.assetVectorize.key),this.cache.set(o.data.assetVectorize.key,Promise.resolve(o.data.assetVectorize)),o.data.assetVectorize})();return this.bgrmProcessCache.set(a,r),r}removePersistedAsset(t){ut.remove(t),q.delete(qt,t),q.delete(Gt,t),q.deleteForTransformedKey(qt,t),q.deleteForTransformedKey(Gt,t)}getPersistedAssets(){return ut.list()}registerPersistedAssetListener(t){ut.addCallback(t)}unRegisterPersistedAssetListener(t){ut.removeCallback(t)}isRaster(t){return!(t.type==="image/svg+xml"||t.type==="application/pdf"||t.type==="application/postscript")}async postProcessFileUpload(t,e){if(e==="image/svg+xml"){const a=await t.blob.text(),o=new window.DOMParser().parseFromString(a,"image/svg+xml").documentElement;if(!o)throw new Bt("Failed to read SVG.");So(o);const l=bt().serializeToString(o);return{name:t.name,blob:new Blob([l],{type:"image/svg+xml"})}}return t}async dispatchCreateAssetRequest(t,e,a,n){const r=t.blob.type?t.blob.type:this.guessMIME(t.name),o=await ko(t.name,e,r,a,n);if(o)return{assetResponse:o,mimeType:r}}guessMIME(t){const e=t.split(".").pop();switch(e){case"glb":return"model/gltf-binary";case"ttf":return"font/ttf";case"mkv":return"video/x-matroska";default:throw new R("Unexpected mimetype: "+e)}}}const zt="persistentAssets",ht=class ht{static add(t){if(!t.fileLink){console.error("Failed to find cdn link on asset, cannot persist!");return}const e=new Map;e.set(t.key||"",t.fileLink);const a=Q.getMap(zt);a&&a.forEach((n,r)=>{e.set(r,n)}),Q.setMap(zt,e),ht.executeCallbacks()}static remove(t){const e=Q.getMap(zt);if(!e)return;const a=Array.from(e.entries()).find(n=>n[0]===t);a&&(e.delete(a[0]),Q.setMap(zt,e),ht.executeCallbacks())}static list(){const t=Q.getMap(zt);return t?Array.from(t.entries()).map(e=>({assetKey:e[0],src:e[1]})):[]}static addCallback(t){ht.callbacks.push(t)}static removeCallback(t){ht.callbacks=ht.callbacks.filter(e=>e!==t)}static executeCallbacks(){ht.callbacks.forEach(t=>t())}};ht.callbacks=[];let ut=ht;const qt="bgrmPersistentAssets",Gt="vectorizePersistentAssets";class q{static has(t,e){return q.getMap(t).has(e)}static get(t,e){return q.getMap(t).get(e)}static keys(t){return q.getMap(t).keys()}static values(t){return q.getMap(t).values()}static add(t,e,a){const n=q.getMap(t);n.set(e,a),q.setMap(t,n)}static delete(t,e){const a=q.getMap(t);a.delete(e),q.setMap(t,a)}static deleteForTransformedKey(t,e){const a=q.getMap(t),n=Array.from(a.keys()).find(r=>a.get(r)===e);n&&(a.delete(n),q.setMap(t,a))}static getMap(t){return Q.getMap(t)||new Map}static setMap(t,e){Q.setMap(t,e)}}const G=new Mo;class To{constructor(){this.cache={},this.disabled=!1}get(t){if(this.disabled)return;const e=JSON.stringify(t);return this.cache[e]}set(t,e){if(this.disabled)return e;const a=JSON.stringify(t);return this.cache[a]=e,e}disable(t){this.disabled=t}}const oe=new To,No=C.gql`
140
+ `,ke=async i=>(await y.getShadowGraphqlClient().query({query:Io,errorPolicy:"all",fetchPolicy:"no-cache",variables:{keys:i}})).data.assets,Do=async i=>(await y.getShadowGraphqlClient().query({query:Bo,errorPolicy:"all",variables:{ids:i}})).data.materials,ko=async(i,t,e,a,n)=>(await y.getShadowGraphqlClient().mutate({mutation:Po,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:i,type:t,mimeType:e,anonymous:a,temporary:n}})).data?.assetCreate;class Mo{constructor(){this.cache=new Map,this.bgrmProcessCache=new Map,this.materialCache=new Map,this.loadImageAsFileInfo=async t=>{const e=await t.arrayBuffer(),a=await ue(e),n=(r,o)=>{const s=atob(r.split(",")[1]),l=[];for(let c=0;c<s.length;c++)l.push(s.charCodeAt(c));return new Blob([new Uint8Array(l)],{type:o})};return{name:t.name.substring(t.name.lastIndexOf("/")+1),blob:n(a.dataUrl,t.type)}}}async getLocalOrFromServer(t){if(this.cache.has(t)){const n=this.cache.get(t);if(!n)throw new R("Failed to get asset from cache!");return n}const a=(async()=>(await ke([t]))[0])();return this.cache.set(t,a),a}async getFromServer(t){const a=(async()=>(await ke([t]))[0])();return this.cache.set(t,a),a}keyFromURL(t){let e;try{e=new URL(t).pathname}catch{e=void 0}return e!==void 0&&e.startsWith("/")&&(e=e.replace("/","")),e?.split("?")[0]}cacheAsset(t){if(!t.key)throw new R("Asset has no key!");this.cache.has(t.key)||this.cache.set(t.key,Promise.resolve(t))}cacheMaterial(t){if(!t.id)throw new R("Material has no id!");this.materialCache.has(t.id)||this.materialCache.set(t.id,Promise.resolve(t))}async getMaterialLocalOrFromServer(t){if(this.materialCache.has(t))return this.materialCache.get(t);const a=(async()=>(await Do([t]))[0])();return this.materialCache.set(t,a),a}async uploadAssetWithProgress(t,e,a,n,r){const o=await this.dispatchCreateAssetRequest(t,e,n,r);if(!o)throw new Error("Failed to create asset.");return await new Promise((s,l)=>{const c=new XMLHttpRequest;c.open("PUT",o.assetResponse.uploadUrl,!0),c.setRequestHeader("Content-Type",o.mimeType),c.setRequestHeader("Cache-Control","public,max-age=31536000,immutable"),c.upload.onprogress=d=>{d.lengthComputable&&a(d.loaded*100/d.total)},c.onload=()=>{const d=o.assetResponse.asset;ut.add(o.assetResponse.asset),s(d)},c.onerror=l,this.postProcessFileUpload(t,o.mimeType).then(d=>c.send(d.blob)).catch(l)}),this.cacheAsset(o.assetResponse.asset),o.assetResponse.asset}async uploadAsset(t,e,a,n){return this.uploadAssetWithProgress(t,e,()=>{},a,n)}async uploadFile(t,e){const n=this.isRaster(t)?ne.Image:ne.Illustration,r=await this.loadImageAsFileInfo(t);return await this.uploadAssetWithProgress(r,n,e,!0)}async removeBackgroundFromAsset(t){const e=t.key;if(this.bgrmProcessCache.has(e))return this.bgrmProcessCache.get(e);if(q.has(qt,e)){const r=this.getLocalOrFromServer(q.get(qt,e));return this.bgrmProcessCache.set(e,r),r}const n=(async()=>{const r=await y.getShadowGraphqlClient().mutate({mutation:xo,fetchPolicy:"no-cache",errorPolicy:"all",variables:{key:e}});if(this.bgrmProcessCache.delete(e),!r.data?.assetRemoveBackground?.key)throw new Error("Failed to remove background from image");return ut.add(r.data.assetRemoveBackground),q.add(qt,e,r.data.assetRemoveBackground.key),this.cache.set(r.data.assetRemoveBackground.key,Promise.resolve(r.data.assetRemoveBackground)),r.data.assetRemoveBackground})();return this.bgrmProcessCache.set(e,n),n}async vectorizeAsset(t,e=void 0){const a=t.key;if(this.bgrmProcessCache.has(a))return this.bgrmProcessCache.get(a);if(q.has(Gt,a)){const o=this.getLocalOrFromServer(q.get(Gt,a));return this.bgrmProcessCache.set(a,o),o}const r=(async()=>{const o=await y.getShadowGraphqlClient().mutate({mutation:Fo,fetchPolicy:"no-cache",errorPolicy:"all",variables:{key:a,options:{maxColorCount:e}}});if(this.bgrmProcessCache.delete(a),!o.data?.assetVectorize?.key)throw new Error("Failed to vectorize image");return ut.add(o.data.assetVectorize),q.add(Gt,a,o.data.assetVectorize.key),this.cache.set(o.data.assetVectorize.key,Promise.resolve(o.data.assetVectorize)),o.data.assetVectorize})();return this.bgrmProcessCache.set(a,r),r}removePersistedAsset(t){ut.remove(t),q.delete(qt,t),q.delete(Gt,t),q.deleteForTransformedKey(qt,t),q.deleteForTransformedKey(Gt,t)}getPersistedAssets(){return ut.list()}registerPersistedAssetListener(t){ut.addCallback(t)}unRegisterPersistedAssetListener(t){ut.removeCallback(t)}isRaster(t){return!(t.type==="image/svg+xml"||t.type==="application/pdf"||t.type==="application/postscript")}async postProcessFileUpload(t,e){if(e==="image/svg+xml"){const a=await t.blob.text(),o=new window.DOMParser().parseFromString(a,"image/svg+xml").documentElement;if(!o)throw new Bt("Failed to read SVG.");So(o);const l=bt().serializeToString(o);return{name:t.name,blob:new Blob([l],{type:"image/svg+xml"})}}return t}async dispatchCreateAssetRequest(t,e,a,n){const r=t.blob.type?t.blob.type:this.guessMIME(t.name),o=await ko(t.name,e,r,a,n);if(o)return{assetResponse:o,mimeType:r}}guessMIME(t){const e=t.split(".").pop();switch(e){case"glb":return"model/gltf-binary";case"ttf":return"font/ttf";case"mkv":return"video/x-matroska";default:throw new R("Unexpected mimetype: "+e)}}}const zt="persistentAssets",At=class At{static add(t){if(!t.fileLink){console.error("Failed to find cdn link on asset, cannot persist!");return}const e=new Map;e.set(t.key||"",t.fileLink);const a=Q.getMap(zt);a&&a.forEach((n,r)=>{e.set(r,n)}),Q.setMap(zt,e),At.executeCallbacks()}static remove(t){const e=Q.getMap(zt);if(!e)return;const a=Array.from(e.entries()).find(n=>n[0]===t);a&&(e.delete(a[0]),Q.setMap(zt,e),At.executeCallbacks())}static list(){const t=Q.getMap(zt);return t?Array.from(t.entries()).map(e=>({assetKey:e[0],src:e[1]})):[]}static addCallback(t){At.callbacks.push(t)}static removeCallback(t){At.callbacks=At.callbacks.filter(e=>e!==t)}static executeCallbacks(){At.callbacks.forEach(t=>t())}};At.callbacks=[];let ut=At;const qt="bgrmPersistentAssets",Gt="vectorizePersistentAssets";class q{static has(t,e){return q.getMap(t).has(e)}static get(t,e){return q.getMap(t).get(e)}static keys(t){return q.getMap(t).keys()}static values(t){return q.getMap(t).values()}static add(t,e,a){const n=q.getMap(t);n.set(e,a),q.setMap(t,n)}static delete(t,e){const a=q.getMap(t);a.delete(e),q.setMap(t,a)}static deleteForTransformedKey(t,e){const a=q.getMap(t),n=Array.from(a.keys()).find(r=>a.get(r)===e);n&&(a.delete(n),q.setMap(t,a))}static getMap(t){return Q.getMap(t)||new Map}static setMap(t,e){Q.setMap(t,e)}}const G=new Mo;class To{constructor(){this.cache={},this.disabled=!1}get(t){if(this.disabled)return;const e=JSON.stringify(t);return this.cache[e]}set(t,e){if(this.disabled)return e;const a=JSON.stringify(t);return this.cache[a]=e,e}disable(t){this.disabled=t}}const oe=new To,No=C.gql`
141
141
  fragment OptionMinimalFields on Option {
142
142
  id
143
143
  defaultVariant {
@@ -1377,10 +1377,10 @@
1377
1377
  matrix(1, 0, 0, 1, ${i.width/2}, ${i.height/2})
1378
1378
  matrix(${a}, ${-n}, ${n}, ${a}, 0, 0)
1379
1379
  matrix(1, 0, 0, 1, ${-i.width/2}, ${-i.height/2})
1380
- `;if(!i.svg)throw new Error(`Illustration element ${i.id} (stepName ${i.stepName}) lacked svg from src ${i.src} at render time.`);return B.jsx("g",{mask:i.stepName?void 0:i.mask,children:B.jsx("g",{transform:r,dangerouslySetInnerHTML:{__html:La(i.svg,i.width,i.height,i.colors,i._renderingConfiguration?.spotColors)}})})};class bi{constructor(){this.id=N(),this.stateCallbacks=[],this.prevCommands=[],this.nextCommands=[]}registerStateCallback(t){this.stateCallbacks.push(t)}unregisterStateCallback(t){this.stateCallbacks.filter(e=>e!==t)}getState(){return this.state}runStateCallbacks(){this.stateCallbacks.forEach(t=>t())}apply(t,e){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);this.state=this.commandReducer(this.state,t),this.runStateCallbacks(),this.nextCommands=[],e||this.prevCommands.push(t)}undo(){if(!this.state)return;const t=this.prevCommands.pop();if(!t)return;const e=t.undo();this.state={...this.state,transaction:e},this.nextCommands.push(t),this.runStateCallbacks()}redo(){if(!this.state)return;const t=this.nextCommands.pop();t&&(this.state=this.commandReducer(this.state,t),this.runStateCallbacks(),this.prevCommands.push(t))}flattenSequence(t,e){const n=this.prevCommands.filter(r=>r.sequenceId===t).pop();n&&(this.prevCommands=this.prevCommands.filter(r=>r.sequenceId!==t),n?.overrideOldState(e),this.prevCommands.push(n))}getLayoutById(t){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);const e=this.state.transaction?.layouts?.[t],a=e?.layout;if(!a)throw new Error(`No layout: ${t}`);const n=[...e?.elements||[]];return this.getLayoutDataWithState(a,n)}getAllLayouts(){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);const t=[...Object.keys(this.state.transaction?.layouts)];return[...new Set(t)].map(a=>this.getLayoutById(a))}getLayoutDataWithState(t,e){return{layoutState:{layout:t,elements:e},getComponentWithProps:a=>Ke(t,e,a)}}initialize(t,e){if(e){this.state={transaction:e};return}let a={serializableWorkflow:{steps:[]},layouts:{}};t.forEach(n=>{a=new Ya(n).apply(a)}),this.runStateCallbacks(),this.state={transaction:a}}commandReducer(t,e){const a=t.transaction||{layouts:{},serializableWorkflow:{steps:[]}};return{...t,transaction:e.apply(a)}}}const Ii=i=>i.type===D.Image?B.jsx(fi,{...i},i.id):i.type===D.Frame?B.jsx(Ps,{...i},i.id):i.type===D.Illustration?B.jsx(Ls,{...i},i.id):i.type===D.Textbox?B.jsx($s,{...i},i.id):i.type===D.Group?B.jsx(Ci,{...i},i.id):null,Ke=(i,t,e)=>{const a=e.renderingConfiguration,n=a?.removeExcludedElements?t.filter(r=>!r.excludeFromExport):t;return B.jsx(gs,{preserveAspectRatio:void 0,elements:n,backgroundColor:i.transparentBackground?void 0:e.backgroundColor?e.backgroundColor:"white",width:e.width||i.width,height:e.height||i.height,viewBox:a?.region?{x:a.region.left,y:a.region.top,width:a.region.width,height:a.region.height}:{x:0,y:0,width:i.width,height:i.height},configuration:a,outlineArea:e.outlineArea,maxHeight:e.maxHeight,maxWidth:e.maxWidth,position:e.position,borderRadius:e.borderRadius,outlineColor:e.outlineColor})};function Ga(i){return i.sort((t,e)=>{const a=t.layer||0,n=e.layer||0;if(a<n)return-1;if(a>n)return 1;const r=t.layerIndex||0,o=e.layerIndex||0;return r<o?-1:r>o?1:0})}const gt=new Map,Mt=new Map,la=new Map,Bi=async(i,t)=>{if(!t){if(!i)throw new Error("No region or src supplied. Cannot construct frame!");return Ia(i)}return et(t)},Ia=i=>{const t=i.width,e=i.height;return`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${t} ${e}'>
1380
+ `;if(!i.svg)throw new Error(`Illustration element ${i.id} (stepName ${i.stepName}) lacked svg from src ${i.src} at render time.`);return B.jsx("g",{mask:i.stepName?void 0:i.mask,children:B.jsx("g",{transform:r,dangerouslySetInnerHTML:{__html:La(i.svg,i.width,i.height,i.colors,i._renderingConfiguration?.spotColors)}})})};class bi{constructor(){this.id=N(),this.stateCallbacks=[],this.prevCommands=[],this.nextCommands=[]}registerStateCallback(t){this.stateCallbacks.push(t)}unregisterStateCallback(t){this.stateCallbacks.filter(e=>e!==t)}getState(){return this.state}runStateCallbacks(){this.stateCallbacks.forEach(t=>t())}apply(t,e){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);this.state=this.commandReducer(this.state,t),this.runStateCallbacks(),this.nextCommands=[],e||this.prevCommands.push(t)}undo(){if(!this.state)return;const t=this.prevCommands.pop();if(!t)return;const e=t.undo();this.state={...this.state,transaction:e},this.nextCommands.push(t),this.runStateCallbacks()}redo(){if(!this.state)return;const t=this.nextCommands.pop();t&&(this.state=this.commandReducer(this.state,t),this.runStateCallbacks(),this.prevCommands.push(t))}flattenSequence(t,e){const n=this.prevCommands.filter(r=>r.sequenceId===t).pop();n&&(this.prevCommands=this.prevCommands.filter(r=>r.sequenceId!==t),n?.overrideOldState(e),this.prevCommands.push(n))}getLayoutById(t){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);const e=this.state.transaction?.layouts?.[t],a=e?.layout;if(!a)throw new Error(`No layout: ${t}`);const n=[...e?.elements||[]];return this.getLayoutDataWithState(a,n)}getAllLayouts(){if(!this.state)throw new Error(`State not initialized for cc ${this.id}!`);const t=[...Object.keys(this.state.transaction?.layouts)];return[...new Set(t)].map(a=>this.getLayoutById(a))}getLayoutDataWithState(t,e){return{layoutState:{layout:t,elements:e},getComponentWithProps:a=>Ke(t,e,a)}}initialize(t,e){if(e){this.state={transaction:e};return}let a={serializableWorkflow:{steps:[]},layouts:{}};t.forEach(n=>{a=new Ya(n).apply(a)}),this.runStateCallbacks(),this.state={transaction:a}}commandReducer(t,e){const a=t.transaction||{layouts:{},serializableWorkflow:{steps:[]}};return{...t,transaction:e.apply(a)}}}const Ii=i=>i.type===D.Image?B.jsx(fi,{...i},i.id):i.type===D.Frame?B.jsx(Ps,{...i},i.id):i.type===D.Illustration?B.jsx(Ls,{...i},i.id):i.type===D.Textbox?B.jsx($s,{...i},i.id):i.type===D.Group?B.jsx(Ci,{...i},i.id):null,Ke=(i,t,e)=>{const a=e.renderingConfiguration,n=a?.removeExcludedElements?t.filter(r=>!r.excludeFromExport):t;return B.jsx(gs,{preserveAspectRatio:void 0,elements:n,backgroundColor:i.transparentBackground?void 0:e.backgroundColor?e.backgroundColor:"white",width:e.width||i.width,height:e.height||i.height,viewBox:a?.region?{x:a.region.left,y:a.region.top,width:a.region.width,height:a.region.height}:{x:0,y:0,width:i.width,height:i.height},configuration:a,outlineArea:e.outlineArea,maxHeight:e.maxHeight,maxWidth:e.maxWidth,position:e.position,borderRadius:e.borderRadius,outlineColor:e.outlineColor})};function Ga(i){return i.sort((t,e)=>{const a=t.layer||0,n=e.layer||0;if(a<n)return-1;if(a>n)return 1;const r=t.layerIndex||0,o=e.layerIndex||0;return r<o?-1:r>o?1:0})}const ht=new Map,Mt=new Map,la=new Map,Bi=async(i,t)=>{if(!t){if(!i)throw new Error("No region or src supplied. Cannot construct frame!");return Ia(i)}return et(t)},Ia=i=>{const t=i.width,e=i.height;return`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${t} ${e}'>
1381
1381
  <path id="target-path" d='M0 0 h ${t} v ${e} h ${-t} Z' />
1382
1382
  </svg>
1383
- `},zs=async(i,t)=>{if(!t)return;const e=await P.getDefaultVariant(t,i.frameVariantId);if(!e)throw new Error(`No variant with ID: ${i.frameVariantId}`);if(!e.asset)throw new Error(`No asset for variant with ID: ${i.frameVariantId}`);return e},me=async i=>{if(la.has(i))return la.get(i);const e=(async()=>{if(Mt.has(i))return Mt.get(i);await new Promise(A=>setTimeout(A,0));const n=ct().parseFromString(i,"image/svg+xml"),r=n.querySelector("svg");if(!r)throw new Error("Malformed frame SVG: <svg> tag not found");const o=r.getAttribute("viewBox");if(!o)throw new Error("SVG missing viewBox.");const s=o.split(" "),l=parseFloat(s[3])||1,c=parseFloat(s[2])||1,d=n.getElementById("target-path"),u=n.getElementsByClassName("st0").item(0);if(d){const A=d.getAttribute("d");if(!A)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:A,width:c,height:l};return Mt.set(A,h),h}if(u){const A=u.getAttribute("d");if(!A)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:A,width:c,height:l};return Mt.set(A,h),h}throw new Error("Malformed frame SVG")})();return la.set(i,e),e},ja=(i,t,e,a)=>{const n=t.width/t.height,r=i.width/i.height;let o;a?r>n?o=t.height/i.height:o=t.width/i.width:r>n?o=t.width/i.width:o=t.height/i.height,e?.scale!==void 0&&(o*=e?.scale);const s=t.width/2,l=t.height/2,c=s-i.width/2*o,d=e?.left||c,u=l-i.height/2*o,A=e?.top||u;return{x:d,y:A,zoom:o}},Ba=async i=>{if(gt.has(i))return gt.get(i);if(i.startsWith("data:image/svg+xml")){const e=Rr.dataUriToBuffer(i),a=new TextDecoder().decode(e.buffer),n=Wa(a),r={src:i,width:n.width,height:n.height,aspect:n.width/n.height};return gt.set(i,r),r}if((i.split(".").pop()?.toLowerCase()??"")==="svg"){const e=await Ha(i),a=e.width,n=e.height,r={src:i,width:a,height:n,aspect:a/n};return gt.set(i,r),r}else{const e=await qe(i,!0),a=await ue(e),n={src:i,width:a.width,height:a.height,aspect:a.width/a.height};return gt.set(i,n),n}},Ha=async i=>{const t=await et(i);return Wa(t)},vn=i=>i.endsWith("mm")?Number(i.replace("mm",""))*3.7795275591:i.endsWith("px")?Number(i.replace("px","")):Number(i),Wa=i=>{const a=ct().parseFromString(i,"image/svg+xml").querySelector("svg");if(!a)throw new Error("No svg tag found, this svg must be malformed!");const n=a.getAttribute("viewBox"),r=a.getAttribute("width"),o=a.getAttribute("height"),s=o&&r?[0,0,vn(r),vn(o)]:n?.split(" ").map(l=>Number(l));if(!s)throw new Error("No viewbox or width/height values detected on SVG file!");return{width:s[2],height:s[3]}},jt=(i,t)=>{const e=i.layoutState.elements.filter(n=>n.layer===t),a=Math.max(...e.map(n=>n.layerIndex).filter(n=>n!==void 0));return Math.max(a,0)+1},Pi=async i=>new Promise(t=>{et(i).then(e=>{t(e)}).catch(e=>console.error(e))}),ca=new Map,se=async i=>{if(ca.has(i))return ca.get(i);const t=async n=>new Promise((r,o)=>{try{if(!(!!URL&&!!URL.createObjectURL))throw new Error("Environment incapable of generating ObjectURL");n.toBlob(l=>{if(!l)throw n.width===0||n.height===0?new Error(`Canvas dimensions are invalid (${n.width},${n.height})`):n.width*n.height>=268435456?new Error(`Canvas dimensions exceed device limit (${n.width},${n.height})`):new Error("Couldn't generate object URL for Illustration, the blob was undefined!");r(URL.createObjectURL(l))})}catch(s){o(s)}}),a=(async()=>{const o=ct().parseFromString(i,"image/svg+xml").firstElementChild;if(!o)throw new Error("Failed to read SVG");const l=bt().serializeToString(o),c=St(),d=c.getContext("2d"),u=await Qa.Pith.from(d,l,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:St,createImage:de,DOMParser:Ua(),fetch:it}),A=o.getAttribute("width"),h=o.getAttribute("height"),g=2048;if(h&&A){const p=parseFloat(h),f=parseFloat(A)/p;f>1?u.resize(g,g/f):u.resize(g*f,g)}else u.resize(g,g);return await u.render(),await t(c)})();return ca.set(i,a),a},Ht=async(i,t,e,a)=>{const n=i.layoutState.layout.useEditableArea&&i.layoutState.layout.editableArea||{width:i.layoutState.layout.width,height:i.layoutState.layout.height,x:0,y:0},r=n.width<n.height?n.width:n.height,o=i.layoutState.layout.useEditableArea?r/1.3:r/2,s={top:n.y+n.height/2-o/2,left:n.x+n.width/2-o/2,width:o,height:o,rotation:0,panelId:i.layoutState.layout.panelId};if(e&&t===D.Illustration){const l=await rt(await Pi(e)),A=ct().parseFromString(l.svg,"image/svg+xml").firstElementChild.getAttribute("viewBox");if(!A)throw new Error("SVG missing viewBox.");const h=s.height,g=A.split(" "),p=parseFloat(g[2])||1,m=parseFloat(g[3])||1,f=p/m;s.height=s.width/f,s.top+=(h-s.height)/2}if(e&&t===D.Image){const l=s.height,c=await qe(e),d=await ue(c),u=d.width/d.height;s.height=s.width/u,s.top+=(l-s.height)/2}if(e&&t===D.Textbox&&a?.text&&a?.fontScale){await Ft(e);const l=Et(e),c=wt(a.text,a?.fontScale,l);s.width=Math.min(c,n.width*.85),s.left=n.x+n.width/2-s.width/2}return s};class qs{static async getFrame(t,e){const a=await Bi(e.region,e.src),n=await me(a),r=e.region||await Ht(t,D.Frame);return{id:N(),x:r.left,y:r.top,width:r.width,height:r.height,layer:r.layer||0,layerIndex:r.layerIndex||jt(t,r.layer||0),rotation:r.rotation,scaleX:r.width/n.width,scaleY:r.height/n.height,path:n.path,dataWidth:n.width,dataHeight:n.height,type:D.Frame,disablePlaceholder:e.configuration.disablePlaceholder,focalBlur:e.configuration.focalBlur,focalBlurStrength:e.configuration.focalBlurStrength,focalBlurRadius:e.configuration.focalBlurRadius,forceImageCover:e.configuration.forceImageCover,pattern:void 0,immutable:r.immutable}}static async getImage(t,e){const a=e.region||await Ht(t,D.Image,e.src);return{id:N(),src:e.src,type:D.Image,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||jt(t,a.layer||0),immutable:a.immutable,preserveAspectRatio:"none"}}static async getTextbox(t,e){const{configuration:a,fontSrc:n,designInputStep:r}=e,o=await Ft(n),s={assetUrl:n,name:o.names.fullName.en},l=r?.text||a.defaultText||"",c=a.replaceableText?a.replaceableText.replace("{{}}",l):l,d=Te(c,{vertical:a.vertical,uppercase:a.uppercase}),u=e.region||await Ht(t,D.Textbox,n,{text:d,fontScale:a.size?a.size/o.unitsPerEm:void 0}),A=ge({id:N(),type:D.Textbox,x:u.left,y:u.top,width:u.width,height:u.height,align:Os(a.textAlign,a.vertical),curved:a.curved,fill:r?.color||a.colour||"#000000",fontData:s,layer:u.layer||0,layerIndex:u.layerIndex||jt(t,u.layer||0),paths:a.paths,rotation:u.rotation,vertical:a.vertical,verticalAlign:a.verticalAlign||"middle",algorithm:xt.Traditional,fontSize:a.size||Math.max(Math.round(u.height*.025),1),text:d,input:l},d),h=Ns({...u,height:A.height},s,A.fontSize,A?.text?.split(`
1383
+ `},zs=async(i,t)=>{if(!t)return;const e=await P.getDefaultVariant(t,i.frameVariantId);if(!e)throw new Error(`No variant with ID: ${i.frameVariantId}`);if(!e.asset)throw new Error(`No asset for variant with ID: ${i.frameVariantId}`);return e},me=async i=>{if(la.has(i))return la.get(i);const e=(async()=>{if(Mt.has(i))return Mt.get(i);await new Promise(A=>setTimeout(A,0));const n=ct().parseFromString(i,"image/svg+xml"),r=n.querySelector("svg");if(!r)throw new Error("Malformed frame SVG: <svg> tag not found");const o=r.getAttribute("viewBox");if(!o)throw new Error("SVG missing viewBox.");const s=o.split(" "),l=parseFloat(s[3])||1,c=parseFloat(s[2])||1,d=n.getElementById("target-path"),u=n.getElementsByClassName("st0").item(0);if(d){const A=d.getAttribute("d");if(!A)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:A,width:c,height:l};return Mt.set(A,h),h}if(u){const A=u.getAttribute("d");if(!A)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:A,width:c,height:l};return Mt.set(A,h),h}throw new Error("Malformed frame SVG")})();return la.set(i,e),e},ja=(i,t,e,a)=>{const n=t.width/t.height,r=i.width/i.height;let o;a?r>n?o=t.height/i.height:o=t.width/i.width:r>n?o=t.width/i.width:o=t.height/i.height,e?.scale!==void 0&&(o*=e?.scale);const s=t.width/2,l=t.height/2,c=s-i.width/2*o,d=e?.left||c,u=l-i.height/2*o,A=e?.top||u;return{x:d,y:A,zoom:o}},Ba=async i=>{if(ht.has(i))return ht.get(i);if(i.startsWith("data:image/svg+xml")){const e=Rr.dataUriToBuffer(i),a=new TextDecoder().decode(e.buffer),n=Wa(a),r={src:i,width:n.width,height:n.height,aspect:n.width/n.height};return ht.set(i,r),r}if((i.split(".").pop()?.toLowerCase()??"")==="svg"){const e=await Ha(i),a=e.width,n=e.height,r={src:i,width:a,height:n,aspect:a/n};return ht.set(i,r),r}else{const e=await qe(i,!0),a=await ue(e),n={src:i,width:a.width,height:a.height,aspect:a.width/a.height};return ht.set(i,n),n}},Ha=async i=>{const t=await et(i);return Wa(t)},vn=i=>i.endsWith("mm")?Number(i.replace("mm",""))*3.7795275591:i.endsWith("px")?Number(i.replace("px","")):Number(i),Wa=i=>{const a=ct().parseFromString(i,"image/svg+xml").querySelector("svg");if(!a)throw new Error("No svg tag found, this svg must be malformed!");const n=a.getAttribute("viewBox"),r=a.getAttribute("width"),o=a.getAttribute("height"),s=o&&r?[0,0,vn(r),vn(o)]:n?.split(" ").map(l=>Number(l));if(!s)throw new Error("No viewbox or width/height values detected on SVG file!");return{width:s[2],height:s[3]}},jt=(i,t)=>{const e=i.layoutState.elements.filter(n=>n.layer===t),a=Math.max(...e.map(n=>n.layerIndex).filter(n=>n!==void 0));return Math.max(a,0)+1},Pi=async i=>new Promise(t=>{et(i).then(e=>{t(e)}).catch(e=>console.error(e))}),ca=new Map,se=async i=>{if(ca.has(i))return ca.get(i);const t=async n=>new Promise((r,o)=>{try{if(!(!!URL&&!!URL.createObjectURL))throw new Error("Environment incapable of generating ObjectURL");n.toBlob(l=>{if(!l)throw n.width===0||n.height===0?new Error(`Canvas dimensions are invalid (${n.width},${n.height})`):n.width*n.height>=268435456?new Error(`Canvas dimensions exceed device limit (${n.width},${n.height})`):new Error("Couldn't generate object URL for Illustration, the blob was undefined!");r(URL.createObjectURL(l))})}catch(s){o(s)}}),a=(async()=>{const o=ct().parseFromString(i,"image/svg+xml").firstElementChild;if(!o)throw new Error("Failed to read SVG");const l=bt().serializeToString(o),c=St(),d=c.getContext("2d"),u=await Qa.Pith.from(d,l,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:St,createImage:de,DOMParser:Ua(),fetch:it}),A=o.getAttribute("width"),h=o.getAttribute("height"),g=2048;if(h&&A){const p=parseFloat(h),f=parseFloat(A)/p;f>1?u.resize(g,g/f):u.resize(g*f,g)}else u.resize(g,g);return await u.render(),await t(c)})();return ca.set(i,a),a},Ht=async(i,t,e,a)=>{const n=i.layoutState.layout.useEditableArea&&i.layoutState.layout.editableArea||{width:i.layoutState.layout.width,height:i.layoutState.layout.height,x:0,y:0},r=n.width<n.height?n.width:n.height,o=i.layoutState.layout.useEditableArea?r/1.3:r/2,s={top:n.y+n.height/2-o/2,left:n.x+n.width/2-o/2,width:o,height:o,rotation:0,panelId:i.layoutState.layout.panelId};if(e&&t===D.Illustration){const l=await rt(await Pi(e)),A=ct().parseFromString(l.svg,"image/svg+xml").firstElementChild.getAttribute("viewBox");if(!A)throw new Error("SVG missing viewBox.");const h=s.height,g=A.split(" "),p=parseFloat(g[2])||1,m=parseFloat(g[3])||1,f=p/m;s.height=s.width/f,s.top+=(h-s.height)/2}if(e&&t===D.Image){const l=s.height,c=await qe(e),d=await ue(c),u=d.width/d.height;s.height=s.width/u,s.top+=(l-s.height)/2}if(e&&t===D.Textbox&&a?.text&&a?.fontScale){await Ft(e);const l=Et(e),c=wt(a.text,a?.fontScale,l);s.width=Math.min(c,n.width*.85),s.left=n.x+n.width/2-s.width/2}return s};class qs{static async getFrame(t,e){const a=await Bi(e.region,e.src),n=await me(a),r=e.region||await Ht(t,D.Frame);return{id:N(),x:r.left,y:r.top,width:r.width,height:r.height,layer:r.layer||0,layerIndex:r.layerIndex||jt(t,r.layer||0),rotation:r.rotation,scaleX:r.width/n.width,scaleY:r.height/n.height,path:n.path,dataWidth:n.width,dataHeight:n.height,type:D.Frame,disablePlaceholder:e.configuration.disablePlaceholder,focalBlur:e.configuration.focalBlur,focalBlurStrength:e.configuration.focalBlurStrength,focalBlurRadius:e.configuration.focalBlurRadius,forceImageCover:e.configuration.forceImageCover,pattern:void 0,immutable:r.immutable}}static async getImage(t,e){const a=e.region||await Ht(t,D.Image,e.src);return{id:N(),src:e.src,type:D.Image,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||jt(t,a.layer||0),immutable:a.immutable,preserveAspectRatio:"none"}}static async getTextbox(t,e){const{configuration:a,fontSrc:n,designInputStep:r}=e,o=await Ft(n),s={assetUrl:n,name:o.names.fullName.en},l=r?.text||a.defaultText||"",c=a.replaceableText?a.replaceableText.replace("{{}}",l):l,d=Te(c,{vertical:a.vertical,uppercase:a.uppercase}),u=e.region||await Ht(t,D.Textbox,n,{text:d,fontScale:a.size?a.size/o.unitsPerEm:void 0}),A=ge({id:N(),type:D.Textbox,x:u.left,y:u.top,width:u.width,height:u.height,align:Os(a.textAlign,a.vertical),curved:a.curved,fill:r?.color||a.colour||"#000000",fontData:s,layer:u.layer||0,layerIndex:u.layerIndex||jt(t,u.layer||0),paths:a.paths,rotation:u.rotation,vertical:a.vertical,verticalAlign:a.verticalAlign||"middle",algorithm:xt.Traditional,fontSize:a.size||Math.max(Math.round(u.height*.025),1),text:d,input:l},d),h=Ns({...u,height:A.height},s,A.fontSize,A?.text?.split(`
1384
1384
  `)||[],A.align);return{...A,x:h.left,y:h.top+(u.height-h.height)/2,width:h.width,height:h.height}}static async getShape(t,e){const a=`
1385
1385
  <svg
1386
1386
  xmlns="http://www.w3.org/2000/svg"
@@ -1401,7 +1401,7 @@
1401
1401
  fill="${e.color}"
1402
1402
  />
1403
1403
  </svg>
1404
- `,n={};n["spiff-fill-shape"]={browserValue:e.color};const r=e.region?.item||await Ht(t,D.Illustration),o=N();return{stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:n,id:o,svg:a,type:D.Illustration,y:r.top,x:r.left,rotation:r.rotation,width:r.width,height:r.height,layer:r.layer||0,layerIndex:r.layerIndex||jt(t,r.layer||0),immutable:r.immutable}}static async getIllustration(t,e){const a=e.region?.item||await Ht(t,D.Illustration,e.src),n=await rt(await Pi(e.src)),r=await se(n.svg),o=N();return{cachedObjectURL:r,stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:n.colors,id:o,src:e.src,svg:n.svg,type:D.Illustration,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||jt(t,a.layer||0),immutable:a.immutable}}}class j extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,j.prototype)}}const U=(i,t)=>_(i,t).elements.find(n=>n.id===i),_=(i,t)=>{const e=Object.values(t).find(a=>a.elements.some(n=>n.id===i));if(!e)throw new j;return e},tt=(i,t)=>{const e=[...t.elements.filter(n=>n.id!==i.id),i],a=Ga(e);return{layout:t.layout,elements:a,modificationID:N()}},Pa=async i=>{const t=[...Object.keys(i.layouts)],e=[...new Set(t)];for(let a=0;a<e.length;a++){const n=e[a],r=i.layouts[n];await Promise.all(r.elements.map(async o=>{if(o.type==="illustration"){const s=o;if(s.src&&!s.svg){const l=await et(s.src),c=await rt(l);s.svg=La(c.svg,s.width,s.height,s.colors)}}else if(o.type==="frame"){const s=o;if(s.pattern?.colors&&s.pattern?.src){const l=await et(s.pattern?.src),c=await rt(l);s.pattern.svg=c.svg}}isNaN(o.x)&&(o.x=0),isNaN(o.y)&&(o.y=0),isNaN(o.width)&&(o.width=0),isNaN(o.height)&&(o.height=0),isNaN(o.rotation)&&(o.rotation=0)}))}for(const a in i.layouts){const n=i.layouts[a].elements.filter(o=>o.type===D.Illustration);for(let o=0;o<n.length;++o){const s=n[o];if(s.src&&s.svg)try{s.cachedObjectURL=await se(s.svg)}catch(l){console.log(l)}}const r=i.layouts[a].elements.filter(o=>o.type===D.Textbox);for(let o=0;o<r.length;++o){const s=r[o];s.fontData?.assetUrl&&await Ft(s.fontData.assetUrl)}}};class ${undo(){if(!this.oldState)throw new Error("Cannot undo.");return this.oldState}overrideOldState(t){this.oldState=t}}class En extends ${constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class Gs extends ${constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,x:this.x,y:this.y},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class js extends ${constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,rotation:this.angle},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Hs extends ${constructor(t,e,a){super(),this.id=t,this.width=Math.abs(e),this.height=Math.abs(a)}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;let a={...e,width:this.width,height:this.height};if(e.type==="frame"){const o=a;o.scaleX=o.scaleX*this.width/e.width,o.scaleY=o.scaleY*this.height/e.height}else if(e.type==="textbox"){const o=a,s=(!o.algorithm||o.algorithm===xt.Autosize?o.text:o.input)??"";a=ge(o,s,e)}const n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class V extends ${constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class Ya extends ${constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:N()}}}}}class H extends ${constructor(t,e){super(),this.element=t,this.layout=e}apply(t){this.oldState=t,t.layouts[this.layout.id]||(t.layouts[this.layout.id]={layout:this.layout,elements:[],modificationID:""});const e=t.layouts[this.layout.id].elements;if(e.find(s=>s.id===this.element.id))throw new Error(`Failed to apply new ${this.element.type} element because ID ${this.element.id} already taken`);if(this.element.productOverlay||e.length===0){const s=[...e,this.element];return this.element.layerIndex===void 0&&(this.element.layerIndex=this.assignIndex(this.element,s)),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:s,modificationID:N()}}}}const n=e[e.length-1],r=n.productOverlay?n:null;r&&e.pop();let o;if(this.element.layerIndex!==null&&this.element.layerIndex!==void 0)o=[...e,this.element].sort((s,l)=>s.layerIndex!==void 0&&l.layerIndex!==void 0?s.layerIndex-l.layerIndex:0);else{const s=this.assignIndex(this.element,e);this.element.layerIndex=s!==void 0?s:0,o=[...e,this.element]}return r&&o.push(r),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:o,modificationID:N()}}}}assignIndex(t,e){if(e.length===0)return 0;const a=e.filter(n=>(n.layer||0)===(t.layer||0)).sort((n,r)=>(n.layerIndex||0)-(r.layerIndex||0))[e.length-1]?.layerIndex;return a!==void 0?a+1:0}}class Dt extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;let e=!1;const a=Object.values(t.layouts).map(r=>(r.elements.filter(s=>s.id!==this.id).length!==r.elements.length&&(e=!0),{...r,elements:r.elements.filter(s=>s.id!==this.id),modificationID:N()}));e||console.log(`Failed to delete element ${this.id}`);const n={};return a.forEach(r=>{n[r.layout.id]=r}),{...t,layouts:n}}}class xi extends ${constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class da extends ${constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,textFillImage:this.imageFill},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Fi extends ${constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,fontSize:this.size},n=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ge(a,r),n);return{...t,layouts:{...t.layouts,[n.layout.id]:o}}}}class xa extends ${constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,fontData:this.fontData},n=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ge(a,r),n);return{...t,layouts:{...t.layouts,[n.layout.id]:o}}}}class Di extends ${constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,align:this.align},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Ws extends ${constructor(t,e,a){super(),this.id=t,this.imageData=e,this.offsets=a}apply(t){this.oldState=t;const e=_(this.id,Object.values(t.layouts)),a=e.elements.findIndex(s=>s.id===this.id),n=e.elements[a].pattern,r=[...e.elements];r.splice(a,1,{...e.elements[a],pattern:{...n,src:this.imageData.src,x:this.offsets.x,y:this.offsets.y,width:this.imageData.width,height:this.imageData.height,scaleX:this.offsets.zoom,scaleY:this.offsets.zoom,svg:this.imageData.svg,colors:this.imageData.colors}});const o={...e,elements:r,modificationID:N()};return{...t,layouts:{...t.layouts,[e.layout.id]:o}}}}class Ys extends ${constructor(t,e,a,n,r){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=n,this.thresholdSaturation=r}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Js extends ${constructor(t,e){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,src:this.src},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class ki extends ${constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=_(e.id,Object.values(t.layouts)),n=tt(ge(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:n}}}}class ua extends ${constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Fa extends ${constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=e.colors||{},n=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:n?.spotColor,pmsValue:n?.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:n?.spotColor,pmsValue:this.fill.pmsValue};const r={...e,colors:a},o=_(e.id,Object.values(t.layouts)),s=tt(r,o);return{...t,layouts:{...t.layouts,[o.layout.id]:s}}}}class Ks extends ${constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class _s extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!U(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(o=>o.elements.find(s=>s.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(o=>o.id===this.id);a.elements.push(a.elements.splice(n,1)[0]);const r=[...a.elements];return r.forEach((o,s)=>o.layerIndex=s),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:r,modificationID:N()}}}}}class Xs extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=Object.values(t.layouts).find(s=>s.elements.find(l=>l.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(s=>s.id===this.id);a.elements.splice(n,1),a.elements.unshift(e);const r=[...a.elements],o=r.splice(n,1)[0];return r.splice(n,0,o),r.forEach((s,l)=>s.layerIndex=l),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:r,modificationID:N()}}}}}class Zs extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!U(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),r=n+1,o=[...a.elements],s=o.splice(n,1)[0];return o.splice(r,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:N()}}}}}class tl extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!U(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),r=n-1,o=[...a.elements],s=o.splice(n,1)[0];return o.splice(r,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:N()}}}}}class bn{constructor(t,e,a){this.processRegion=async n=>{const r=this.layouts.find(l=>l.panelId===n.panelId);if(!r)throw new J(n);let o="";if(this.configuration.type===E.ProductOverlay){let l="";if(this.product?.overlayImageUrl&&(l=this.product.overlayImageUrl),o=l,!l)throw new lt(this.configuration,"Couldn't find an asset for product overlay step")}const s=this.evaluateAssetType();if(s===D.Image){const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!l)throw new Error("Undefined raster silent step source");const c={stepName:this.configuration.stepName,id:N(),src:l,type:s,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,rotation:n.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:c.id,region:n},command:new H(c,r)}}else{const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:o,d=await rt(await(async()=>new Promise((A,h)=>{if(!l){h("Undefined vector silent step source");return}et(l,!0).then(g=>{A(g)}).catch(g=>console.error(g))}))()),u={stepName:this.configuration.stepName,id:N(),cachedObjectURL:await se(d.svg),src:l,svg:d.svg,colors:d.colors,type:s,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,rotation:n.rotation,immutable:n.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:u.id,region:n},command:new H(u,r)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new lt(this.configuration,"Missing regions.");if(this.configuration.type===E.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}else return this.configuration.type===E.ProductOverlay?Promise.all(this.configuration.data.regions.map(t=>{if(!this.layouts.find(a=>t.panelId===a.panelId))throw new J(t);return this.processRegion(t)})):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===E.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?D.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),D.Illustration)}}const Mi=async i=>{const t=`${mt.getServicesApiUrl()}/shortener`;try{return(await(await it(t,{method:"POST",body:JSON.stringify({longUrl:i}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new ze("Failed to shorten URL, see console.")}};class Ti{async poll(){try{if(await this.predicate()){this.onSuccess(),this.pollingId>-1&&window.clearInterval(this.pollingId);return}}catch{}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,a,n=3e3,r=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=r,this.poll()}}class el{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{const c=n?.storage?.videoShortUrl,d=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,n){const r=async()=>{const h=(await ke([e]))[0],g=h?.versions?.find(p=>p.name==="mpeg4")?.link;return{asset:h,link:g}},o=await new Promise((h,g)=>{new Ti(async()=>!!(await r()).link,async()=>{const p=await r();if(!p.link||!p.link)throw new Ot(p.asset);h({rel:"mpeg4",href:p.link})},()=>{g("Poller timed out with 40 attempts @ 3 second interval")},3e3,40)});t.forEach(h=>a.getCommandDispatcher()(new Dt(h.id)));const s=n.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(s+n.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([o]))),l.pathname=l.pathname+(l.pathname.slice(-1)==="/"?"":"/");const c=l.toString();if(c.length>=2e3)throw new ze("Cannot create QR code, URL too long.");const d=await Mi(c);if(!n.data||!n.data.regions)throw new lt(n,"Missing regions.");const u=await this.regionElements(n),A=await this.command(d,u,a,n.stepName);return A&&(A.command&&a.getCommandDispatcher()(A.command),A.followup&&await A.followup()),await a.setSelectionsAndElements(n.stepName,[],u,async()=>{a.updateStorage(n.stepName,{videoShortUrl:d,videoUrl:o.href})}),d}async regionElements(t){const e=(a,n)=>({id:N(),region:a,regionIndex:n});return t.data.regions.map(e)}async command(t,e,a,n){const r=a.getLayouts(),s=`data:image/svg+xml;base64,${btoa(await Ln.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,u=r.find(A=>A.panelId===d?.panelId);if(!u&&d)throw new J(d);if(u&&!d)throw new Error("Region not found");if(!u||!d)throw new Error("Neither a region or layout found!");return new H({stepRegion:d,stepRegionIndex:c.regionIndex,stepName:n,id:c.id,src:s,type:D.Image,y:d.top,x:d.left,width:d.width,height:d.height,rotation:0},u)});return{command:new V(l),followup:async()=>{}}}}const Ja=new el;class Ne{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return Ia(e);const a=t.asset;if(!a)throw new yt(t);const n=a.fileLink;if(n)return et(n,!0);throw new Ot(a)}}async init(t,e,a){const n=a?.serializableWorkflow.steps.find(s=>s.stepName===t.stepName);if(n?.storage&&Object.keys(n.storage).length!==0||n?.selectedVariants&&n.selectedVariants.length!==0)return await this.reload(t,e,a),null;t.mandatory&&e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]);let r;const o=e.getWorkflowExperience().getBundle();if(o&&t.globalPropertyAspectConfigurations){const s=o.getGlobalPropertyStateManager(),l=t.globalPropertyAspectConfigurations[0],c=s.getAspectStorage(l.aspectName);c&&c.originalAssetKey&&(r=(await G.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option){const s=await P.getDefaultVariant(t.option,t.overrideDefaultVariantId);if(s)return this.selectVariantCommand(t,s,[],e,void 0,r||t.data.placeholderImageUrl);if(t.option.variants&&t.option.variants?.length!==0)return null}return this.selectVariantCommand(t,void 0,[],e,void 0,r||t.data.placeholderImageUrl)}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));if(!t.option||(t.option.variants||[]).length===0){const c=t.data.regions.map(d=>Ia(d));e.updateStorage(t.stepName,{currentFrameSources:c})}if(n){const c=async()=>{const d=n.storage?.colors,u=n.storage?.framePatternSrc,A=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:A,framePatternSrc:u}),u){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(u,h,!0,d),e.updateMetadata(t.stepName,{image:u}),e.updateStorage(t.stepName,{framePatternSrc:u}),this.validateColorCount(t,e)}if(A?.some(h=>h.zoom)){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");h.updateOffsets(A)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const d=n.selectedVariants[0].id;if(t.option&&d){const u=t.option.variants?.find(A=>A.id===d);u&&await e.setSelectionsAndElements(t.stepName,[u],l,async()=>{const A=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(u,h)));e.updateStorage(t.stepName,{currentFrameSources:A}),await c()})}}else await e.setSelectionsAndElements(t.stepName,[],l,c)}}async availableColors(t,e){return(await P.ensureFullOption(t.data.colorOption))?.variants?.map(n=>({fill:n.color,stroke:n.color,variant:n,pmsValue:n.name}))??[]}selectImage(t,e,a,n=!0){const r=Ne.patternSource(e),o=a.getStepStorage(t.stepName)?.framePatternSrc;if(o&&o===r)return Promise.resolve();a.setEditedStatus(t.stepName,!0);const s=e.fileLink||"";return s.endsWith(".pdf")||s.endsWith(".eps")||s.endsWith(".ai")?new Promise(l=>{a.addPoller(new Ti(async()=>{const d=(await G.getFromServer(e.key||"")).versions?.find(A=>A.name==="svg");return d?(await it(d.link)).status===200:!1},()=>{G.getLocalOrFromServer(e.key||"").then(c=>{this.loadPatternFromAsset(c,t,a,n).then(l)})},()=>{throw new ze("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,n)}async selectVariant(t,e,a,n,r){const o=await this.selectVariantCommand(t,e,a,n,r);o&&(o.command&&n.getCommandDispatcher()(o.command),o.followup&&await o.followup())}getCreateElementCommand(t,e,a,n,r){return new H({id:t,type:D.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/r.frameData.width,scaleY:e.height/r.frameData.height,path:r.frameData.path,dataWidth:r.frameData.width,dataHeight:r.frameData.height,stepRegion:e,stepRegionIndex:a,stepName:r.stepName,disablePlaceholder:r.disablePlaceholder,pattern:r.pattern,immutable:e.immutable},n)}async loadPatternFromString(t,e,a=!0,n=void 0,r){if(t.endsWith("svg")){const o=await Ha(t),s=o.width,l=o.height,c=await et(t);if(r){const A=c.match(/<(image|linearGradient|radialGradient)(\s|>|\/>)/gim);if(A&&A.length>0)throw new Error("Vector files may not include images or gradients when a color limit is specified.")}const d=await rt(c),u={src:t,width:s,height:l,aspect:s/l,svg:d.svg,colors:n??d.colors};gt.set(t,u),e.setPatternData(u,a)}else{const o=await qe(t,!0),s=await ue(o),l={src:t,width:s.width,height:s.height,aspect:s.width/s.height,svg:void 0,colors:void 0};gt.set(t,l),e.setPatternData(l,a)}}async changeColors(t,e,a){const n=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!n||!n.getImageData()?.svg){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const r=await this.calculateColorMetadata(n,t,a);e.updateMetadata(t.stepName,{colors:r.metadataColors}),e.updateStorage(t.stepName,{colors:r.storageColors}),n.setPatternData({...n.getImageData(),colors:r.newColors},!1),this.validateColorCount(t,e)}getUniqueColorCount(t,e){const a=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!a)return 0;const n=a.getImageData()?.colors??{},r=[];for(const o in n){const s=n[o];if(s.pmsValue){const l=s.pmsValue.trim().toLocaleLowerCase();r.includes(l)||r.push(l)}else if(s.browserValue){const l=ii(s.browserValue);r.includes(l)||r.push(l)}}return r.length}async calculateColorMetadata(t,e,a){if(!t.getImageData()?.svg)return{newColors:void 0,metadataColors:void 0,storageColors:void 0};const n={...t.getImageData().colors??{}},r={};Object.entries(n).forEach(([l,c])=>{const d={browserValue:c.browserValue};r[l]=d});for(const[l,c]of a.entries())n[l]={browserValue:c.browserValue,pmsValue:c.pmsValue},r[l]=c;let o=Array.from(Object.values(n)).map(l=>l.browserValue);const s=await P.ensureFullOption(e.data.colorOption);return s&&s.variants?.forEach(l=>{o=o.map(c=>c.toLowerCase()===l.color?.toLowerCase()?l.name:c)}),{newColors:n,metadataColors:o,storageColors:r}}validateColorCount(t,e){const a=t.data.colorPickerEnabled?t.data.maxColors??0:0;e.setStepError(t.stepName,"colors",a>0&&this.getUniqueColorCount(t,e)>a?"workflow.steps.frame.tooManyColors":void 0)}async selectVariantCommand(t,e,a,n,r,o){const s=n.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!s)throw new Error("Frame service unavailable, cannot load pattern!");const l=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(e,h)));r&&r(!0);const c=t.data.initialZoomLevel,d=await Promise.all(t.data.regions.map(async(h,g)=>{const p=await me(l[g]),m=s.getImageData(),f=a.map(I=>new Dt(I.id)),S=m?ja(m,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,w=m?{id:N(),src:m.src,x:S?.x||0,y:S?.y||0,width:m.width,height:m.height,scaleX:S?.zoom||1,scaleY:S?.zoom||1,rotation:0}:void 0,F=N(),v=n.getLayouts().find(I=>I.panelId===h.panelId);if(!v)throw new J(h);return{command:this.getCreateElementCommand(F,h,g,v,{frameData:p,pattern:w,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:F,region:h,regionIndex:g},removeExistingCommands:f}})),u=d.map(h=>h.command),A=d.map(h=>h.removeExistingCommands).flat();return{command:new V([...u,...A]),followup:async()=>{r&&r(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(h=>h.regionEl)],async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:l}),o){const h=n.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(o,h,!0)}})}}}static patternSource(t){const e=t.versions?.find(n=>n.name==="svg");if(e?.link)return e.link;const a=t.fileLink;if(a)return a;throw new Ot(t)}async loadPatternFromAsset(t,e,a,n){const r=Ne.patternSource(t),o=a.markUpdatePending(),s=a.getWorkflowExperience().getStepById(e.stepName)?.frameService;if(!s)throw a.markUpdateCompleted(o),new Error("Frame service unavailable, cannot load pattern!");try{await this.loadPatternFromString(r,s,n,void 0,e.data.colorPickerEnabled&&!!e.data.maxColors&&e.data.maxColors>0)}catch(c){throw a.markUpdateCompleted(o),c}const l=await this.calculateColorMetadata(s,e,new Map(Object.entries(s.getImageData()?.colors??{})));a.updateMetadata(e.stepName,{image:r,colors:l.metadataColors}),a.updateStorage(e.stepName,{framePatternSrc:r,colors:l.storageColors}),a.markUpdateCompleted(o),a.setMandatoryFulfilled(e.stepName,!0),a.setInformationResults(a.getInformationResults().filter(c=>c.stepID===e.stepName)),this.validateColorCount(e,a)}}const At=new Ne;class al{async getIllustrationBody(t){return new Promise(e=>{et(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,n,r){return new H({stepRegion:e,stepRegionIndex:a,stepName:r.stepName,colors:r.svg.colors,id:t,src:r.src,svg:r.svg.svg,cachedObjectURL:r.objectURL,type:D.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},n)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return U(a[0].id,e.getAllLayoutData()).colors}catch{return[]}}async init(t,e,a){const n=await P.getOptionForStep(t);if(!n)throw new lt(t,"No option configured for illustration step.");if(a)return await this.reload(t,e,a);{const r=await P.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return await this.selectVariantCommand(t,r,[],e)}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateMetadata(t.stepName,{colors:n.storage?.colors})})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){const a=await P.ensureFullOption(t.data.colorOption);return a?a?a.variants?.map(n=>({fill:n.color,stroke:n.color,variant:n,pmsValue:n.name})):[]:[]}async changeColorsCommand(t,e,a,n,r){const o={};for(const[d,u]of r.entries())typeof u=="string"?o[d]={browserValue:u,spotColor:void 0,pmsValue:void 0}:o[d]={browserValue:u.browserValue,spotColor:u.spotColor,pmsValue:u.pmsValue};const s=La(t,e,a,o),l=await se(s),c=[];for(const d of n){for(const[u,A]of r.entries())c.push(new Fa(d,u,A));c.push(new Ks(d,s,l))}return new V(c)}async changeColors(t,e,a,n){if(e.length===0)return;const r=U(e[0].id,a.getCommandContext().getAllLayouts().map(A=>A.layoutState)),o={...r.colors},s={};Object.entries(o).forEach(([A,h])=>{const g={browserValue:h.browserValue,pmsValue:h.pmsValue},p=h.spotColor;p&&(g.spotColor={profileName:p.profileName,namedColor:p.namedColor}),s[A]=g});for(const[A,h]of n.entries()){const g=typeof h=="string"?h:h.browserValue,p=typeof h=="string"?void 0:h.pmsValue;A===""?Object.keys(o).forEach(m=>{o[m]={browserValue:g,spotColor:o[m]?.spotColor,pmsValue:p},s[m]={browserValue:g}}):(o[A]={browserValue:g,spotColor:o[A]?.spotColor,pmsValue:p},s[A]={browserValue:g})}let l=Array.from(Object.values(o)).map(A=>A.browserValue);const c=await P.ensureFullOption(t.data.colorOption);c&&c.variants?.forEach(A=>{l=l.map(h=>h.toLowerCase()===A.color?.toLowerCase()?A.name:h)}),a.updateMetadata(t.stepName,{colors:l});const d=new Map;if(Object.entries(o).forEach(([A,h])=>{d.set(A,h)}),!r.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const u=await this.changeColorsCommand(r.svg,r.width,r.height,e.map(A=>A.id),d);a.updateStorage(t.stepName,{colors:s}),a.getCommandDispatcher()(u)}async selectVariant(t,e,a,n,r){n(!0);try{const o=await this.selectVariantCommand(t,e,a,r);o&&(o.command&&r.getCommandDispatcher()(o.command),o.followup&&await o.followup())}finally{n(!1)}}async selectVariantCommand(t,e,a,n){if(!t.data||!t.data.regions)throw new lt(t,"Missing regions.");const r=e.asset;if(!r)throw new yt(e);const o=r.fileLink;if(!o)throw new Ot(r);t.mandatory&&n.setMandatoryFulfilled(t.stepName,!1);const s=a.map(m=>new Dt(m.id)),l=await rt(await this.getIllustrationBody(o)),c=await se(l.svg),d=(m,f)=>{const S=n.getLayouts().find(F=>F.panelId===m.panelId);if(!S)throw new J(m);const w=N();return{regionElement:{id:w,region:m,regionIndex:f},command:this.getCreateElementCommand(w,m,f,S,{stepName:t.stepName,src:o,objectURL:c,svg:l})}},u=t.data.regions.map(d),A=u.map(m=>m.command),h=[...s,...A];let g=Array.from(Object.values(l.colors)).map(m=>m.browserValue);const p=await P.ensureFullOption(t.data.colorOption);return p&&p.variants?.forEach(m=>{g=g.map(f=>f.toLowerCase()===m.color?.toLowerCase()?m.name:f)}),n.updateMetadata(t.stepName,{colors:g}),{command:new V(h),followup:async()=>{const m=u.map(S=>S.regionElement);await n.setSelectionsAndElements(t.stepName,[e],m);const f=r.assetConfiguration?.defaultColorVariants||[];if(f.length!==0){const S={};(r.assetConfiguration?.channelNumbers||[]).forEach(F=>{const b=f.find(v=>v.channelNumber===F.number);b&&(S[`${F.id.replace(/\W/g,"")}`]={browserValue:b?.variant?.color||""})}),await this.changeColors(t,m,n,new Map(Object.entries(S)))}if(t.data.colorPickerEnabled){const S=await this.availableColors(t,n)||[],w=Object.keys(l.colors),F=S.length===1&&w.length===1;if(F){const b=S[0],v=w[0];await this.changeColors(t,m,n,new Map([[v,b.variant.color]]))}!F&&f.length===0&&await this.changeColors(t,m,n,new Map)}}}}}const _t=new al;class nl{async init(t,e,a){const n=t.option;if(!n)throw new ie(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=t.option;if(!l)throw new ie(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(c){const d=l.variants?.find(u=>u.id===c);if(d){const u=d.material,A=s.map(h=>({id:h.id,region:h.stepRegion,regionIndex:h.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{const h=e.getModelContainer();if(h){const g=t.data.targetMaterials.map(p=>h.applyMaterialVariant(p,l.id||"",u||{}));Promise.all(g)}})}}}}async selectVariant(t,e,a,n){const r=await this.selectVariantLambda(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,n){const r=a.getModelContainer();n(!0);const o=e.material;if(!o)throw n(!1),new yt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{r&&t.data.targetMaterials.forEach(s=>{t.option&&r.applyMaterialVariant(s,t.option.id||"",o)})}finally{n(!1)}})}}}}const Ka=new nl;class il{async init(t,e,a){const n=await P.getOptionForStep(t);if(!n)throw new ie(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{const A=e.getModelContainer();if(A&&t.option){const h=d.asset?.fileLink;if(!h)throw new yt(d);await A.applyModelVariant(t.stepName||"",{model:h,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1)}})}}}}async selectVariant(t,e,a,n){const r=await this.selectVariantLambda(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,n){n(!0);const r=e.asset?.fileLink;if(!r)throw new yt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{const o=a.getModelContainer();o&&await o.applyModelVariant(t.stepName,{model:r,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1)}finally{n(!1)}})}}}}const _a=new il;class rl{async init(t,e,a){if(a)await this.reload(t,e,a);else return e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,()=>{});return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,n?.storage?.text!=="")})}async changeText(t,e,a,n){const r=await this.changeTextCommand(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async changeTextCommand(t,e,a,n){const r=a.getRegionElements(t.stepName),o=a.getStepSpecificServices(t.stepName)?.module;if(!o)return console.error("Missing module."),null;const s=a.getWorkflowExperience().getProfanityList(),l=this.validateInput(t,e,s,n);if(l.errorData)return a.setMandatoryFulfilled(t.stepName,!1),l.errorData.blockedProfanity?console.error("Blocked profanity."):l.errorData.hitCharacterLimit?console.error("Too many characters."):l.errorData.unsupportedCharacters&&console.error("Unsupported characters."),null;if(a.setMandatoryFulfilled(t.stepName,e!==""),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;a.updateStorage(t.stepName,{text:e}),a.updateMetadata(t.stepName,{text:e});const c=(d,u,A,h)=>{const g=h||N(),m=a.getLayouts().find(S=>S.panelId===u.panelId);if(!m)return console.error(`Can not find layout for region: ${u.panelId}`),null;const f=[];return h&&f.push(new Dt(g)),f.push(new H({stepRegion:u,stepRegionIndex:A,stepName:t.stepName,colors:{},id:g,svg:d,type:D.Illustration,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable},m)),{id:g,region:u,command:new V(f)}};if(r.length>0){const u=r.map(A=>{if(!A.region)return null;const h=o.svgPrint(e,A.region);return c(h,A.region,A.regionIndex,A.id)}).filter(A=>!!A).filter(A=>!!A).map(A=>A&&A.command);return{command:new V(u),followup:async()=>{}}}else{const d=t.data.regions.map((A,h)=>c(o.svgPrint(e,A),A,h)),u=d.filter(A=>!!A).map(A=>A&&A.command);return{command:new V(u),followup:async()=>{const A=d.filter(h=>h).map(h=>h&&{id:h.id,region:h.region});await a.setSelectionsAndElements(t.stepName,[],A)}}}}validateInput(t,e,a,n){if(t.data&&t.data.maxLength){const o=t.data.maxLength;if(e.length>o)return n("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const r=Ca.split(e.toLowerCase());for(const o of r)for(const s in a){const l=a[s].toLowerCase().replace(/\s/g,"");if(o===l)return n("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return n(""),{input:e,helperData:{}}}}const Xa=new rl;class ol{async init(t,e,a){const n=await P.getOptionForStep(t);if(!n)throw new lt(t,"Missing option for picture step");if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,r,e,()=>{})}return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u)}}}}async selectVariant(t,e,a,n){const r=await this.selectVariantCommand(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantCommand(t,e,a,n){const r=e.asset;if(!r)throw new yt(e);const o=r?.fileLink;if(!o)return console.error("No URL for picture!"),null;n(!0),t.mandatory&&a.setMandatoryFulfilled(t.stepName,!1);const l=a.getRegionElements(t.stepName).map(u=>new Dt(u.id)),c=(u,A)=>{const g=a.getLayouts().find(m=>m.panelId===u.panelId);if(!g)throw new J(u);const p=N();return{regionElement:{id:p,region:u,regionIndex:A},command:new H({stepName:t.stepName,stepRegion:u,stepRegionIndex:A,id:p,src:o,type:D.Image,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable,preserveAspectRatio:"none"},g)}},d=t.data.regions.map(c);return{command:new V([...l,...d.map(u=>u.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(u=>u.regionElement),async()=>{n(!1)})}}}}const Za=new ol;class sl{async init(t,e,a){const n=t.option;if(!n)throw new lt(t,"Missing option for question step");if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return this.selectVariantLambda(t,r.id||"",e)}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),r=await P.getOptionForStep(t);if(n?.selectedVariants){const o=n.selectedVariants[0].id;if(r&&o){const s=r.variants?.find(l=>l.id===o);s&&await e.setSelectionsAndElements(t.stepName,[s],[])}}}async selectVariant(t,e,a){const n=await this.selectVariantLambda(t,e,a);n&&(n.command&&a.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,a){const n=await P.getOptionForStep(t);if(!n)throw new lt(t,"Missing option for question step");const r=n.variants;if(!r)throw new lt(t,"Option for question step is missing variants");const o=r.length>1?r.find(s=>s.id===e):r[0];if(!o)throw new Error(`Failed to find selected variant ${e} in option ${n.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[o],[])}}}}const tn=new sl;class ll{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){const e=await P.getOptionForStep(t);return e?e.variants?.map(a=>({fill:a.color,stroke:a.color,variant:a}))||[]:[]}setCustomColor(t,e,a){const n=a.getLayouts(),o=(a.getRegionElements(e.stepName)||[]).map(s=>{const l=s.region;if(!n.find(d=>d.panelId===l?.panelId))throw new J(l);return new Fa(s.id,this.shapeFillId,t)}).filter(s=>!!s);a.getCommandDispatcher()(new V(o)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const n=await P.getOptionForStep(t);if(!n)throw new ie(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(n,t.overrideDefaultVariantId);return r?this.selectVariantCommand(t,{fill:r.color,stroke:r.color,variant:r},[],e):null}return null}async selectVariant(t,e,a,n){const r=await this.selectVariantCommand(t,e,a,n);r&&(r.command&&n.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateStorage(t.stepName,{colour:n?.storage?.colour||""})})}}}}async selectVariantCommand(t,e,a,n){const r=n.getLayouts(),o=n.getStepStorage(t.stepName)?.colour,s=()=>{if(e.variant?.color==="#custom")return o||"#FFFFFF";if(e.variant?.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(a.length>0){const l=d=>{const u=d.region;if(!r.find(g=>g.panelId===u?.panelId))throw new J(u);const h=s();return new Fa(d.id,this.shapeFillId,h)},c=a.map(l).filter(d=>!!d);return{command:new V(c),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),n.updateStorage(t.stepName,{colour:s()})}}}else{const l=(A,h)=>{const g=r.find(w=>w.panelId===A.panelId);if(!g)throw new J(A);const p=s(),m=`
1404
+ `,n={};n["spiff-fill-shape"]={browserValue:e.color};const r=e.region?.item||await Ht(t,D.Illustration),o=N();return{stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:n,id:o,svg:a,type:D.Illustration,y:r.top,x:r.left,rotation:r.rotation,width:r.width,height:r.height,layer:r.layer||0,layerIndex:r.layerIndex||jt(t,r.layer||0),immutable:r.immutable}}static async getIllustration(t,e){const a=e.region?.item||await Ht(t,D.Illustration,e.src),n=await rt(await Pi(e.src)),r=await se(n.svg),o=N();return{cachedObjectURL:r,stepRegion:e.region?.item,stepRegionIndex:e.region?.index,colors:n.colors,id:o,src:e.src,svg:n.svg,type:D.Illustration,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||jt(t,a.layer||0),immutable:a.immutable}}}class j extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,j.prototype)}}const U=(i,t)=>_(i,t).elements.find(n=>n.id===i),_=(i,t)=>{const e=Object.values(t).find(a=>a.elements.some(n=>n.id===i));if(!e)throw new j;return e},tt=(i,t)=>{const e=[...t.elements.filter(n=>n.id!==i.id),i],a=Ga(e);return{layout:t.layout,elements:a,modificationID:N()}},Pa=async i=>{const t=[...Object.keys(i.layouts)],e=[...new Set(t)];for(let a=0;a<e.length;a++){const n=e[a],r=i.layouts[n];await Promise.all(r.elements.map(async o=>{if(o.type==="illustration"){const s=o;if(s.src&&!s.svg){const l=await et(s.src),c=await rt(l);s.svg=La(c.svg,s.width,s.height,s.colors)}}else if(o.type==="frame"){const s=o;if(s.pattern?.colors&&s.pattern?.src){const l=await et(s.pattern?.src),c=await rt(l);s.pattern.svg=c.svg}}isNaN(o.x)&&(o.x=0),isNaN(o.y)&&(o.y=0),isNaN(o.width)&&(o.width=0),isNaN(o.height)&&(o.height=0),isNaN(o.rotation)&&(o.rotation=0)}))}for(const a in i.layouts){const n=i.layouts[a].elements.filter(o=>o.type===D.Illustration);for(let o=0;o<n.length;++o){const s=n[o];if(s.src&&s.svg)try{s.cachedObjectURL=await se(s.svg)}catch(l){console.log(l)}}const r=i.layouts[a].elements.filter(o=>o.type===D.Textbox);for(let o=0;o<r.length;++o){const s=r[o];s.fontData?.assetUrl&&await Ft(s.fontData.assetUrl)}}};class ${undo(){if(!this.oldState)throw new Error("Cannot undo.");return this.oldState}overrideOldState(t){this.oldState=t}}class En extends ${constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class Gs extends ${constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,x:this.x,y:this.y},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class js extends ${constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,rotation:this.angle},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Hs extends ${constructor(t,e,a){super(),this.id=t,this.width=Math.abs(e),this.height=Math.abs(a)}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;let a={...e,width:this.width,height:this.height};if(e.type==="frame"){const o=a;o.scaleX=o.scaleX*this.width/e.width,o.scaleY=o.scaleY*this.height/e.height}else if(e.type==="textbox"){const o=a,s=(!o.algorithm||o.algorithm===xt.Autosize?o.text:o.input)??"";a=ge(o,s,e)}const n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class V extends ${constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class Ya extends ${constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:N()}}}}}class H extends ${constructor(t,e){super(),this.element=t,this.layout=e}apply(t){this.oldState=t,t.layouts[this.layout.id]||(t.layouts[this.layout.id]={layout:this.layout,elements:[],modificationID:""});const e=t.layouts[this.layout.id].elements;if(e.find(s=>s.id===this.element.id))throw new Error(`Failed to apply new ${this.element.type} element because ID ${this.element.id} already taken`);if(this.element.productOverlay||e.length===0){const s=[...e,this.element];return this.element.layerIndex===void 0&&(this.element.layerIndex=this.assignIndex(this.element,s)),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:s,modificationID:N()}}}}const n=e[e.length-1],r=n.productOverlay?n:null;r&&e.pop();let o;if(this.element.layerIndex!==null&&this.element.layerIndex!==void 0)o=[...e,this.element].sort((s,l)=>s.layerIndex!==void 0&&l.layerIndex!==void 0?s.layerIndex-l.layerIndex:0);else{const s=this.assignIndex(this.element,e);this.element.layerIndex=s!==void 0?s:0,o=[...e,this.element]}return r&&o.push(r),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:o,modificationID:N()}}}}assignIndex(t,e){if(e.length===0)return 0;const a=e.filter(n=>(n.layer||0)===(t.layer||0)).sort((n,r)=>(n.layerIndex||0)-(r.layerIndex||0))[e.length-1]?.layerIndex;return a!==void 0?a+1:0}}class Dt extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;let e=!1;const a=Object.values(t.layouts).map(r=>(r.elements.filter(s=>s.id!==this.id).length!==r.elements.length&&(e=!0),{...r,elements:r.elements.filter(s=>s.id!==this.id),modificationID:N()}));e||console.log(`Failed to delete element ${this.id}`);const n={};return a.forEach(r=>{n[r.layout.id]=r}),{...t,layouts:n}}}class xi extends ${constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class da extends ${constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,textFillImage:this.imageFill},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Fi extends ${constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,fontSize:this.size},n=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ge(a,r),n);return{...t,layouts:{...t.layouts,[n.layout.id]:o}}}}class xa extends ${constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,fontData:this.fontData},n=_(e.id,Object.values(t.layouts)),r=(!e.algorithm||e.algorithm===xt.Autosize?e.text:e.input)??"",o=tt(ge(a,r),n);return{...t,layouts:{...t.layouts,[n.layout.id]:o}}}}class Di extends ${constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,align:this.align},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Ws extends ${constructor(t,e,a){super(),this.id=t,this.imageData=e,this.offsets=a}apply(t){this.oldState=t;const e=_(this.id,Object.values(t.layouts)),a=e.elements.findIndex(s=>s.id===this.id),n=e.elements[a].pattern,r=[...e.elements];r.splice(a,1,{...e.elements[a],pattern:{...n,src:this.imageData.src,x:this.offsets.x,y:this.offsets.y,width:this.imageData.width,height:this.imageData.height,scaleX:this.offsets.zoom,scaleY:this.offsets.zoom,svg:this.imageData.svg,colors:this.imageData.colors}});const o={...e,elements:r,modificationID:N()};return{...t,layouts:{...t.layouts,[e.layout.id]:o}}}}class Ys extends ${constructor(t,e,a,n,r){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=n,this.thresholdSaturation=r}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Js extends ${constructor(t,e){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,src:this.src},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class ki extends ${constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=_(e.id,Object.values(t.layouts)),n=tt(ge(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:n}}}}class ua extends ${constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class Fa extends ${constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=e.colors||{},n=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:n?.spotColor,pmsValue:n?.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:n?.spotColor,pmsValue:this.fill.pmsValue};const r={...e,colors:a},o=_(e.id,Object.values(t.layouts)),s=tt(r,o);return{...t,layouts:{...t.layouts,[o.layout.id]:s}}}}class Ks extends ${constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},n=_(e.id,Object.values(t.layouts)),r=tt(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:r}}}}class _s extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!U(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(o=>o.elements.find(s=>s.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(o=>o.id===this.id);a.elements.push(a.elements.splice(n,1)[0]);const r=[...a.elements];return r.forEach((o,s)=>o.layerIndex=s),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:r,modificationID:N()}}}}}class Xs extends ${constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=U(this.id,Object.values(t.layouts));if(!e.id)throw new j;const a=Object.values(t.layouts).find(s=>s.elements.find(l=>l.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(s=>s.id===this.id);a.elements.splice(n,1),a.elements.unshift(e);const r=[...a.elements],o=r.splice(n,1)[0];return r.splice(n,0,o),r.forEach((s,l)=>s.layerIndex=l),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:r,modificationID:N()}}}}}class Zs extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!U(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),r=n+1,o=[...a.elements],s=o.splice(n,1)[0];return o.splice(r,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:N()}}}}}class tl extends ${constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!U(this.id,Object.values(t.layouts)).id)throw new j;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),r=n-1,o=[...a.elements],s=o.splice(n,1)[0];return o.splice(r,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:N()}}}}}class bn{constructor(t,e,a){this.processRegion=async n=>{const r=this.layouts.find(l=>l.panelId===n.panelId);if(!r)throw new J(n);let o="";if(this.configuration.type===E.ProductOverlay){let l="";if(this.product?.overlayImageUrl&&(l=this.product.overlayImageUrl),o=l,!l)throw new lt(this.configuration,"Couldn't find an asset for product overlay step")}const s=this.evaluateAssetType();if(s===D.Image){const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!l)throw new Error("Undefined raster silent step source");const c={stepName:this.configuration.stepName,id:N(),src:l,type:s,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,rotation:n.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:c.id,region:n},command:new H(c,r)}}else{const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:o,d=await rt(await(async()=>new Promise((A,h)=>{if(!l){h("Undefined vector silent step source");return}et(l,!0).then(g=>{A(g)}).catch(g=>console.error(g))}))()),u={stepName:this.configuration.stepName,id:N(),cachedObjectURL:await se(d.svg),src:l,svg:d.svg,colors:d.colors,type:s,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,rotation:n.rotation,immutable:n.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:u.id,region:n},command:new H(u,r)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new lt(this.configuration,"Missing regions.");if(this.configuration.type===E.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}else return this.configuration.type===E.ProductOverlay?Promise.all(this.configuration.data.regions.map(t=>{if(!this.layouts.find(a=>t.panelId===a.panelId))throw new J(t);return this.processRegion(t)})):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===E.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?D.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),D.Illustration)}}const Mi=async i=>{const t=`${gt.getServicesApiUrl()}/shortener`;try{return(await(await it(t,{method:"POST",body:JSON.stringify({longUrl:i}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new ze("Failed to shorten URL, see console.")}};class Ti{async poll(){try{if(await this.predicate()){this.onSuccess(),this.pollingId>-1&&window.clearInterval(this.pollingId);return}}catch{}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,a,n=3e3,r=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=r,this.poll()}}class el{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{const c=n?.storage?.videoShortUrl,d=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,n){const r=async()=>{const h=(await ke([e]))[0],g=h?.versions?.find(p=>p.name==="mpeg4")?.link;return{asset:h,link:g}},o=await new Promise((h,g)=>{new Ti(async()=>!!(await r()).link,async()=>{const p=await r();if(!p.link||!p.link)throw new Ot(p.asset);h({rel:"mpeg4",href:p.link})},()=>{g("Poller timed out with 40 attempts @ 3 second interval")},3e3,40)});t.forEach(h=>a.getCommandDispatcher()(new Dt(h.id)));const s=n.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(s+n.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([o]))),l.pathname=l.pathname+(l.pathname.slice(-1)==="/"?"":"/");const c=l.toString();if(c.length>=2e3)throw new ze("Cannot create QR code, URL too long.");const d=await Mi(c);if(!n.data||!n.data.regions)throw new lt(n,"Missing regions.");const u=await this.regionElements(n),A=await this.command(d,u,a,n.stepName);return A&&(A.command&&a.getCommandDispatcher()(A.command),A.followup&&await A.followup()),await a.setSelectionsAndElements(n.stepName,[],u,async()=>{a.updateStorage(n.stepName,{videoShortUrl:d,videoUrl:o.href})}),d}async regionElements(t){const e=(a,n)=>({id:N(),region:a,regionIndex:n});return t.data.regions.map(e)}async command(t,e,a,n){const r=a.getLayouts(),s=`data:image/svg+xml;base64,${btoa(await Ln.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,u=r.find(A=>A.panelId===d?.panelId);if(!u&&d)throw new J(d);if(u&&!d)throw new Error("Region not found");if(!u||!d)throw new Error("Neither a region or layout found!");return new H({stepRegion:d,stepRegionIndex:c.regionIndex,stepName:n,id:c.id,src:s,type:D.Image,y:d.top,x:d.left,width:d.width,height:d.height,rotation:0},u)});return{command:new V(l),followup:async()=>{}}}}const Ja=new el;class Ne{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return Ia(e);const a=t.asset;if(!a)throw new yt(t);const n=a.fileLink;if(n)return et(n,!0);throw new Ot(a)}}async init(t,e,a){const n=a?.serializableWorkflow.steps.find(s=>s.stepName===t.stepName);if(n?.storage&&Object.keys(n.storage).length!==0||n?.selectedVariants&&n.selectedVariants.length!==0)return await this.reload(t,e,a),null;t.mandatory&&e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]);let r;const o=e.getWorkflowExperience().getBundle();if(o&&t.globalPropertyAspectConfigurations){const s=o.getGlobalPropertyStateManager(),l=t.globalPropertyAspectConfigurations[0],c=s.getAspectStorage(l.aspectName);c&&c.originalAssetKey&&(r=(await G.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option){const s=await P.getDefaultVariant(t.option,t.overrideDefaultVariantId);if(s)return this.selectVariantCommand(t,s,[],e,void 0,r||t.data.placeholderImageUrl);if(t.option.variants&&t.option.variants?.length!==0)return null}return this.selectVariantCommand(t,void 0,[],e,void 0,r||t.data.placeholderImageUrl)}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));if(!t.option||(t.option.variants||[]).length===0){const c=t.data.regions.map(d=>Ia(d));e.updateStorage(t.stepName,{currentFrameSources:c})}if(n){const c=async()=>{const d=n.storage?.colors,u=n.storage?.framePatternSrc,A=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:A,framePatternSrc:u}),u){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(u,h,!0,d),e.updateMetadata(t.stepName,{image:u}),e.updateStorage(t.stepName,{framePatternSrc:u}),this.validateColorCount(t,e)}if(A?.some(h=>h.zoom)){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");h.updateOffsets(A)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const d=n.selectedVariants[0].id;if(t.option&&d){const u=t.option.variants?.find(A=>A.id===d);u&&await e.setSelectionsAndElements(t.stepName,[u],l,async()=>{const A=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(u,h)));e.updateStorage(t.stepName,{currentFrameSources:A}),await c()})}}else await e.setSelectionsAndElements(t.stepName,[],l,c)}}async availableColors(t,e){return(await P.ensureFullOption(t.data.colorOption))?.variants?.map(n=>({fill:n.color,stroke:n.color,variant:n,pmsValue:n.name}))??[]}selectImage(t,e,a,n=!0){const r=Ne.patternSource(e),o=a.getStepStorage(t.stepName)?.framePatternSrc;if(o&&o===r)return Promise.resolve();a.setEditedStatus(t.stepName,!0);const s=e.fileLink||"";return s.endsWith(".pdf")||s.endsWith(".eps")||s.endsWith(".ai")?new Promise(l=>{a.addPoller(new Ti(async()=>{const d=(await G.getFromServer(e.key||"")).versions?.find(A=>A.name==="svg");return d?(await it(d.link)).status===200:!1},()=>{G.getLocalOrFromServer(e.key||"").then(c=>{this.loadPatternFromAsset(c,t,a,n).then(l)})},()=>{throw new ze("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,n)}async selectVariant(t,e,a,n,r){const o=await this.selectVariantCommand(t,e,a,n,r);o&&(o.command&&n.getCommandDispatcher()(o.command),o.followup&&await o.followup())}getCreateElementCommand(t,e,a,n,r){return new H({id:t,type:D.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/r.frameData.width,scaleY:e.height/r.frameData.height,path:r.frameData.path,dataWidth:r.frameData.width,dataHeight:r.frameData.height,stepRegion:e,stepRegionIndex:a,stepName:r.stepName,disablePlaceholder:r.disablePlaceholder,pattern:r.pattern,immutable:e.immutable},n)}async loadPatternFromString(t,e,a=!0,n=void 0,r){if(t.endsWith("svg")){const o=await Ha(t),s=o.width,l=o.height,c=await et(t);if(r){const A=c.match(/<(image|linearGradient|radialGradient)(\s|>|\/>)/gim);if(A&&A.length>0)throw new Error("Vector files may not include images or gradients when a color limit is specified.")}const d=await rt(c),u={src:t,width:s,height:l,aspect:s/l,svg:d.svg,colors:n??d.colors};ht.set(t,u),e.setPatternData(u,a)}else{const o=await qe(t,!0),s=await ue(o),l={src:t,width:s.width,height:s.height,aspect:s.width/s.height,svg:void 0,colors:void 0};ht.set(t,l),e.setPatternData(l,a)}}async changeColors(t,e,a){const n=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!n||!n.getImageData()?.svg){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const r=await this.calculateColorMetadata(n,t,a);e.updateMetadata(t.stepName,{colors:r.metadataColors}),e.updateStorage(t.stepName,{colors:r.storageColors}),n.setPatternData({...n.getImageData(),colors:r.newColors},!1),this.validateColorCount(t,e)}getUniqueColorCount(t,e){const a=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!a)return 0;const n=a.getImageData()?.colors??{},r=[];for(const o in n){const s=n[o];if(s.pmsValue){const l=s.pmsValue.trim().toLocaleLowerCase();r.includes(l)||r.push(l)}else if(s.browserValue){const l=ii(s.browserValue);r.includes(l)||r.push(l)}}return r.length}async calculateColorMetadata(t,e,a){if(!t.getImageData()?.svg)return{newColors:void 0,metadataColors:void 0,storageColors:void 0};const n={...t.getImageData().colors??{}},r={};Object.entries(n).forEach(([l,c])=>{const d={browserValue:c.browserValue};r[l]=d});for(const[l,c]of a.entries())n[l]={browserValue:c.browserValue,pmsValue:c.pmsValue},r[l]=c;let o=Array.from(Object.values(n)).map(l=>l.browserValue);const s=await P.ensureFullOption(e.data.colorOption);return s&&s.variants?.forEach(l=>{o=o.map(c=>c.toLowerCase()===l.color?.toLowerCase()?l.name:c)}),{newColors:n,metadataColors:o,storageColors:r}}validateColorCount(t,e){const a=t.data.colorPickerEnabled?t.data.maxColors??0:0;e.setStepError(t.stepName,"colors",a>0&&this.getUniqueColorCount(t,e)>a?"workflow.steps.frame.tooManyColors":void 0)}async selectVariantCommand(t,e,a,n,r,o){const s=n.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!s)throw new Error("Frame service unavailable, cannot load pattern!");const l=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(e,h)));r&&r(!0);const c=t.data.initialZoomLevel,d=await Promise.all(t.data.regions.map(async(h,g)=>{const p=await me(l[g]),m=s.getImageData(),f=a.map(I=>new Dt(I.id)),S=m?ja(m,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,w=m?{id:N(),src:m.src,x:S?.x||0,y:S?.y||0,width:m.width,height:m.height,scaleX:S?.zoom||1,scaleY:S?.zoom||1,rotation:0}:void 0,F=N(),v=n.getLayouts().find(I=>I.panelId===h.panelId);if(!v)throw new J(h);return{command:this.getCreateElementCommand(F,h,g,v,{frameData:p,pattern:w,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:F,region:h,regionIndex:g},removeExistingCommands:f}})),u=d.map(h=>h.command),A=d.map(h=>h.removeExistingCommands).flat();return{command:new V([...u,...A]),followup:async()=>{r&&r(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(h=>h.regionEl)],async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:l}),o){const h=n.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(o,h,!0)}})}}}static patternSource(t){const e=t.versions?.find(n=>n.name==="svg");if(e?.link)return e.link;const a=t.fileLink;if(a)return a;throw new Ot(t)}async loadPatternFromAsset(t,e,a,n){const r=Ne.patternSource(t),o=a.markUpdatePending(),s=a.getWorkflowExperience().getStepById(e.stepName)?.frameService;if(!s)throw a.markUpdateCompleted(o),new Error("Frame service unavailable, cannot load pattern!");try{await this.loadPatternFromString(r,s,n,void 0,e.data.colorPickerEnabled&&!!e.data.maxColors&&e.data.maxColors>0)}catch(c){throw a.markUpdateCompleted(o),c}const l=await this.calculateColorMetadata(s,e,new Map(Object.entries(s.getImageData()?.colors??{})));a.updateMetadata(e.stepName,{image:r,colors:l.metadataColors}),a.updateStorage(e.stepName,{framePatternSrc:r,colors:l.storageColors}),a.markUpdateCompleted(o),a.setMandatoryFulfilled(e.stepName,!0),a.setInformationResults(a.getInformationResults().filter(c=>c.stepID===e.stepName)),this.validateColorCount(e,a)}}const pt=new Ne;class al{async getIllustrationBody(t){return new Promise(e=>{et(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,n,r){return new H({stepRegion:e,stepRegionIndex:a,stepName:r.stepName,colors:r.svg.colors,id:t,src:r.src,svg:r.svg.svg,cachedObjectURL:r.objectURL,type:D.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},n)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return U(a[0].id,e.getAllLayoutData()).colors}catch{return[]}}async init(t,e,a){const n=await P.getOptionForStep(t);if(!n)throw new lt(t,"No option configured for illustration step.");if(a)return await this.reload(t,e,a);{const r=await P.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return await this.selectVariantCommand(t,r,[],e)}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateMetadata(t.stepName,{colors:n.storage?.colors})})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){const a=await P.ensureFullOption(t.data.colorOption);return a?a?a.variants?.map(n=>({fill:n.color,stroke:n.color,variant:n,pmsValue:n.name})):[]:[]}async changeColorsCommand(t,e,a,n,r){const o={};for(const[d,u]of r.entries())typeof u=="string"?o[d]={browserValue:u,spotColor:void 0,pmsValue:void 0}:o[d]={browserValue:u.browserValue,spotColor:u.spotColor,pmsValue:u.pmsValue};const s=La(t,e,a,o),l=await se(s),c=[];for(const d of n){for(const[u,A]of r.entries())c.push(new Fa(d,u,A));c.push(new Ks(d,s,l))}return new V(c)}async changeColors(t,e,a,n){if(e.length===0)return;const r=U(e[0].id,a.getCommandContext().getAllLayouts().map(A=>A.layoutState)),o={...r.colors},s={};Object.entries(o).forEach(([A,h])=>{const g={browserValue:h.browserValue,pmsValue:h.pmsValue},p=h.spotColor;p&&(g.spotColor={profileName:p.profileName,namedColor:p.namedColor}),s[A]=g});for(const[A,h]of n.entries()){const g=typeof h=="string"?h:h.browserValue,p=typeof h=="string"?void 0:h.pmsValue;A===""?Object.keys(o).forEach(m=>{o[m]={browserValue:g,spotColor:o[m]?.spotColor,pmsValue:p},s[m]={browserValue:g}}):(o[A]={browserValue:g,spotColor:o[A]?.spotColor,pmsValue:p},s[A]={browserValue:g})}let l=Array.from(Object.values(o)).map(A=>A.browserValue);const c=await P.ensureFullOption(t.data.colorOption);c&&c.variants?.forEach(A=>{l=l.map(h=>h.toLowerCase()===A.color?.toLowerCase()?A.name:h)}),a.updateMetadata(t.stepName,{colors:l});const d=new Map;if(Object.entries(o).forEach(([A,h])=>{d.set(A,h)}),!r.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const u=await this.changeColorsCommand(r.svg,r.width,r.height,e.map(A=>A.id),d);a.updateStorage(t.stepName,{colors:s}),a.getCommandDispatcher()(u)}async selectVariant(t,e,a,n,r){n(!0);try{const o=await this.selectVariantCommand(t,e,a,r);o&&(o.command&&r.getCommandDispatcher()(o.command),o.followup&&await o.followup())}finally{n(!1)}}async selectVariantCommand(t,e,a,n){if(!t.data||!t.data.regions)throw new lt(t,"Missing regions.");const r=e.asset;if(!r)throw new yt(e);const o=r.fileLink;if(!o)throw new Ot(r);t.mandatory&&n.setMandatoryFulfilled(t.stepName,!1);const s=a.map(m=>new Dt(m.id)),l=await rt(await this.getIllustrationBody(o)),c=await se(l.svg),d=(m,f)=>{const S=n.getLayouts().find(F=>F.panelId===m.panelId);if(!S)throw new J(m);const w=N();return{regionElement:{id:w,region:m,regionIndex:f},command:this.getCreateElementCommand(w,m,f,S,{stepName:t.stepName,src:o,objectURL:c,svg:l})}},u=t.data.regions.map(d),A=u.map(m=>m.command),h=[...s,...A];let g=Array.from(Object.values(l.colors)).map(m=>m.browserValue);const p=await P.ensureFullOption(t.data.colorOption);return p&&p.variants?.forEach(m=>{g=g.map(f=>f.toLowerCase()===m.color?.toLowerCase()?m.name:f)}),n.updateMetadata(t.stepName,{colors:g}),{command:new V(h),followup:async()=>{const m=u.map(S=>S.regionElement);await n.setSelectionsAndElements(t.stepName,[e],m);const f=r.assetConfiguration?.defaultColorVariants||[];if(f.length!==0){const S={};(r.assetConfiguration?.channelNumbers||[]).forEach(F=>{const b=f.find(v=>v.channelNumber===F.number);b&&(S[`${F.id.replace(/\W/g,"")}`]={browserValue:b?.variant?.color||""})}),await this.changeColors(t,m,n,new Map(Object.entries(S)))}if(t.data.colorPickerEnabled){const S=await this.availableColors(t,n)||[],w=Object.keys(l.colors),F=S.length===1&&w.length===1;if(F){const b=S[0],v=w[0];await this.changeColors(t,m,n,new Map([[v,b.variant.color]]))}!F&&f.length===0&&await this.changeColors(t,m,n,new Map)}}}}}const _t=new al;class nl{async init(t,e,a){const n=t.option;if(!n)throw new ie(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=t.option;if(!l)throw new ie(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(c){const d=l.variants?.find(u=>u.id===c);if(d){const u=d.material,A=s.map(h=>({id:h.id,region:h.stepRegion,regionIndex:h.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{const h=e.getModelContainer();if(h){const g=t.data.targetMaterials.map(p=>h.applyMaterialVariant(p,l.id||"",u||{}));Promise.all(g)}})}}}}async selectVariant(t,e,a,n){const r=await this.selectVariantLambda(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,n){const r=a.getModelContainer();n(!0);const o=e.material;if(!o)throw n(!1),new yt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{r&&t.data.targetMaterials.forEach(s=>{t.option&&r.applyMaterialVariant(s,t.option.id||"",o)})}finally{n(!1)}})}}}}const Ka=new nl;class il{async init(t,e,a){const n=await P.getOptionForStep(t);if(!n)throw new ie(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return await this.selectVariantLambda(t,r,e,()=>{})}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{const A=e.getModelContainer();if(A&&t.option){const h=d.asset?.fileLink;if(!h)throw new yt(d);await A.applyModelVariant(t.stepName||"",{model:h,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1)}})}}}}async selectVariant(t,e,a,n){const r=await this.selectVariantLambda(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a,n){n(!0);const r=e.asset?.fileLink;if(!r)throw new yt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{const o=a.getModelContainer();o&&await o.applyModelVariant(t.stepName,{model:r,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1)}finally{n(!1)}})}}}}const _a=new il;class rl{async init(t,e,a){if(a)await this.reload(t,e,a);else return e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,()=>{});return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion,regionIndex:c.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,n?.storage?.text!=="")})}async changeText(t,e,a,n){const r=await this.changeTextCommand(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async changeTextCommand(t,e,a,n){const r=a.getRegionElements(t.stepName),o=a.getStepSpecificServices(t.stepName)?.module;if(!o)return console.error("Missing module."),null;const s=a.getWorkflowExperience().getProfanityList(),l=this.validateInput(t,e,s,n);if(l.errorData)return a.setMandatoryFulfilled(t.stepName,!1),l.errorData.blockedProfanity?console.error("Blocked profanity."):l.errorData.hitCharacterLimit?console.error("Too many characters."):l.errorData.unsupportedCharacters&&console.error("Unsupported characters."),null;if(a.setMandatoryFulfilled(t.stepName,e!==""),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;a.updateStorage(t.stepName,{text:e}),a.updateMetadata(t.stepName,{text:e});const c=(d,u,A,h)=>{const g=h||N(),m=a.getLayouts().find(S=>S.panelId===u.panelId);if(!m)return console.error(`Can not find layout for region: ${u.panelId}`),null;const f=[];return h&&f.push(new Dt(g)),f.push(new H({stepRegion:u,stepRegionIndex:A,stepName:t.stepName,colors:{},id:g,svg:d,type:D.Illustration,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable},m)),{id:g,region:u,command:new V(f)}};if(r.length>0){const u=r.map(A=>{if(!A.region)return null;const h=o.svgPrint(e,A.region);return c(h,A.region,A.regionIndex,A.id)}).filter(A=>!!A).filter(A=>!!A).map(A=>A&&A.command);return{command:new V(u),followup:async()=>{}}}else{const d=t.data.regions.map((A,h)=>c(o.svgPrint(e,A),A,h)),u=d.filter(A=>!!A).map(A=>A&&A.command);return{command:new V(u),followup:async()=>{const A=d.filter(h=>h).map(h=>h&&{id:h.id,region:h.region});await a.setSelectionsAndElements(t.stepName,[],A)}}}}validateInput(t,e,a,n){if(t.data&&t.data.maxLength){const o=t.data.maxLength;if(e.length>o)return n("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const r=Ca.split(e.toLowerCase());for(const o of r)for(const s in a){const l=a[s].toLowerCase().replace(/\s/g,"");if(o===l)return n("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return n(""),{input:e,helperData:{}}}}const Xa=new rl;class ol{async init(t,e,a){const n=await P.getOptionForStep(t);if(!n)throw new lt(t,"Missing option for picture step");if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,r,e,()=>{})}return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u)}}}}async selectVariant(t,e,a,n){const r=await this.selectVariantCommand(t,e,a,n);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantCommand(t,e,a,n){const r=e.asset;if(!r)throw new yt(e);const o=r?.fileLink;if(!o)return console.error("No URL for picture!"),null;n(!0),t.mandatory&&a.setMandatoryFulfilled(t.stepName,!1);const l=a.getRegionElements(t.stepName).map(u=>new Dt(u.id)),c=(u,A)=>{const g=a.getLayouts().find(m=>m.panelId===u.panelId);if(!g)throw new J(u);const p=N();return{regionElement:{id:p,region:u,regionIndex:A},command:new H({stepName:t.stepName,stepRegion:u,stepRegionIndex:A,id:p,src:o,type:D.Image,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable,preserveAspectRatio:"none"},g)}},d=t.data.regions.map(c);return{command:new V([...l,...d.map(u=>u.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(u=>u.regionElement),async()=>{n(!1)})}}}}const Za=new ol;class sl{async init(t,e,a){const n=t.option;if(!n)throw new lt(t,"Missing option for question step");if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(n,t.overrideDefaultVariantId);if(r)return this.selectVariantLambda(t,r.id||"",e)}return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),r=await P.getOptionForStep(t);if(n?.selectedVariants){const o=n.selectedVariants[0].id;if(r&&o){const s=r.variants?.find(l=>l.id===o);s&&await e.setSelectionsAndElements(t.stepName,[s],[])}}}async selectVariant(t,e,a){const n=await this.selectVariantLambda(t,e,a);n&&(n.command&&a.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,a){const n=await P.getOptionForStep(t);if(!n)throw new lt(t,"Missing option for question step");const r=n.variants;if(!r)throw new lt(t,"Option for question step is missing variants");const o=r.length>1?r.find(s=>s.id===e):r[0];if(!o)throw new Error(`Failed to find selected variant ${e} in option ${n.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[o],[])}}}}const tn=new sl;class ll{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){const e=await P.getOptionForStep(t);return e?e.variants?.map(a=>({fill:a.color,stroke:a.color,variant:a}))||[]:[]}setCustomColor(t,e,a){const n=a.getLayouts(),o=(a.getRegionElements(e.stepName)||[]).map(s=>{const l=s.region;if(!n.find(d=>d.panelId===l?.panelId))throw new J(l);return new Fa(s.id,this.shapeFillId,t)}).filter(s=>!!s);a.getCommandDispatcher()(new V(o)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const n=await P.getOptionForStep(t);if(!n)throw new ie(t);if(a)await this.reload(t,e,a);else{const r=await P.getDefaultVariant(n,t.overrideDefaultVariantId);return r?this.selectVariantCommand(t,{fill:r.color,stroke:r.color,variant:r},[],e):null}return null}async selectVariant(t,e,a,n){const r=await this.selectVariantCommand(t,e,a,n);r&&(r.command&&n.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=await P.getOptionForStep(t);if(n?.selectedVariants){const c=n.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=s.map(A=>({id:A.id,region:A.stepRegion,regionIndex:A.stepRegionIndex}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateStorage(t.stepName,{colour:n?.storage?.colour||""})})}}}}async selectVariantCommand(t,e,a,n){const r=n.getLayouts(),o=n.getStepStorage(t.stepName)?.colour,s=()=>{if(e.variant?.color==="#custom")return o||"#FFFFFF";if(e.variant?.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(a.length>0){const l=d=>{const u=d.region;if(!r.find(g=>g.panelId===u?.panelId))throw new J(u);const h=s();return new Fa(d.id,this.shapeFillId,h)},c=a.map(l).filter(d=>!!d);return{command:new V(c),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),n.updateStorage(t.stepName,{colour:s()})}}}else{const l=(A,h)=>{const g=r.find(w=>w.panelId===A.panelId);if(!g)throw new J(A);const p=s(),m=`
1405
1405
  <svg
1406
1406
  xmlns="http://www.w3.org/2000/svg"
1407
1407
  xmlnsXlink="http://www.w3.org/1999/xlink"
@@ -2135,7 +2135,7 @@
2135
2135
  }
2136
2136
  }
2137
2137
  }
2138
- `,pc=(i,t)=>t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).sort().reduce((e,a)=>(e[a]=t[a],e),{}):t,fc=i=>{for(const t of Object.values(i.layouts).map(e=>e.elements).flat())t.type==="illustration"&&(delete t.cachedObjectURL,t.src&&delete t.svg),t.type==="frame"&&delete t.pattern?.svg;return $i(i,"__typename"),i},$i=(i,t)=>{if(!(typeof i!="object"||i===null))for(const e in i)e===t?delete i[e]:$i(i[e],t)};var pe=(i=>(i.Error="Error",i.Warning="Warning",i.Info="Info",i))(pe||{});const Cc=1e3;class Pn extends za{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},Cc)})}}const wc=i=>i.sort((t,e)=>t.index-e.index).map(t=>({id:N(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),yc=(i,t)=>{const e=i.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):wc(t.panels)},te=class te{constructor(t,e,a,n,r,o=!1,s,l=!1,c=!1,d=!1){this.workflowStatePromiseQueue=new qa(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async A=>{this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.reloadedState?this.layouts=Object.values(this.reloadedState.layouts||{}).map(g=>g.layout):A?this.layouts=yc(this.experience.getTransaction(),A):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new Dl(this.layouts),this.renderableContextService.setWorkflowManager(this),A.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(A),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(g=>{throw this.initialized=!1,new Error(g)}),this.initializationPromise.finally(()=>this.commandContext.registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()})),h&&await this.injectIntoPreviewService(h,!0)},this.renderLayouts=()=>{if(!this.previewService)return;const A=this.getCommandContext().getAllLayouts(),h=this.getLayoutPreviewService()?.getAll();if(h)for(const[,g]of h)g.render(A)},this.experience=t,this.client=e,this.updateTransaction=a,this.graphQlClient=n,this.reloadedState=r,this.readOnly=o,this.singleVariantsRenderable=c,this.commandContext=new bi,this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.modelContainer=s,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.isReloadedTransaction=l,d&&(this.workflowStatePromiseQueue.enabled=!1);const u=this.experience.getWorkflow();u&&this.setWorkflow(u)}getTemplatingContext(){const t=this.experience.getTransaction().recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const n=a.uniqueIdentifier??a.title??"";a.type===Zt.FirstName?e[n]=t?.firstName:a.type===Zt.LastName?e[n]=t?.lastName:a.type===Zt.Custom&&(a.customFieldIndex===1?e[n]=t?.customField1:a.customFieldIndex===2?e[n]=t?.customField2:a.customFieldIndex===3?e[n]=t?.customField3:a.customFieldIndex===4?e[n]=t?.customField4:a.customFieldIndex===5&&(e[n]=t?.customField5),a.option&&(e[n]=a.option.variants?.find(r=>r.id===e[n])?.name))}),e}async updateRecipient(t,e,a,n,r,o,s,l,c,d,u,A,h,g,p,m,f,S){const w=this.experience.getTransaction();if(w.recipient?.id)this.experience.getTransaction().recipient={id:w.recipient.id,firstName:t??w.recipient.firstName,lastName:e??w.recipient.lastName,address:a??w.recipient.address,suburb:n??w.recipient.suburb,state:r??w.recipient.state,email:o??w.recipient.email,postalCode:s??w.recipient.postalCode,country:l??w.recipient.country,mobile:c??w.recipient.mobile,company:d??w.recipient.company,apartment:u??w.recipient.apartment,customField1:A??w.recipient.customField1,customField2:h??w.recipient.customField2,customField3:g??w.recipient.customField3,customField4:p??w.recipient.customField4,customField5:m??w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId},this.experience.callEvent($e.RecipientChanged),await this.graphQlClient().mutate({mutation:Ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:w.recipient.id,firstName:t||w.recipient.firstName,lastName:e||w.recipient.lastName,address:a||w.recipient.address,suburb:n||w.recipient.suburb,state:r||w.recipient.state,email:o||w.recipient.email,postalCode:s||w.recipient.postalCode,country:l||w.recipient.country,mobile:c||w.recipient.mobile,company:d||w.recipient.company,apartment:u||w.recipient.apartment,customField1:A||w.recipient.customField1,customField2:h||w.recipient.customField2,customField3:g||w.recipient.customField3,customField4:p||w.recipient.customField4,customField5:m||w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId,prevalidated:S}});else{const F=await this.graphQlClient().mutate({mutation:uc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:n,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f}});w.recipient={id:F?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:n,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f},this.experience.callEvent($e.RecipientChanged),await this.graphQlClient().mutate({mutation:hc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,recipientId:F.data?.recipientCreate?.id},context:{transactionOwnerId:this.experience.getTransaction().transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(F=>F(this.experience.getTransaction().recipient))}async fetchConversionConfiguration(){const t=this.experience.getTransaction().recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=te.configurationPromiseMap.get(t.conversionConfigurationId);if(e)this.recipientConversionConfiguration=await e;else{const n=(async()=>(await this.graphQlClient().query({query:Ho,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}})).data.conversionConfiguration)();te.configurationPromiseMap.set(t.conversionConfigurationId,n),this.recipientConversionConfiguration=await n}}}async initializeDefaultWorkflowState(t){const e=()=>{const d=t.finalizeStepConfig;if(!d)return;const u=d.lookAtAnimation,A=d.modelAnimation;u&&this.previewService?.executeCameraAnimation(u),A&&this.modelContainer?.executeAnimation(A)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(d=>{this.storage[d.stepName]=d.storage||{}});const a=await this.getInitialOptionIds(this.reloadedState?.serializableWorkflow?.steps.reduce((d,u)=>(u.selectedVariants?.length&&(d[u.stepName]={selectedVariants:u.selectedVariants.map(A=>({id:A.id}))}),d),{})),n=P.getOptions(Array.from(a)),r=this.fetchConversionConfiguration();await Promise.all([n,r]),this.allScenes=wn(t);const s=(await dt(this.allScenes,this.stepSelections)).map(d=>d.silentSteps).flat(),{stepElements:l,commands:c}=await this.stepElementsForIntroducedSilentSteps(s,!!this.reloadedState);this.commandContext.apply(new V(c),!0),this.stepElements={...this.stepElements,...l},await this.ensureStepsAreLoaded(),this.isReloadedTransaction||this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}async getInitialOptionIds(t){const e=new Set,a=this.experience.getWorkflow();if(!a)return e;const n=wn(a),r={...t};let o=-1;for(;;){const c=(await dt(n,r)).flatMap(d=>d.renderableSteps);if(c.length===o)break;o=c.length;for(const d of c){if(r[d.stepName])continue;const u=d.option?.defaultVariant?.id;u&&(r[d.stepName]={selectedVariants:[{id:u}]})}}return(await dt(n,r)).flatMap(l=>l.renderableSteps).forEach(l=>{l.option?.id&&!l.option?.variants&&e.add(l.option.id)}),e}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addPoller(t){this.pollers.push(t)}addValidationCallback(t){this.validationCallbacks.push(t),t(this.validationErrors)}addRecipientCallback(t){this.recipientCallbacks.push(t),t(this.experience.getTransaction().recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(t=>t.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.experience.getWorkflow()?.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!0}),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter(e=>e!==t)}markUpdatePending(){const t=N();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}async getMandatoryUnfulfilledSteps(){return(await dt(this.allScenes,this.stepSelections)).flatMap(r=>r.renderableSteps).filter(r=>r.mandatory).filter(r=>!this.mandatorySteps[r.stepName]).map(r=>r.stepName)}setStepError(t,e,a){let n=!1;if(!this.validationErrors.steps.has(t)&&a)n=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const r=this.validationErrors.steps.get(t);a&&a!==r.get(e)?(n=!0,r.set(e,a)):a||(n=!0,r.delete(e),r.size===0&&this.validationErrors.steps.delete(t))}n&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");this.previewService=t;const a=this.experience.getProduct();if(!a?.modelUrl||!this.previewService)return;const n=t.loadModel({model:a.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(n),(await dt(this.allScenes,this.stepSelections)).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===E.Model||s.type===E.Material).forEach(s=>{if(!s.option?.id){console.error(`Failed to read option id from step: ${s.stepName}`);return}const l=this.stepSelections[s.stepName]?.selectedVariants||[];if(l.length===0)return;const c=l[0];if(s.type===E.Model){if(!this.modelContainer)throw new R("We should always have a model container when injecting a preview!");const d=c.asset?.fileLink;if(!d){console.error(`Failed to read model url from variant: ${c.id} for step: ${s.stepName}`);return}const u=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:d,contextService:this.getLayoutPreviewService()},u.replaceProductModel||!1)}else{const d=c.material;if(!d){console.error(`Failed to read material from variant: ${c.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new R("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,s.option.id,d)})}}),await n.getInitializationPromise(),this.renderLayouts()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}updateStorage(t,e){const a={...this.storage,[t]:{...this.storage[t],...e}};if(!ae(a,this.storage)){this.storage=a;const n=new En(this.constructSerializableWorkflow());this.commandContext.apply(n,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const n={stepName:a.stepName};n.storage=this.storage[a.stepName],n.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(r=>({id:r.id,priceModifier:r.priceModifier})),t.push(n)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new Pn(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new Pn(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new R("Attempted to serialize state before it was initialized.");const e=Pt(t.transaction),a=fc(e);return JSON.stringify(a,pc,void 0)}async getStateHash(){const t=this.getCommandContext().getState(),a=Object.values(t?.transaction.layouts||{}).map(o=>o.modificationID??"").sort().join(""),r=new TextEncoder().encode(a);if(typeof window<"u"&&window.crypto&&window.crypto.subtle&&window.crypto.subtle.digest){const o=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(c=>c.toString(16).padStart(2,"0")).join("")}try{return(await import("crypto")).createHash("sha256").update(a,"utf8").digest("hex")}catch{throw new Error("Unable to compute SHA-256 hash: no suitable crypto implementation available.")}}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,n)=>Object.keys(a).reduce((r,o)=>{const s=[...a[o]||[]];return n.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),r[o]=s,r},{});this.stepElements=e(this.stepElements,t)}async getInvalidCanvasRegions(){let t=[];for(const e of this.experience.getWorkflow()?.steps||[])if(!await Ct(e,this.stepSelections)&&this.stepElements[e.stepName])for(const a of this.stepElements[e.stepName])t.push(a);return t}async getInvalidModelVariants(){let t=[];for(const e of this.experience.getWorkflow()?.steps||[])e.type===E.Model&&!await Ct(e,this.stepSelections)&&t.push(e.stepName);return t}async stepElementsForIntroducedSilentSteps(t,e){const a=this.experience.getProduct();if(!a)return Promise.resolve({stepElements:{},commands:[]});const n=async(c,d,u)=>{if(c.type===E.SilentIllustration){const A=await new bn(c,d).trigger();return{step:c,results:A}}else if(c.type===E.ProductOverlay){const A=await new bn(c,d,u).trigger();return{step:c,results:A}}return Promise.reject("Unknown silent step. This is a bug")},r=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of r)this.markStepsAsInitialised([c.stepName]),e||s.push(n(c,this.layouts,a));const l=await Promise.all(s);for(const c of l)o.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),o.commands=[...o.commands,...c.results.map(d=>d.command)];return o}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=t}async updateTransactionStakeholders(){const t=await y.getShadowGraphqlClient().query({query:Xo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=t.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:cc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async rejectTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,n){const r=this.experience.getWorkflow();if(!r)throw new Error("Attempted to set selections when no workflow is set!");const o=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((v,I)=>v+I.selectedVariants.map(M=>M.priceModifier||0).reduce((M,O)=>M+O,0),0);for(const v of r.steps)await Ct(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1,delete this.stepMetadata[v.stepName],delete this.stepSelections[v.stepName],delete this.storage[v.stepName]);const s=this.allScenes,l=await dt(s,o),c=await dt(s,this.stepSelections),d=l.map(v=>v.silentSteps).flat(),A=c.map(v=>v.silentSteps).flat().filter(v=>!d.some(I=>I.stepName===v.stepName));for(const v of d)await Ct(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1);const h=await this.getInvalidCanvasRegions(),{stepElements:g,commands:p}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...g,[t]:a},this.removeElements(h);const m=r.steps.find(v=>v.stepName===t);m?.type===E.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(I=>I.id));const f=h.map(v=>new Dt(v.id)),S=new En(this.constructSerializableWorkflow()),w=[...p,...f,S];w.length>0&&this.commandContext.apply(new V(w),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const F=await this.getInvalidModelVariants(),b=this.modelContainer;if(b){const v=F.map(I=>b.applyModelVariant(I,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(v)}await this.onSelectionChange(),m?.type!==E.Frame&&m?.type!==E.Text&&this.setMandatoryFulfilled(t,!0),n&&await n()}async ensureStepsAreLoaded(){const e=(await dt(this.allScenes,this.stepSelections)).map(l=>l.renderableSteps),a=[],n=e.flat();for(const l of n)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case E.DigitalContent:a.push(Ja.init(l,this,this.reloadedState));break;case E.Frame:a.push(At.init(l,this,this.reloadedState));break;case E.Illustration:a.push(_t.init(l,this,this.reloadedState));break;case E.Material:a.push(Ka.init(l,this,this.reloadedState));break;case E.Model:a.push(_a.init(l,this,this.reloadedState));break;case E.Module:this.stepSpecificServices[l.stepName]={module:await Qi(l.data.module)},a.push(Xa.init(l,this,this.reloadedState));break;case E.Picture:a.push(Za.init(l,this,this.reloadedState));break;case E.Question:a.push(tn.init(l,this,this.reloadedState));break;case E.Shape:a.push(Tt.init(l,this,this.reloadedState));break;case E.Text:a.push(W.init(l,this,this.reloadedState));break}const r=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=r.flatMap(l=>l?.command?[l.command]:[]),s=r.flatMap(l=>l?.followup?[l.followup]:[]);o&&o.length>0&&this.commandContext.apply(new V(o),!0);for(const l of s)await l();s.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(t=>t(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(t=>t(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(t=>t(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(t=>t(this.informationResults))}onInitChange(){this.initCallbacks.forEach(t=>t(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(t=>{t(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(t=>t(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(t=>{t(this.stepMetadata)})}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach(e=>e(this.storage[t]))}onStorageChange(){this.storageCallbacks.forEach(t=>t(this.storage))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return hs(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}};te.configurationPromiseMap=new Map;let Da=te;class nt{constructor(t){this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.asset?.versions?.find(t=>t.name==="cdn")?.link}getAssetResource(){return this.variantData.asset}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find(a=>a.name==="thumbnail")?.link,e=this.variantData.thumbnail?.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}getCategory(){return this.variantData.category}}const ee=class ee{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){ee.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,t)}getUpdateState(){return!!ee.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new nt(a)}async getAvailableVariants(){return(await this.getAllVariants()).filter(e=>e.isEnabled())||[]}async getAllVariants(){if(!this.step.option?.id)return[];if(this.step.option.variants)return(this.step.option.variants||[]).map(e=>new nt(e))||[];const t=await P.getOption(this.step.option?.id);if(!t)throw new Error("Option not found, cannot fetch variants.");return(t.variants||[]).map(e=>new nt(e))||[]}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.tags}hasTag(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){const a=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){return this.step.globalPropertyAspectConfigurations?.filter(e=>e.globalPropertyConfigurationId===t&&e.aspectName).map(e=>e.aspectName)??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),n=this.step.data.modelAnimation,r=this.step.data.lookAtAnimation;e?r&&e.executeCameraAnimation(r):console.warn("No preview service available, cannot execute camera animations."),a?n&&a.executeAnimation(n,t):console.warn("No model container available, cannot execute model animations.")}};ee.updateState=new Map;let Z=ee;class Vi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return _t.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=U(t[0].id,this.manager.getAllLayoutData()).colors,r=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=r?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=r.channelNumbers.find(d=>d.number===l.channelNumber);if(c){const d=c.id.replace(/\W/g,"");s[l.channelNumber]={browserValue:a[d]?.browserValue||""}}}),s}try{return a}catch(s){console.error(s)}}setColor(t,e,a){const n=new Map,o=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(o?.defaultColorVariants||[]).length!==0?o.channelNumbers.forEach(l=>{if(l.number.toString()===t){const c=l.id.replace(/\W/g,"");a?n.set(c,{browserValue:e,pmsValue:a}):n.set(c,e)}}):a?n.set(t,{browserValue:e,pmsValue:a}):n.set(t,e),_t.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,n)}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?_t.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Ui extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ka.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Li extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return _a.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class zi extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Za.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class qi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await tn.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class Gi extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return Tt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Tt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Tt.availableColours(this.step)}setCustomColor(t){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),Tt.setCustomColor(t,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const t=this.manager.getStepStorage(this.step.stepName)?.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class ji extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){await W.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:e,messageType:pe.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}async getAvailableFillColors(){return this.step.data.colorPickerEnabled?W.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return W.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return W.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);W.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,n=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1}),this.setText(n)}setText(t){const e={input:t,helperData:{}},a=W.findLayoutElements(this.manager,this.step),n=W.filterUnsupportedCharacters(t,a[0]?.fontData),r=Nt(n,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&r>this.step.data.maxLength;o||(e.input=n);const s=a.length<=0,l=s?{inputText:n,text:n}:{inputText:n};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=W.getProcessedInput(n,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:u,errorData:A,helperData:h}=W.updateInputText(n,a,this.step,this.manager);u&&this.manager.getCommandDispatcher()(u),e.helperData=h,e.errorData=A,!o&&!A&&this.manager.updateMetadata(this.step.stepName,{text:d})}return e}getText(){const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&e?.defaultCleared!==void 0&&!e?.defaultCleared?t:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=W.findLayoutElements(this.manager,this.step);return W.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Nt(this.getText(),this.manager);return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}async getAvailableStrokeColors(){return this.step.data.strokeEnabled?W.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeStrokeColor(this.step,t,e,this.manager)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Hi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Wi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return Ja.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Yi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Nt(this.getText(),this.manager);return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(t){Xa.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:pe.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class be{static get(t,e){switch(e.type){case E.DigitalContent:return new Wi(t,e,t.getStepTags(e.stepName));case E.Information:return new Hi(t,e,t.getStepTags(e.stepName));case E.Question:return new qi(t,e,t.getStepTags(e.stepName));case E.Text:return new ji(t,e,t.getStepTags(e.stepName));case E.Illustration:return new Vi(t,e,t.getStepTags(e.stepName));case E.Picture:return new zi(t,e,t.getStepTags(e.stepName));case E.Shape:return new Gi(t,e,t.getStepTags(e.stepName));case E.Material:return new Ui(t,e,t.getStepTags(e.stepName));case E.Model:return new Li(t,e,t.getStepTags(e.stepName));case E.Frame:return new gr(t,e,t.getStepTags(e.stepName));case E.Module:return new Yi(t,e,t.getStepTags(e.stepName));default:throw new R(`Step type ${e.type} not yet supported in Core SDK`)}}}const Sc=C.gql`
2138
+ `,pc=(i,t)=>t&&typeof t=="object"&&!Array.isArray(t)?Object.keys(t).sort().reduce((e,a)=>(e[a]=t[a],e),{}):t,fc=i=>{for(const t of Object.values(i.layouts).map(e=>e.elements).flat())t.type==="illustration"&&(delete t.cachedObjectURL,t.src&&delete t.svg),t.type==="frame"&&delete t.pattern?.svg;return $i(i,"__typename"),i},$i=(i,t)=>{if(!(typeof i!="object"||i===null))for(const e in i)e===t?delete i[e]:$i(i[e],t)};var pe=(i=>(i.Error="Error",i.Warning="Warning",i.Info="Info",i))(pe||{});const Cc=1e3;class Pn extends za{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},Cc)})}}const wc=i=>i.sort((t,e)=>t.index-e.index).map(t=>({id:N(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),yc=(i,t)=>{const e=i.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):wc(t.panels)},te=class te{constructor(t,e,a,n,r,o=!1,s,l=!1,c=!1,d=!1){this.workflowStatePromiseQueue=new qa(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async A=>{this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.reloadedState?this.layouts=Object.values(this.reloadedState.layouts||{}).map(g=>g.layout):A?this.layouts=yc(this.experience.getTransaction(),A):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new Dl(this.layouts),this.renderableContextService.setWorkflowManager(this),A.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(A),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(g=>{throw this.initialized=!1,new Error(g)}),this.initializationPromise.finally(()=>this.commandContext.registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()})),h&&await this.injectIntoPreviewService(h,!0)},this.renderLayouts=()=>{if(!this.previewService)return;const A=this.getCommandContext().getAllLayouts(),h=this.getLayoutPreviewService()?.getAll();if(h)for(const[,g]of h)g.render(A)},this.experience=t,this.client=e,this.updateTransaction=a,this.graphQlClient=n,this.reloadedState=r,this.readOnly=o,this.singleVariantsRenderable=c,this.commandContext=new bi,this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.modelContainer=s,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.isReloadedTransaction=l,d&&(this.workflowStatePromiseQueue.enabled=!1);const u=this.experience.getWorkflow();u&&this.setWorkflow(u)}getTemplatingContext(){const t=this.experience.getTransaction().recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const n=a.uniqueIdentifier??a.title??"";a.type===Zt.FirstName?e[n]=t?.firstName:a.type===Zt.LastName?e[n]=t?.lastName:a.type===Zt.Custom&&(a.customFieldIndex===1?e[n]=t?.customField1:a.customFieldIndex===2?e[n]=t?.customField2:a.customFieldIndex===3?e[n]=t?.customField3:a.customFieldIndex===4?e[n]=t?.customField4:a.customFieldIndex===5&&(e[n]=t?.customField5),a.option&&(e[n]=a.option.variants?.find(r=>r.id===e[n])?.name))}),e}async updateRecipient(t,e,a,n,r,o,s,l,c,d,u,A,h,g,p,m,f,S){const w=this.experience.getTransaction();if(w.recipient?.id)this.experience.getTransaction().recipient={id:w.recipient.id,firstName:t??w.recipient.firstName,lastName:e??w.recipient.lastName,address:a??w.recipient.address,suburb:n??w.recipient.suburb,state:r??w.recipient.state,email:o??w.recipient.email,postalCode:s??w.recipient.postalCode,country:l??w.recipient.country,mobile:c??w.recipient.mobile,company:d??w.recipient.company,apartment:u??w.recipient.apartment,customField1:A??w.recipient.customField1,customField2:h??w.recipient.customField2,customField3:g??w.recipient.customField3,customField4:p??w.recipient.customField4,customField5:m??w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId},this.experience.callEvent($e.RecipientChanged),await this.graphQlClient().mutate({mutation:Ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:w.recipient.id,firstName:t||w.recipient.firstName,lastName:e||w.recipient.lastName,address:a||w.recipient.address,suburb:n||w.recipient.suburb,state:r||w.recipient.state,email:o||w.recipient.email,postalCode:s||w.recipient.postalCode,country:l||w.recipient.country,mobile:c||w.recipient.mobile,company:d||w.recipient.company,apartment:u||w.recipient.apartment,customField1:A||w.recipient.customField1,customField2:h||w.recipient.customField2,customField3:g||w.recipient.customField3,customField4:p||w.recipient.customField4,customField5:m||w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId,prevalidated:S}});else{const F=await this.graphQlClient().mutate({mutation:uc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:n,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f}});w.recipient={id:F?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:n,state:r,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f},this.experience.callEvent($e.RecipientChanged),await this.graphQlClient().mutate({mutation:hc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,recipientId:F.data?.recipientCreate?.id},context:{transactionOwnerId:this.experience.getTransaction().transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(F=>F(this.experience.getTransaction().recipient))}async fetchConversionConfiguration(){const t=this.experience.getTransaction().recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=te.configurationPromiseMap.get(t.conversionConfigurationId);if(e)this.recipientConversionConfiguration=await e;else{const n=(async()=>(await this.graphQlClient().query({query:Ho,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}})).data.conversionConfiguration)();te.configurationPromiseMap.set(t.conversionConfigurationId,n),this.recipientConversionConfiguration=await n}}}async initializeDefaultWorkflowState(t){const e=()=>{const d=t.finalizeStepConfig;if(!d)return;const u=d.lookAtAnimation,A=d.modelAnimation;u&&this.previewService?.executeCameraAnimation(u),A&&this.modelContainer?.executeAnimation(A)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(d=>{this.storage[d.stepName]=d.storage||{}});const a=await this.getInitialOptionIds(this.reloadedState?.serializableWorkflow?.steps.reduce((d,u)=>(u.selectedVariants?.length&&(d[u.stepName]={selectedVariants:u.selectedVariants.map(A=>({id:A.id}))}),d),{})),n=P.getOptions(Array.from(a)),r=this.fetchConversionConfiguration();await Promise.all([n,r]),this.allScenes=wn(t);const s=(await dt(this.allScenes,this.stepSelections)).map(d=>d.silentSteps).flat(),{stepElements:l,commands:c}=await this.stepElementsForIntroducedSilentSteps(s,!!this.reloadedState);this.commandContext.apply(new V(c),!0),this.stepElements={...this.stepElements,...l},await this.ensureStepsAreLoaded(),this.isReloadedTransaction||this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}async getInitialOptionIds(t){const e=new Set,a=this.experience.getWorkflow();if(!a)return e;const n=wn(a),r={...t};let o=-1;for(;;){const c=(await dt(n,r)).flatMap(d=>d.renderableSteps);if(c.length===o)break;o=c.length;for(const d of c){if(r[d.stepName])continue;const u=d.option?.defaultVariant?.id;u&&(r[d.stepName]={selectedVariants:[{id:u}]})}}return(await dt(n,r)).flatMap(l=>l.renderableSteps).forEach(l=>{l.option?.id&&!l.option?.variants&&e.add(l.option.id)}),e}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addPoller(t){this.pollers.push(t)}addValidationCallback(t){this.validationCallbacks.push(t),t(this.validationErrors)}addRecipientCallback(t){this.recipientCallbacks.push(t),t(this.experience.getTransaction().recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(t=>t.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.experience.getWorkflow()?.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!0}),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter(e=>e!==t)}markUpdatePending(){const t=N();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}async getMandatoryUnfulfilledSteps(){return(await dt(this.allScenes,this.stepSelections)).flatMap(r=>r.renderableSteps).filter(r=>r.mandatory).filter(r=>!this.mandatorySteps[r.stepName]).map(r=>r.stepName)}setStepError(t,e,a){let n=!1;if(!this.validationErrors.steps.has(t)&&a)n=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const r=this.validationErrors.steps.get(t);a&&a!==r.get(e)?(n=!0,r.set(e,a)):a||(n=!0,r.delete(e),r.size===0&&this.validationErrors.steps.delete(t))}n&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");this.previewService=t;const a=this.experience.getProduct();if(!a?.modelUrl||!this.previewService)return;const n=t.loadModel({model:a.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(n),(await dt(this.allScenes,this.stepSelections)).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===E.Model||s.type===E.Material).forEach(s=>{if(!s.option?.id){console.error(`Failed to read option id from step: ${s.stepName}`);return}const l=this.stepSelections[s.stepName]?.selectedVariants||[];if(l.length===0)return;const c=l[0];if(s.type===E.Model){if(!this.modelContainer)throw new R("We should always have a model container when injecting a preview!");const d=c.asset?.fileLink;if(!d){console.error(`Failed to read model url from variant: ${c.id} for step: ${s.stepName}`);return}const u=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:d,contextService:this.getLayoutPreviewService()},u.replaceProductModel||!1)}else{const d=c.material;if(!d){console.error(`Failed to read material from variant: ${c.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new R("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,s.option.id,d)})}}),await n.getInitializationPromise(),this.renderLayouts()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}updateStorage(t,e){const a={...this.storage,[t]:{...this.storage[t],...e}};if(!ae(a,this.storage)){this.storage=a;const n=new En(this.constructSerializableWorkflow());this.commandContext.apply(n,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const n={stepName:a.stepName};n.storage=this.storage[a.stepName],n.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(r=>({id:r.id,priceModifier:r.priceModifier})),t.push(n)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new Pn(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new Pn(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new R("Attempted to serialize state before it was initialized.");const e=Pt(t.transaction),a=fc(e);return JSON.stringify(a,pc,void 0)}async getStateHash(){const t=this.getCommandContext().getState(),a=Object.values(t?.transaction.layouts||{}).map(o=>o.modificationID??"").sort().join(""),r=new TextEncoder().encode(a);if(typeof window<"u"&&window.crypto&&window.crypto.subtle&&window.crypto.subtle.digest){const o=await window.crypto.subtle.digest("SHA-256",r);return Array.from(new Uint8Array(o)).map(c=>c.toString(16).padStart(2,"0")).join("")}try{return(await import("crypto")).createHash("sha256").update(a,"utf8").digest("hex")}catch{throw new Error("Unable to compute SHA-256 hash: no suitable crypto implementation available.")}}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,n)=>Object.keys(a).reduce((r,o)=>{const s=[...a[o]||[]];return n.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),r[o]=s,r},{});this.stepElements=e(this.stepElements,t)}async getInvalidCanvasRegions(){let t=[];for(const e of this.experience.getWorkflow()?.steps||[])if(!await Ct(e,this.stepSelections)&&this.stepElements[e.stepName])for(const a of this.stepElements[e.stepName])t.push(a);return t}async getInvalidModelVariants(){let t=[];for(const e of this.experience.getWorkflow()?.steps||[])e.type===E.Model&&!await Ct(e,this.stepSelections)&&t.push(e.stepName);return t}async stepElementsForIntroducedSilentSteps(t,e){const a=this.experience.getProduct();if(!a)return Promise.resolve({stepElements:{},commands:[]});const n=async(c,d,u)=>{if(c.type===E.SilentIllustration){const A=await new bn(c,d).trigger();return{step:c,results:A}}else if(c.type===E.ProductOverlay){const A=await new bn(c,d,u).trigger();return{step:c,results:A}}return Promise.reject("Unknown silent step. This is a bug")},r=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of r)this.markStepsAsInitialised([c.stepName]),e||s.push(n(c,this.layouts,a));const l=await Promise.all(s);for(const c of l)o.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),o.commands=[...o.commands,...c.results.map(d=>d.command)];return o}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=t}async updateTransactionStakeholders(){const t=await y.getShadowGraphqlClient().query({query:Xo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=t.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:cc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async rejectTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,n){const r=this.experience.getWorkflow();if(!r)throw new Error("Attempted to set selections when no workflow is set!");const o=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((v,I)=>v+I.selectedVariants.map(M=>M.priceModifier||0).reduce((M,O)=>M+O,0),0);for(const v of r.steps)await Ct(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1,delete this.stepMetadata[v.stepName],delete this.stepSelections[v.stepName],delete this.storage[v.stepName]);const s=this.allScenes,l=await dt(s,o),c=await dt(s,this.stepSelections),d=l.map(v=>v.silentSteps).flat(),A=c.map(v=>v.silentSteps).flat().filter(v=>!d.some(I=>I.stepName===v.stepName));for(const v of d)await Ct(v,this.stepSelections)||(this.stepInitialised[v.stepName]=!1);const h=await this.getInvalidCanvasRegions(),{stepElements:g,commands:p}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...g,[t]:a},this.removeElements(h);const m=r.steps.find(v=>v.stepName===t);m?.type===E.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(I=>I.id));const f=h.map(v=>new Dt(v.id)),S=new En(this.constructSerializableWorkflow()),w=[...p,...f,S];w.length>0&&this.commandContext.apply(new V(w),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const F=await this.getInvalidModelVariants(),b=this.modelContainer;if(b){const v=F.map(I=>b.applyModelVariant(I,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(v)}await this.onSelectionChange(),m?.type!==E.Frame&&m?.type!==E.Text&&this.setMandatoryFulfilled(t,!0),n&&await n()}async ensureStepsAreLoaded(){const e=(await dt(this.allScenes,this.stepSelections)).map(l=>l.renderableSteps),a=[],n=e.flat();for(const l of n)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case E.DigitalContent:a.push(Ja.init(l,this,this.reloadedState));break;case E.Frame:a.push(pt.init(l,this,this.reloadedState));break;case E.Illustration:a.push(_t.init(l,this,this.reloadedState));break;case E.Material:a.push(Ka.init(l,this,this.reloadedState));break;case E.Model:a.push(_a.init(l,this,this.reloadedState));break;case E.Module:this.stepSpecificServices[l.stepName]={module:await Qi(l.data.module)},a.push(Xa.init(l,this,this.reloadedState));break;case E.Picture:a.push(Za.init(l,this,this.reloadedState));break;case E.Question:a.push(tn.init(l,this,this.reloadedState));break;case E.Shape:a.push(Tt.init(l,this,this.reloadedState));break;case E.Text:a.push(W.init(l,this,this.reloadedState));break}const r=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=r.flatMap(l=>l?.command?[l.command]:[]),s=r.flatMap(l=>l?.followup?[l.followup]:[]);o&&o.length>0&&this.commandContext.apply(new V(o),!0);for(const l of s)await l();s.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(t=>t(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(t=>t(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(t=>t(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(t=>t(this.informationResults))}onInitChange(){this.initCallbacks.forEach(t=>t(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(t=>{t(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(t=>t(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(t=>{t(this.stepMetadata)})}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach(e=>e(this.storage[t]))}onStorageChange(){this.storageCallbacks.forEach(t=>t(this.storage))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return hs(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}};te.configurationPromiseMap=new Map;let Da=te;class nt{constructor(t){this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.asset?.versions?.find(t=>t.name==="cdn")?.link}getAssetResource(){return this.variantData.asset}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find(a=>a.name==="thumbnail")?.link,e=this.variantData.thumbnail?.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}getCategory(){return this.variantData.category}}const ee=class ee{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){ee.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,t)}getUpdateState(){return!!ee.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new nt(a)}async getAvailableVariants(){return(await this.getAllVariants()).filter(e=>e.isEnabled())||[]}async getAllVariants(){if(!this.step.option?.id)return[];if(this.step.option.variants)return(this.step.option.variants||[]).map(e=>new nt(e))||[];const t=await P.getOption(this.step.option?.id);if(!t)throw new Error("Option not found, cannot fetch variants.");return(t.variants||[]).map(e=>new nt(e))||[]}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.tags}hasTag(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){const a=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){return this.step.globalPropertyAspectConfigurations?.filter(e=>e.globalPropertyConfigurationId===t&&e.aspectName).map(e=>e.aspectName)??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),n=this.step.data.modelAnimation,r=this.step.data.lookAtAnimation;e?r&&e.executeCameraAnimation(r):console.warn("No preview service available, cannot execute camera animations."),a?n&&a.executeAnimation(n,t):console.warn("No model container available, cannot execute model animations.")}};ee.updateState=new Map;let Z=ee;class Vi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return _t.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=U(t[0].id,this.manager.getAllLayoutData()).colors,r=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=r?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=r.channelNumbers.find(d=>d.number===l.channelNumber);if(c){const d=c.id.replace(/\W/g,"");s[l.channelNumber]={browserValue:a[d]?.browserValue||""}}}),s}try{return a}catch(s){console.error(s)}}setColor(t,e,a){const n=new Map,o=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(o?.defaultColorVariants||[]).length!==0?o.channelNumbers.forEach(l=>{if(l.number.toString()===t){const c=l.id.replace(/\W/g,"");a?n.set(c,{browserValue:e,pmsValue:a}):n.set(c,e)}}):a?n.set(t,{browserValue:e,pmsValue:a}):n.set(t,e),_t.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,n)}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?_t.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Ui extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ka.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Li extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return _a.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class zi extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Za.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class qi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await tn.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class Gi extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return Tt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Tt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Tt.availableColours(this.step)}setCustomColor(t){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),Tt.setCustomColor(t,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const t=this.manager.getStepStorage(this.step.stepName)?.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class ji extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){await W.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:e,messageType:pe.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}async getAvailableFillColors(){return this.step.data.colorPickerEnabled?W.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return W.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return W.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);W.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,n=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1}),this.setText(n)}setText(t){const e={input:t,helperData:{}},a=W.findLayoutElements(this.manager,this.step),n=W.filterUnsupportedCharacters(t,a[0]?.fontData),r=Nt(n,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&r>this.step.data.maxLength;o||(e.input=n);const s=a.length<=0,l=s?{inputText:n,text:n}:{inputText:n};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=W.getProcessedInput(n,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:u,errorData:A,helperData:h}=W.updateInputText(n,a,this.step,this.manager);u&&this.manager.getCommandDispatcher()(u),e.helperData=h,e.errorData=A,!o&&!A&&this.manager.updateMetadata(this.step.stepName,{text:d})}return e}getText(){const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&e?.defaultCleared!==void 0&&!e?.defaultCleared?t:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=W.findLayoutElements(this.manager,this.step);return W.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Nt(this.getText(),this.manager);return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}async getAvailableStrokeColors(){return this.step.data.strokeEnabled?W.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeStrokeColor(this.step,t,e,this.manager)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class Hi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Wi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return Ja.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Yi extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Nt(this.getText(),this.manager);return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(t){Xa.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:pe.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class be{static get(t,e){switch(e.type){case E.DigitalContent:return new Wi(t,e,t.getStepTags(e.stepName));case E.Information:return new Hi(t,e,t.getStepTags(e.stepName));case E.Question:return new qi(t,e,t.getStepTags(e.stepName));case E.Text:return new ji(t,e,t.getStepTags(e.stepName));case E.Illustration:return new Vi(t,e,t.getStepTags(e.stepName));case E.Picture:return new zi(t,e,t.getStepTags(e.stepName));case E.Shape:return new Gi(t,e,t.getStepTags(e.stepName));case E.Material:return new Ui(t,e,t.getStepTags(e.stepName));case E.Model:return new Li(t,e,t.getStepTags(e.stepName));case E.Frame:return new gr(t,e,t.getStepTags(e.stepName));case E.Module:return new Yi(t,e,t.getStepTags(e.stepName));default:throw new R(`Step type ${e.type} not yet supported in Core SDK`)}}}const Sc=C.gql`
2139
2139
  fragment CreateDesignTransaction on Transaction {
2140
2140
  id
2141
2141
  designName
@@ -2304,7 +2304,7 @@
2304
2304
  }
2305
2305
  }
2306
2306
  }
2307
- `;var $e=(i=>(i.PriceBreakChanged="PriceBreakChanged",i.ProductChanged="ProductChanged",i.QuantityChanged="QuantityChanged",i.RecipientChanged="RecipientChanged",i.SelectionChanged="SelectionChanged",i))($e||{});class Ki{constructor(t,e){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=Un(async()=>{await Fe.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async a=>new Promise((n,r)=>{try{a.toBlob(o=>{if(o){const s=URL.createObjectURL(o);n(s)}})}catch(o){r(o)}}),this.client=t,this.transaction=e.transaction,this.workflow=e.workflow,this.profanityList=this.transaction.product?.profanities?.map(a=>a.word)||[],this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Da(this,t,a=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(a)},e.graphQlClient,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(a=>{const n=a.traversableScenes.map(r=>{const o=r.renderableSteps.map(s=>s.stepName);return{id:r.name,title:r.title,renderableSteps:o,workflowScene:r}});this.renderableScenes=n,this.renderableSceneCallbacks.forEach(r=>r(n)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.transaction.product}getProfanityList(){return this.profanityList}async setProduct(t){this.workflow=void 0;const e=await this.graphQlClient().mutate({mutation:Fn,variables:{id:this.getTransaction().id,integrationProductId:t}}),a=e.data?.transactionUpdateIntegrationProduct.product;if(!a)throw new R("Failed to set product. No product returned from server.");if(!this.bundle)throw new R("Cannot set product on experience that is not part of a bundle.");this.transaction.product={...this.transaction.product,...e.data?.transactionUpdateIntegrationProduct.product},this.transaction.integrationProduct={...this.transaction.integrationProduct,...e.data?.transactionUpdateIntegrationProduct.integrationProduct},this.transaction.workflowState=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged");const n=(await this.bundle.getProductCollection().fetchProducts()).find(r=>r.getId()===a.id);try{const r=n?.getDefaultWorkflow();if(r){const o=await sr(r.getId());await this.setWorkflow(o),console.log("Setting Product - Workflow set to default for product.")}}catch{console.log("Setting Product - No default workflow available, must be set manually.")}}async clearProduct(){if(!this.bundle)throw new R("Cannot clear product on experience that is not part of a bundle.");this.workflow=void 0,this.transaction.workflowState=void 0,this.transaction.product=void 0,this.transaction.integrationProduct=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged"),await this.graphQlClient().mutate({mutation:Fn,variables:{id:this.getTransaction().id}})}getWorkflow(){return this.workflow}async setWorkflow(t){return this.workflow=t,await this.graphQlClient().mutate({mutation:jo,variables:{id:this.getTransaction().id,workflowId:t.id}}),this.workflowManager.setWorkflow(t)}async attachAddress(t,e,a,n,r,o){await this.graphQlClient().mutate({mutation:Fc,variables:{transactionId:this.getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:r||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:Dc,variables:{transactionId:this.getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.workflowManager.getCommandContext()}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.getWorkflow(),n=a?.finalizeStepConfig?.lookAtAnimation;if(!a)throw new Error("Failed to generate cart preview image! No workflow is set.");if(t){if(!n)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,n)||""}let r=2048;e&&e<=2048&&(r=e);const o=St(r,r),s=this.workflowManager.getCommandContext().getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=s.find(w=>w.layoutState?.layout.panelId===c?.name)||s[0],u=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},A=this.workflowManager.getCommandContext().getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new ze("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),p=Ke(A.layoutState.layout,A.layoutState.elements,{renderingConfiguration:{purpose:Rt.Print,region:{left:u.x,top:u.y,width:u.width,height:u.height},templatingContext:g}}),m=Xn(p);await(await Qa.Pith.from(h,m,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:St,createImage:de,DOMParser:Ua(),fetch})).render();const S=await this.getCanvasObjectURLAsync(o);return o.toDataURL(S)}getStepById(t){const e=this.getWorkflow()?.steps.find(r=>r.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const n=be.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,n),n}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}async getStepsConditionallyActive(){const t=this.getScenes();return(await Promise.all(t.map(async a=>{const n=this.getStepsByScene(a),r=await Promise.all(n.map(o=>Ct(o.getRaw(),this.getWorkflowManager().getStepSelections())));return n.filter((o,s)=>r[s])}))).flat()}getScenes(){return(this.getWorkflow()?.stepGroups||[]).map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let a=0;return Object.values(e).forEach(n=>{a+=n.selections.reduce((r,o)=>r+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,e);if(t){const n=this.getAdditionalProductPriceSubunits(e)||0;return a+n}return a}getAdditionalProductPriceSubunits(t){const e=this.getTransaction().integrationProduct;if(e?.additionalIntegrationProduct?.product){const a=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(a,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),n=t*a;return Math.ceil(n)}priceBreakToBeApplied(){const t=(this.getProduct()?.priceBreaks||[]).sort((n,r)=>-(n.minQty-r.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((n,r)=>n+r.getQuantity(),0);for(const n of t)if(n.minQty<=a)return n.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(t=>{const e=t.getTransaction().id,a=this.getTransaction().id,n=t.getProduct()?.id,r=this.getProduct()?.id;return e!==a&&n===r})}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const n=await t.getGlobalProperties(),r=a?.map(c=>c.getId()),o=this.getSteps().filter(c=>r===void 0||r.includes(c.getId())),s=e.getSteps(),l=c=>n.find(d=>d.getRawProperty().name===c.aspectName);o.forEach(c=>{const d=new Set,u=c.getRaw().globalPropertyAspectConfigurations;u!==void 0&&(u.forEach(A=>d.add(JSON.stringify(A))),s.forEach(A=>{const h=A.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const p=l(g),m=d.has(JSON.stringify(g));if(m&&p?.getType()==="Option"){const f=A.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(m&&p?.getType()==="Text"){const f=A.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflow()?.steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return be.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflow()?.steps.filter(e=>e.type===t).map(e=>be.get(this.getWorkflowManager(),e))||[]}getStepsByScene(t){const e=this.getWorkflow();if(!e?.stepGroups.find(n=>n.name===t.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map(n=>e.steps.find(r=>r.stepName===n)).filter(n=>!!n&&this.stepHasHandle(n)).map(n=>be.get(this.getWorkflowManager(),n))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:xc,variables:{id:this.getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(n=>n.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const n=Q.getMap("transactionCustomerIds")||new Map;n.set(this.getTransaction().id,a.customer.id),Q.setMap("transactionCustomerIds",n)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){const e=this.getProduct(),a=this.getWorkflow(),n=this.getCommandContext().getState();if(!e)throw new R("Product undefined!");if(!a)throw new R("Workflow undefined!");if(!n)throw new R("State undefined!");const o={title:await(async()=>{if(t)return t;const s=this.getTransaction().id,c=(await Fe.getSavedDesigns()).find(d=>d.transactionId===s)?.title;return c||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getTransaction().id,productId:e.id,integrationProductId:this.getTransaction().integrationProduct.id,workflowName:a.name,workflowId:a.id,lastEdited:new Date};return await Fe.addDesign(o),o}async copy(){const t=Pt(this.getCommandContext().getState());if(!t)throw new R("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflow();if(!a)throw new R("Workflow is undefined! Cannot copy experience!");const n=this.getTransaction().integrationProduct?.id;if(!n)throw new R("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:n,workflowId:a.id,workflowState:e})}async onDesignFinished(t=!0){const e=this.getTransaction(),a=this.getProduct(),n=this.getWorkflow();if(!a)throw new R("Product undefined! Cannot finish an experience without a product.");if(!n)throw new R("Workflow undefined! Cannot finish an experience without a workflow.");if(e.isOrdered)return{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:e.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""};const r=await Ji([{workflowManager:this.workflowManager,workflow:n,layouts:this.workflowManager.getLayouts(),getReducerState:()=>this.workflowManager.getCommandContext().getState(),product:a,transaction:e,workflowSelections:this.workflowManager.getWorkflowSelections(),workflowMetadata:this.workflowManager.getWorkflowMetadata(),designName:n.name}],o=>t?this.createPreviewImage(o,1024):Promise.resolve(void 0));return e.completed&&await this.graphQlClient().mutate({mutation:Zo,variables:{transactionId:e.id}}),r[0]}stepHasHandle(t){return t.type!==E.SilentIllustration&&t.type!==E.ProductOverlay}async getExportedStepData(){const t=this.getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),n=[];for(const r of t?.steps||[]){const o=r.stepName,s=e[o],l=a[o]?.selections[0],c={stepId:o,title:r.stepTitle,properties:[]};if(l&&await Mc(r,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){n.push(c);continue}switch(r.type){case E.Frame:{const d=r.data,u=s;u.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case E.Illustration:{const d=r.data,u=s;if(u&&u.colors&&u.colors.length>0&&d.displayColorsOnFinishStep){const A=u.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:A,priceModifier:0})}}break;case E.Module:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case E.Text:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0}),u&&u.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:u.color,priceModifier:0})}}n.push(c)}return n.filter(r=>r.properties&&r.properties.length>0)}getQuantity(){return this.getTransaction().quantity||1}async setQuantity(t){if(t<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getTransaction();await this.graphQlClient().mutate({mutation:Go,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const a=this.eventCallbacks.get(t)||[];a.push(e),this.eventCallbacks.set(t,a)}removeEventListener(t,e){const a=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,a.filter(n=>n!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const kc=i=>{if([E.Question,E.Frame,E.Illustration,E.Material,E.Model,E.Picture,E.Shape,E.Text].includes(i.type)){const e=i.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Mc=async(i,t)=>{if(!kc(i))return!1;const e=await P.getOptionForStep(i);if(e&&(e.variants||[]).length>1){const a=t[i.stepName];return!!(a&&a.selections.length>0)}return!1};class Tc{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration;return t?Promise.all(t.aspects.map(e=>this.getHandle(e))):[]}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:(t.conditionMode===zn.AND?Array.prototype.every.bind(t.conditions):Array.prototype.some.bind(t.conditions))(n=>{const r=e.aspects.find(o=>o.name===n.targetAspectName);return r?n.requiredVariantSelections.some(o=>o===r.value):!1})}async createHandle(t){switch(t.type){case z.FileUpload:return new _i(this.bundle,t).initialize();case z.ColorOption:return new ka(this.bundle,t,t.entityId?await P.getOption(t.entityId):void 0);case z.Option:{const e=t.entityId?await P.getOption(t.entityId):void 0;return e?.type==="Color"?new ka(this.bundle,t,e):new an(this.bundle,t,e)}case z.Text:return new Xi(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Ze{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}isSilent(){return!!this.property.silent}async getSharedSteps(t){const e=t??this.bundle.getWorkflowExperiences();return(await Promise.all(e.map(r=>r.getStepsConditionallyActive()))).map(r=>r.filter(o=>o.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:o.getRaw().globalPropertyAspectConfigurations?.some(s=>s.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&s.aspectName===this.property.name))).flat()}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class _i extends Ze{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await P.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await et(t?.fileLink),a=await Ha(t?.fileLink),n=a.width,r=a.height,o=await rt(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{o.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:n,height:r,aspect:n/r,svg:o.svg,colors:o.colors};gt.set(t?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,vectorizedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Ue.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await G.removeBackgroundFromAsset(e),o={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),n}async vectorizeImage(t=!0){const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to vectorize the image.");const a=this.bundle.getGlobalPropertyStateManager(),n=await G.vectorizeAsset(e),o={...a.getAspectStorage(this.property.name),vectorizedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return G.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?je(We(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return G.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return G.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if(n?.useOriginalAsset===t)return;const r={...n,useOriginalAsset:t},o=t?n?.originalAssetKey:n?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",r)];if(t)s.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};s.push(l())}s.push(this.loadImageData()),await Promise.all(s),this.updateSharedStepStorage(r)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await G.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const r=new Map(n.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);await Promise.all((await this.getSharedSteps(t)).map(async o=>{await o.changeColors(r)}))}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await rt(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));await Promise.all((await e).map(async r=>{await r.changeColors(a)}));const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([r,o])=>({key:r,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const o=(await this.getSharedSteps(e)).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;n.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Xi extends Ze{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=(await this.getSharedSteps(e)).map(r=>{r.setText(t)});await Promise.all(n)}}class an extends Ze{constructor(t,e,a){super(t,e),this.optionResource=a}async ensureOptionLoaded(){if(this.optionResource?.variants)return this.optionResource;if(!this.property.entityId)return this.optionResource;const t=await P.getOption(this.property.entityId);return t&&(this.optionResource=t),this.optionResource}async initDefaultVariant(){await this.ensureOptionLoaded();const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new nt(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(a=>a.id===t);return e?new nt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new nt(e):void 0}}async getAvailableVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new nt(e))}async getAllVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants||[]).map(e=>new nt(e))}async selectVariant(t,e){await this.applyVariantSelection(t),await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(n=>n.id===e);if(a)return this.applyVariantSelection(new nt(a),t)}async applyVariantSelection(t,e){const n=(await this.getSharedSteps(e)).map(r=>r.selectVariant(t));await Promise.all(n)}}class ka extends an{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(r=>r.id===e);if(!a)return;await this.applyColorVariant(new nt(a),t);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;n&&await this.setCustomColor(n)}async applyColorVariant(t,e,a){const r=(await this.getSharedSteps(e)).map(o=>{switch(o.getType()){case E.Shape:return o.selectVariant(t);case E.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case E.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(r)}async setCustomColor(t){const e=this.getCurrentVariant()?.getColor();e&&e.toLowerCase()==="#custom"&&(await this.getSharedSteps()).forEach(n=>n.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const Nc=(i,t,e)=>{const a=i.getWorkflowExperiences(),n=i.getGlobalPropertyConfiguration();return n?a.flatMap(o=>o.getSteps()).filter(o=>o.getGlobalPropertyAspects(n.id).includes(t)&&o.getType()===e):[]},Zi=(i,t)=>{const a=Nc(i,t,E.Illustration).map(n=>{if(!n.getCurrentVariant()?.getAssetResource()?.assetConfiguration)return 0;const o=n.getColors();return o?Object.getOwnPropertyNames(o).length:0});return Math.max(...a)};function Ma(i,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!Rc(a))return a;if(Array.isArray(a))return Ma(a,t);let n={};for(const[r,o]of Object.entries(a))n[r]=Qc(o)?o:Ma(o,t);return Ur(n,t)}return Array.isArray(i)?i.map(e):e(i)}function Qc(i){return i==null}function Rc(i){return typeof i=="object"&&!Array.isArray(i)&&i!==null}function tr(i){const t=new Map;return i?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}function Ie(i){return Ma(i,["__typename"])}class Oc{constructor(t,e,a,n,r){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=r;const o=r?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=Ie(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=Ie(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=n}async clearAspects(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects;this.globalPropertyState.aspects=e.filter(a=>!t.includes(a.name))}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=tr(this.globalPropertyState)}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=Pt(this.globalPropertyState);this.globalPropertyState={...Ie(t),id:e.id},this.recalculateMandatoryStates(),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(a=>a.name===t&&a.channel===e)?.storage}async setAspect(t,e,a,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const r=this.configuration.aspects.find(l=>l.name===t);if(!r)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=Pt(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(n){const l=s.find(c=>c.channel===n);if(l)l.value=e,l.type=r.type,l.channel=n,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(n===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:r.type,storage:a!==null?a:void 0,channel:n})}}else{const l=s[0];l.value=e,l.type=r.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:r.type,storage:a!==null?a:void 0,channel:n});ae(o,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(o,this.globalPropertyState))}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(s=>s.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const r=Pt(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(s=>s.name===t);if(o.length>0)if(a){const s=o.find(l=>l.channel===a);s&&(s.storage=e!==null?e:void 0,s.type=n.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});ae(r,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(r,this.globalPropertyState))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await y.getShadowGraphqlClient().mutate({mutation:$l,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let a=e.type&&e.storage?{}:void 0;if(a)switch(e.type){case z.FileUpload:{a.fileUpload=e.storage;break}case z.Option:{a.option=e.storage;break}case z.ColorOption:{a=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:a,channel:e.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateUpdate)this.globalPropertyState=Ie(t.data.globalPropertyStateUpdate);else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:Ol,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class $c{constructor(t){this.setState(t||'{"transactions": []}')}setState(t){t&&(this.state=JSON.parse(t))}getState(){return this.state}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}}const Vc=C.gql`
2307
+ `;var $e=(i=>(i.PriceBreakChanged="PriceBreakChanged",i.ProductChanged="ProductChanged",i.QuantityChanged="QuantityChanged",i.RecipientChanged="RecipientChanged",i.SelectionChanged="SelectionChanged",i))($e||{});class Ki{constructor(t,e){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=Un(async()=>{await Fe.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async a=>new Promise((n,r)=>{try{a.toBlob(o=>{if(o){const s=URL.createObjectURL(o);n(s)}})}catch(o){r(o)}}),this.client=t,this.transaction=e.transaction,this.workflow=e.workflow,this.profanityList=this.transaction.product?.profanities?.map(a=>a.word)||[],this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Da(this,t,a=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(a)},e.graphQlClient,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(a=>{const n=a.traversableScenes.map(r=>{const o=r.renderableSteps.map(s=>s.stepName);return{id:r.name,title:r.title,renderableSteps:o,workflowScene:r}});this.renderableScenes=n,this.renderableSceneCallbacks.forEach(r=>r(n)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.transaction.product}getProfanityList(){return this.profanityList}async setProduct(t){this.workflow=void 0;const e=await this.graphQlClient().mutate({mutation:Fn,variables:{id:this.getTransaction().id,integrationProductId:t}}),a=e.data?.transactionUpdateIntegrationProduct.product;if(!a)throw new R("Failed to set product. No product returned from server.");if(!this.bundle)throw new R("Cannot set product on experience that is not part of a bundle.");this.transaction.product={...this.transaction.product,...e.data?.transactionUpdateIntegrationProduct.product},this.transaction.integrationProduct={...this.transaction.integrationProduct,...e.data?.transactionUpdateIntegrationProduct.integrationProduct},this.transaction.workflowState=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged");const n=(await this.bundle.getProductCollection().fetchProducts()).find(r=>r.getId()===a.id);try{const r=n?.getDefaultWorkflow();if(r){const o=await sr(r.getId());await this.setWorkflow(o),console.log("Setting Product - Workflow set to default for product.")}}catch{console.log("Setting Product - No default workflow available, must be set manually.")}}async clearProduct(){if(!this.bundle)throw new R("Cannot clear product on experience that is not part of a bundle.");this.workflow=void 0,this.transaction.workflowState=void 0,this.transaction.product=void 0,this.transaction.integrationProduct=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged"),await this.graphQlClient().mutate({mutation:Fn,variables:{id:this.getTransaction().id}})}getWorkflow(){return this.workflow}async setWorkflow(t){return this.workflow=t,await this.graphQlClient().mutate({mutation:jo,variables:{id:this.getTransaction().id,workflowId:t.id}}),this.workflowManager.setWorkflow(t)}async attachAddress(t,e,a,n,r,o){await this.graphQlClient().mutate({mutation:Fc,variables:{transactionId:this.getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:r||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:Dc,variables:{transactionId:this.getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.workflowManager.getCommandContext()}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.getWorkflow(),n=a?.finalizeStepConfig?.lookAtAnimation;if(!a)throw new Error("Failed to generate cart preview image! No workflow is set.");if(t){if(!n)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,n)||""}let r=2048;e&&e<=2048&&(r=e);const o=St(r,r),s=this.workflowManager.getCommandContext().getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=s.find(w=>w.layoutState?.layout.panelId===c?.name)||s[0],u=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},A=this.workflowManager.getCommandContext().getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new ze("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),p=Ke(A.layoutState.layout,A.layoutState.elements,{renderingConfiguration:{purpose:Rt.Print,region:{left:u.x,top:u.y,width:u.width,height:u.height},templatingContext:g}}),m=Xn(p);await(await Qa.Pith.from(h,m,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:St,createImage:de,DOMParser:Ua(),fetch})).render();const S=await this.getCanvasObjectURLAsync(o);return o.toDataURL(S)}getStepById(t){const e=this.getWorkflow()?.steps.find(r=>r.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const n=be.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,n),n}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}async getStepsConditionallyActive(){const t=this.getScenes();return(await Promise.all(t.map(async a=>{const n=this.getStepsByScene(a),r=await Promise.all(n.map(o=>Ct(o.getRaw(),this.getWorkflowManager().getStepSelections())));return n.filter((o,s)=>r[s])}))).flat()}getScenes(){return(this.getWorkflow()?.stepGroups||[]).map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let a=0;return Object.values(e).forEach(n=>{a+=n.selections.reduce((r,o)=>r+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,e);if(t){const n=this.getAdditionalProductPriceSubunits(e)||0;return a+n}return a}getAdditionalProductPriceSubunits(t){const e=this.getTransaction().integrationProduct;if(e?.additionalIntegrationProduct?.product){const a=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(a,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),n=t*a;return Math.ceil(n)}priceBreakToBeApplied(){const t=(this.getProduct()?.priceBreaks||[]).sort((n,r)=>-(n.minQty-r.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((n,r)=>n+r.getQuantity(),0);for(const n of t)if(n.minQty<=a)return n.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(t=>{const e=t.getTransaction().id,a=this.getTransaction().id,n=t.getProduct()?.id,r=this.getProduct()?.id;return e!==a&&n===r})}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const n=await t.getGlobalProperties(),r=a?.map(c=>c.getId()),o=this.getSteps().filter(c=>r===void 0||r.includes(c.getId())),s=e.getSteps(),l=c=>n.find(d=>d.getRawProperty().name===c.aspectName);o.forEach(c=>{const d=new Set,u=c.getRaw().globalPropertyAspectConfigurations;u!==void 0&&(u.forEach(A=>d.add(JSON.stringify(A))),s.forEach(A=>{const h=A.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const p=l(g),m=d.has(JSON.stringify(g));if(m&&p?.getType()==="Option"){const f=A.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(m&&p?.getType()==="Text"){const f=A.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflow()?.steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return be.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflow()?.steps.filter(e=>e.type===t).map(e=>be.get(this.getWorkflowManager(),e))||[]}getStepsByScene(t){const e=this.getWorkflow();if(!e?.stepGroups.find(n=>n.name===t.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map(n=>e.steps.find(r=>r.stepName===n)).filter(n=>!!n&&this.stepHasHandle(n)).map(n=>be.get(this.getWorkflowManager(),n))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:xc,variables:{id:this.getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(n=>n.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const n=Q.getMap("transactionCustomerIds")||new Map;n.set(this.getTransaction().id,a.customer.id),Q.setMap("transactionCustomerIds",n)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){const e=this.getProduct(),a=this.getWorkflow(),n=this.getCommandContext().getState();if(!e)throw new R("Product undefined!");if(!a)throw new R("Workflow undefined!");if(!n)throw new R("State undefined!");const o={title:await(async()=>{if(t)return t;const s=this.getTransaction().id,c=(await Fe.getSavedDesigns()).find(d=>d.transactionId===s)?.title;return c||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getTransaction().id,productId:e.id,integrationProductId:this.getTransaction().integrationProduct.id,workflowName:a.name,workflowId:a.id,lastEdited:new Date};return await Fe.addDesign(o),o}async copy(){const t=Pt(this.getCommandContext().getState());if(!t)throw new R("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflow();if(!a)throw new R("Workflow is undefined! Cannot copy experience!");const n=this.getTransaction().integrationProduct?.id;if(!n)throw new R("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:n,workflowId:a.id,workflowState:e})}async onDesignFinished(t=!0){const e=this.getTransaction(),a=this.getProduct(),n=this.getWorkflow();if(!a)throw new R("Product undefined! Cannot finish an experience without a product.");if(!n)throw new R("Workflow undefined! Cannot finish an experience without a workflow.");if(e.isOrdered)return{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:e.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""};const r=await Ji([{workflowManager:this.workflowManager,workflow:n,layouts:this.workflowManager.getLayouts(),getReducerState:()=>this.workflowManager.getCommandContext().getState(),product:a,transaction:e,workflowSelections:this.workflowManager.getWorkflowSelections(),workflowMetadata:this.workflowManager.getWorkflowMetadata(),designName:n.name}],o=>t?this.createPreviewImage(o,1024):Promise.resolve(void 0));return e.completed&&await this.graphQlClient().mutate({mutation:Zo,variables:{transactionId:e.id}}),r[0]}stepHasHandle(t){return t.type!==E.SilentIllustration&&t.type!==E.ProductOverlay}async getExportedStepData(){const t=this.getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),n=[];for(const r of t?.steps||[]){const o=r.stepName,s=e[o],l=a[o]?.selections[0],c={stepId:o,title:r.stepTitle,properties:[]};if(l&&await Mc(r,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){n.push(c);continue}switch(r.type){case E.Frame:{const d=r.data,u=s;u.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case E.Illustration:{const d=r.data,u=s;if(u&&u.colors&&u.colors.length>0&&d.displayColorsOnFinishStep){const A=u.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:A,priceModifier:0})}}break;case E.Module:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case E.Text:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0}),u&&u.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:u.color,priceModifier:0})}}n.push(c)}return n.filter(r=>r.properties&&r.properties.length>0)}getQuantity(){return this.getTransaction().quantity||1}async setQuantity(t){if(t<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getTransaction();await this.graphQlClient().mutate({mutation:Go,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const a=this.eventCallbacks.get(t)||[];a.push(e),this.eventCallbacks.set(t,a)}removeEventListener(t,e){const a=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,a.filter(n=>n!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const kc=i=>{if([E.Question,E.Frame,E.Illustration,E.Material,E.Model,E.Picture,E.Shape,E.Text].includes(i.type)){const e=i.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Mc=async(i,t)=>{if(!kc(i))return!1;const e=await P.getOptionForStep(i);if(e&&(e.variants||[]).length>1){const a=t[i.stepName];return!!(a&&a.selections.length>0)}return!1};class Tc{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration;return t?Promise.all(t.aspects.map(e=>this.getHandle(e))):[]}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:(t.conditionMode===zn.AND?Array.prototype.every.bind(t.conditions):Array.prototype.some.bind(t.conditions))(n=>{const r=e.aspects.find(o=>o.name===n.targetAspectName);return r?n.requiredVariantSelections.some(o=>o===r.value):!1})}async createHandle(t){switch(t.type){case z.FileUpload:return new _i(this.bundle,t).initialize();case z.ColorOption:return new ka(this.bundle,t,t.entityId?await P.getOption(t.entityId):void 0);case z.Option:{const e=t.entityId?await P.getOption(t.entityId):void 0;return e?.type==="Color"?new ka(this.bundle,t,e):new an(this.bundle,t,e)}case z.Text:return new Xi(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Ze{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}isSilent(){return!!this.property.silent}async getSharedSteps(t){const e=t??this.bundle.getWorkflowExperiences();return(await Promise.all(e.map(r=>r.getStepsConditionallyActive()))).map(r=>r.filter(o=>o.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:o.getRaw().globalPropertyAspectConfigurations?.some(s=>s.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&s.aspectName===this.property.name))).flat()}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class _i extends Ze{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await P.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await et(t?.fileLink),a=await Ha(t?.fileLink),n=a.width,r=a.height,o=await rt(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{o.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:n,height:r,aspect:n/r,svg:o.svg,colors:o.colors};ht.set(t?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,vectorizedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Ue.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await G.removeBackgroundFromAsset(e),o={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),n}async vectorizeImage(t=!0){const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to vectorize the image.");const a=this.bundle.getGlobalPropertyStateManager(),n=await G.vectorizeAsset(e),o={...a.getAspectStorage(this.property.name),vectorizedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return G.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?je(We(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return G.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return G.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if(n?.useOriginalAsset===t)return;const r={...n,useOriginalAsset:t},o=t?n?.originalAssetKey:n?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",r)];if(t)s.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};s.push(l())}s.push(this.loadImageData()),await Promise.all(s),this.updateSharedStepStorage(r)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await G.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const r=new Map(n.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);await Promise.all((await this.getSharedSteps(t)).map(async o=>{await o.changeColors(r)}))}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await rt(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));await Promise.all((await e).map(async r=>{await r.changeColors(a)}));const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([r,o])=>({key:r,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const o=(await this.getSharedSteps(e)).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;n.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Xi extends Ze{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=(await this.getSharedSteps(e)).map(r=>{r.setText(t)});await Promise.all(n)}}class an extends Ze{constructor(t,e,a){super(t,e),this.optionResource=a}async ensureOptionLoaded(){if(this.optionResource?.variants)return this.optionResource;if(!this.property.entityId)return this.optionResource;const t=await P.getOption(this.property.entityId);return t&&(this.optionResource=t),this.optionResource}async initDefaultVariant(){await this.ensureOptionLoaded();const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new nt(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(a=>a.id===t);return e?new nt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new nt(e):void 0}}async getAvailableVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new nt(e))}async getAllVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants||[]).map(e=>new nt(e))}async selectVariant(t,e){await this.applyVariantSelection(t),await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(n=>n.id===e);if(a)return this.applyVariantSelection(new nt(a),t)}async applyVariantSelection(t,e){const n=(await this.getSharedSteps(e)).map(r=>r.selectVariant(t));await Promise.all(n)}}class ka extends an{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(r=>r.id===e);if(!a)return;await this.applyColorVariant(new nt(a),t);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;n&&await this.setCustomColor(n)}async applyColorVariant(t,e,a){const r=(await this.getSharedSteps(e)).map(o=>{switch(o.getType()){case E.Shape:return o.selectVariant(t);case E.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case E.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(r)}async setCustomColor(t){const e=this.getCurrentVariant()?.getColor();e&&e.toLowerCase()==="#custom"&&(await this.getSharedSteps()).forEach(n=>n.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const Nc=(i,t,e)=>{const a=i.getWorkflowExperiences(),n=i.getGlobalPropertyConfiguration();return n?a.flatMap(o=>o.getSteps()).filter(o=>o.getGlobalPropertyAspects(n.id).includes(t)&&o.getType()===e):[]},Zi=(i,t)=>{const a=Nc(i,t,E.Illustration).map(n=>{if(!n.getCurrentVariant()?.getAssetResource()?.assetConfiguration)return 0;const o=n.getColors();return o?Object.getOwnPropertyNames(o).length:0});return Math.max(...a)};function Ma(i,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!Rc(a))return a;if(Array.isArray(a))return Ma(a,t);let n={};for(const[r,o]of Object.entries(a))n[r]=Qc(o)?o:Ma(o,t);return Ur(n,t)}return Array.isArray(i)?i.map(e):e(i)}function Qc(i){return i==null}function Rc(i){return typeof i=="object"&&!Array.isArray(i)&&i!==null}function tr(i){const t=new Map;return i?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}function Ie(i){return Ma(i,["__typename"])}class Oc{constructor(t,e,a,n,r){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=r;const o=r?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=Ie(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=Ie(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=n}async clearAspects(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects;this.globalPropertyState.aspects=e.filter(a=>!t.includes(a.name))}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=tr(this.globalPropertyState)}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=Pt(this.globalPropertyState);this.globalPropertyState={...Ie(t),id:e.id},this.recalculateMandatoryStates(),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(a=>a.name===t&&a.channel===e)?.storage}async setAspect(t,e,a,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const r=this.configuration.aspects.find(l=>l.name===t);if(!r)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=Pt(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(n){const l=s.find(c=>c.channel===n);if(l)l.value=e,l.type=r.type,l.channel=n,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(n===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:r.type,storage:a!==null?a:void 0,channel:n})}}else{const l=s[0];l.value=e,l.type=r.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:r.type,storage:a!==null?a:void 0,channel:n});ae(o,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(o,this.globalPropertyState))}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(s=>s.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const r=Pt(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(s=>s.name===t);if(o.length>0)if(a){const s=o.find(l=>l.channel===a);s&&(s.storage=e!==null?e:void 0,s.type=n.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});ae(r,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(r,this.globalPropertyState))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await y.getShadowGraphqlClient().mutate({mutation:$l,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let a=e.type&&e.storage?{}:void 0;if(a)switch(e.type){case z.FileUpload:{a.fileUpload=e.storage;break}case z.Option:{a.option=e.storage;break}case z.ColorOption:{a=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:a,channel:e.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateUpdate)this.globalPropertyState=Ie(t.data.globalPropertyStateUpdate);else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:Ol,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class $c{constructor(t){this.setState(t||'{"transactions": []}')}setState(t){t&&(this.state=JSON.parse(t))}getState(){return this.state}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}}const Vc=C.gql`
2308
2308
  query GetManyMetafields($entityIds: [String!]!) {
2309
2309
  metafieldsMany(entityIds: $entityIds) {
2310
2310
  id
@@ -2487,7 +2487,7 @@
2487
2487
  }
2488
2488
  }
2489
2489
  }
2490
- `;class Zc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class td{init(t,e,a){this.cognitoClient=new we.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const n=await this.cognitoClient?.send(new we.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return n?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new td;class rr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Or(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=un.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(un.code(e)?.code==="CLP")return"USD0,0"}}const kn=new rr;class or{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,kn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,kn.getPrecisionForCurrency(e))}}const ed=async(i,t)=>{const e=await y.getShadowGraphqlClient().query({query:is(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:i}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(n=>console.error(n)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==i.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(n=>{n.finalizeStepConfig||(n.finalizeStepConfig={}),n.finalizeStepConfig.termsMarkdown=n.finalizeStepConfig.termsMarkdown||n.partner.termsMarkdown}),a},ad=async(i,t)=>{const a=(await t).find(n=>n.id===i);if(!a)throw new Error(`Workflow not found: ${i}`);return a},sn=async(i,t)=>{const e=i.map(s=>oe.get({id:s,options:t})),a=i.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=ed(a,t),r=a.map(s=>oe.set({id:s,options:t},ad(s,n))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},sr=async(i,t)=>(await sn([i],t))[0],nd=async i=>{const t=await y.getShadowGraphqlClient().query({query:mi,variables:{ids:i},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class id{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:qo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&ao(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 39.2.1"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){mt.setHubUrl(t.hubUrl),mt.setServerUrl(t.serverUrl),mt.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&ei(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return G}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!no())throw new Error("Application key required to use Flow Service.");return new ar}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await y.getShadowGraphqlClient().query({query:ds,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new or(o,s,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=lr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Q.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),Q.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),n=(await e.query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const s=(await e.mutate({mutation:Kc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(n);const r=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:r}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),r=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<r-parseInt(t)){const l=await Wt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:_c,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,r=!a?.AccessToken||Oe(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||r){const o=await Wt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Xc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await y.getShadowGraphqlClient().mutate({mutation:Wl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!r?.id)throw new Error("Unable to create bundle");const o=Q.getMap("bundlePartnerIds")||new Map;o.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",o);const s=Q.getMap("bundleOwnerIds")||new Map;s.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",s);const l=new Dn(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n,r){const s=Q.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const m=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(m);f&&!Oe(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...n?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:zl(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=Q.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),Q.setMap("bundlePartnerIds",A);const h=new Dn(this,u,e,a,s,{additionalHeaders:n?.graphql?.additionalHeaders,eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:n?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,n){const o={...await dr(t),...n?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Yl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:rc(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:ql,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&n.set(r.bundle.id,r.bundle.partner.id)}),Q.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0],r=n.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await n.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,n){if(t.length===0)throw new ft("No options provided!");const r=t.map((x,T)=>({option:x,index:T})),o=r.filter(x=>x.option.type==="transaction"),s=r.filter(x=>x.option.type==="integration"||x.option.type==="external"||x.option.type==="blank"),l=50,c=pa(o,l),d=pa(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:zo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,n&&n(u,o.length),k.length!==x.length){const X=L.errors?.[0]?.message||"Unknown error";throw new ft(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((X,It)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(pt=>pt.option.transactionId===X.id)?.option.readOnly??!1,index:x[It].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:Lo,variables:{inputs:x.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new ft(`Failed to create transactions: ${k}`)}return u=u+L.length,n&&n(u,o.length),L.map((k,X)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:x[X].index}))},p=(await Promise.all([...c.map(h),...d.map(g)])).flat(),m=[...new Set(p.map(x=>x.transaction.integrationProductId))].filter(x=>x!==void 0),f=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[S,w]=await Promise.all([(async()=>m.length>0?await nd(m):[])(),(async()=>f.length>0?await sn(f,e):[])()]),F=new Map(S.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,It=L?b.get(L):void 0,pt=t[X];if(T.integrationProductId){const ot=F.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const fe=Q.getMap("transactionOwnerIds")||new Map;!fe.get(T.id)&&T.transactionOwnerId&&(fe.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",fe));const ta=fe.get(T.id)||void 0,yr=new Zc({onMutate:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}})}),Ce={workflow:It,transaction:T,singleVariantsRenderable:pt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new R("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>yr,readOnly:k,isReloadedTransaction:pt.type==="transaction"};if(pt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await Pa(ot),Ce.reloadedState=ot}else if(!k&&pt.workflowState){const ot=JSON.parse(pt.workflowState);await Pa(ot),Ce.reloadedState=ot}return Ce.delayWorkflowStateSync=!0,{experienceOptions:Ce,index:X,options:pt}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let O=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new Ki(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),O=[...O,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return O}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await y.getShadowGraphqlClient().query({query:Ko(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new Ta(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:_o(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new Ta(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(Q.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await y.getShadowGraphqlClient().query({query:Yo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:cs,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const lr=async(i,t)=>(await y.getShadowGraphqlClient().query({query:os,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":i},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,rd=async i=>{const e=await y.getShadowGraphqlClient().query({query:Wo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:i}});if(e.data.transactions.length!==0)return e.data.transactions[0]},od=async(i,t)=>(await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{themeConfigurationId:i,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,sd=async i=>(await y.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",variables:{id:i}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,ld=async i=>(await y.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",variables:{id:i}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function cr(){const i={};try{const t=await this.loggedInBearerToken();i.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,o])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",n=localStorage.getItem(a);n&&!Oe(n)&&(i.Authorization=`Bearer ${n}`)}return i}async function dr(i){const e=Q.getMap("bundleOwnerIds")?.get(i),a=await cr();return{bundleOwnerId:e,...a}}async function cd(i){const e=Q.getMap("transactionOwnerIds")?.get(i),a=await cr();return{transactionOwnerId:e,...a}}const dd=async i=>{const t=await dr(i),e=await y.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i},context:{headers:t}});if(e.data?.bundleDelete!==i)throw new Error(`Failed to delete bundle: ${e.errors}`)},ud=async i=>{const t=await cd(i),e=await y.getShadowGraphqlClient().mutate({mutation:mc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[i]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==i)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function ur(i,t,e,a){const n=e.width*i.zoom,r=e.height*i.zoom;if(a){const s=i,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,i.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Pe(i.x,t.width-c,0),s.y=Pe(i.y,t.height-d,0),s}const o=i;return o.x=Pe(o.x,-n,t.width),o.y=Pe(o.y,-r,t.height),o}function Pe(i,t,e){return Math.min(Math.max(i,t),e)}class Ar{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Un(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let r=!1;for(let o=0;o<n.currentFrameSources.length;o++){const s=n.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;ae(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[o]=l,r=!0)}r&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Mt.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=We(this.imageData.svg,this.imageData.colors||{},!1);return je(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const r=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(r,n),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new R("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=ur(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,r){if(!a||a.length===0||a.some(l=>!l))throw new R("Frame data not set. This is a bug");if(!this.workflowManager)throw new R("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new V([new Ws(l,e,t[d]),new Ys(l,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),r&&r()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=r,this.maxZoomScale[n]=r*2.5):(this.minZoomScale[n]=r/10,this.maxZoomScale[n]=r*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=ja(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Ad{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,n,r,o,s,l,c,d,u,A,h,g,p,m,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Promise(()=>new Set)}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var hr=(i=>(i.SelectFrame="SelectFrame",i.SelectImage="SelectImage",i.Position="Position",i))(hr||{});class gr extends Z{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Ar(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return At.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await At.selectImage(this.step,t,this.manager,a),e){const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Ue.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await G.removeBackgroundFromAsset(e);t&&await At.selectImage(this.step,a,this.manager,!1);const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}async vectorize(t,e=void 0){const a=t??await this.getOriginalImageSelection();if(!a)throw new Error("You must supply an image selection before attempting to vectorize the image.");const n=await G.vectorizeAsset(a,e);await At.selectImage(this.step,n,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,vectorizedAssetKey:n.key,useOriginalAsset:!1}}),n}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return G.getLocalOrFromServer(t)}async getVectorizedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.vectorizedAssetKey;if(t)return G.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}async changeColors(t){await At.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?At.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await rt(t.svg)).colors:void 0}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return At.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return G.getLocalOrFromServer(t)}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const n=await this.getBackgroundRemovedImageSelection();if(!n)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(n,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const hd=C.gql`
2490
+ `;class Zc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class td{init(t,e,a){this.cognitoClient=new we.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const n=await this.cognitoClient?.send(new we.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return n?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new td;class rr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Or(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=un.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(un.code(e)?.code==="CLP")return"USD0,0"}}const kn=new rr;class or{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,kn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,kn.getPrecisionForCurrency(e))}}const ed=async(i,t)=>{const e=await y.getShadowGraphqlClient().query({query:is(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:i}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(n=>console.error(n)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==i.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(n=>{n.finalizeStepConfig||(n.finalizeStepConfig={}),n.finalizeStepConfig.termsMarkdown=n.finalizeStepConfig.termsMarkdown||n.partner.termsMarkdown}),a},ad=async(i,t)=>{const a=(await t).find(n=>n.id===i);if(!a)throw new Error(`Workflow not found: ${i}`);return a},sn=async(i,t)=>{const e=i.map(s=>oe.get({id:s,options:t})),a=i.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=ed(a,t),r=a.map(s=>oe.set({id:s,options:t},ad(s,n))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},sr=async(i,t)=>(await sn([i],t))[0],nd=async i=>{const t=await y.getShadowGraphqlClient().query({query:mi,variables:{ids:i},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class id{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:qo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&ao(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 39.2.2"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){gt.setHubUrl(t.hubUrl),gt.setServerUrl(t.serverUrl),gt.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&ei(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return G}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!no())throw new Error("Application key required to use Flow Service.");return new ar}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await y.getShadowGraphqlClient().query({query:ds,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new or(o,s,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=lr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Q.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),Q.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),n=(await e.query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const s=(await e.mutate({mutation:Kc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(n);const r=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:r}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),r=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<r-parseInt(t)){const l=await Wt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:_c,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,r=!a?.AccessToken||Oe(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||r){const o=await Wt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Xc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await y.getShadowGraphqlClient().mutate({mutation:Wl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!r?.id)throw new Error("Unable to create bundle");const o=Q.getMap("bundlePartnerIds")||new Map;o.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",o);const s=Q.getMap("bundleOwnerIds")||new Map;s.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",s);const l=new Dn(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n,r){const s=Q.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const m=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(m);f&&!Oe(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...n?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:zl(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=Q.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),Q.setMap("bundlePartnerIds",A);const h=new Dn(this,u,e,a,s,{additionalHeaders:n?.graphql?.additionalHeaders,eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:n?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,n){const o={...await dr(t),...n?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Yl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:rc(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:ql,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&n.set(r.bundle.id,r.bundle.partner.id)}),Q.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0],r=n.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await n.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,n){if(t.length===0)throw new ft("No options provided!");const r=t.map((x,T)=>({option:x,index:T})),o=r.filter(x=>x.option.type==="transaction"),s=r.filter(x=>x.option.type==="integration"||x.option.type==="external"||x.option.type==="blank"),l=50,c=pa(o,l),d=pa(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:zo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,n&&n(u,o.length),k.length!==x.length){const X=L.errors?.[0]?.message||"Unknown error";throw new ft(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((X,It)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(mt=>mt.option.transactionId===X.id)?.option.readOnly??!1,index:x[It].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:Lo,variables:{inputs:x.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new ft(`Failed to create transactions: ${k}`)}return u=u+L.length,n&&n(u,o.length),L.map((k,X)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:x[X].index}))},p=(await Promise.all([...c.map(h),...d.map(g)])).flat(),m=[...new Set(p.map(x=>x.transaction.integrationProductId))].filter(x=>x!==void 0),f=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[S,w]=await Promise.all([(async()=>m.length>0?await nd(m):[])(),(async()=>f.length>0?await sn(f,e):[])()]),F=new Map(S.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,It=L?b.get(L):void 0,mt=t[X];if(T.integrationProductId){const ot=F.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const fe=Q.getMap("transactionOwnerIds")||new Map;!fe.get(T.id)&&T.transactionOwnerId&&(fe.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",fe));const ta=fe.get(T.id)||void 0,yr=new Zc({onMutate:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}})}),Ce={workflow:It,transaction:T,singleVariantsRenderable:mt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new R("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>yr,readOnly:k,isReloadedTransaction:mt.type==="transaction"};if(mt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await Pa(ot),Ce.reloadedState=ot}else if(!k&&mt.workflowState){const ot=JSON.parse(mt.workflowState);await Pa(ot),Ce.reloadedState=ot}return Ce.delayWorkflowStateSync=!0,{experienceOptions:Ce,index:X,options:mt}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let O=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new Ki(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),O=[...O,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return O}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await y.getShadowGraphqlClient().query({query:Ko(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new Ta(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:_o(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new Ta(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(Q.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await y.getShadowGraphqlClient().query({query:Yo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:cs,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const lr=async(i,t)=>(await y.getShadowGraphqlClient().query({query:os,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":i},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,rd=async i=>{const e=await y.getShadowGraphqlClient().query({query:Wo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:i}});if(e.data.transactions.length!==0)return e.data.transactions[0]},od=async(i,t)=>(await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{themeConfigurationId:i,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,sd=async i=>(await y.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",variables:{id:i}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,ld=async i=>(await y.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",variables:{id:i}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function cr(){const i={};try{const t=await this.loggedInBearerToken();i.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,o])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",n=localStorage.getItem(a);n&&!Oe(n)&&(i.Authorization=`Bearer ${n}`)}return i}async function dr(i){const e=Q.getMap("bundleOwnerIds")?.get(i),a=await cr();return{bundleOwnerId:e,...a}}async function cd(i){const e=Q.getMap("transactionOwnerIds")?.get(i),a=await cr();return{transactionOwnerId:e,...a}}const dd=async i=>{const t=await dr(i),e=await y.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i},context:{headers:t}});if(e.data?.bundleDelete!==i)throw new Error(`Failed to delete bundle: ${e.errors}`)},ud=async i=>{const t=await cd(i),e=await y.getShadowGraphqlClient().mutate({mutation:mc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[i]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==i)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function ur(i,t,e,a){const n=e.width*i.zoom,r=e.height*i.zoom;if(a){const s=i,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,i.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Pe(i.x,t.width-c,0),s.y=Pe(i.y,t.height-d,0),s}const o=i;return o.x=Pe(o.x,-n,t.width),o.y=Pe(o.y,-r,t.height),o}function Pe(i,t,e){return Math.min(Math.max(i,t),e)}class Ar{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Un(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let r=!1;for(let o=0;o<n.currentFrameSources.length;o++){const s=n.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;ae(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[o]=l,r=!0)}r&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Mt.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=We(this.imageData.svg,this.imageData.colors||{},!1);return je(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const r=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(r,n),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new R("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=ur(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,r){if(!a||a.length===0||a.some(l=>!l))throw new R("Frame data not set. This is a bug");if(!this.workflowManager)throw new R("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new V([new Ws(l,e,t[d]),new Ys(l,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),r&&r()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=r,this.maxZoomScale[n]=r*2.5):(this.minZoomScale[n]=r/10,this.maxZoomScale[n]=r*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=ja(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Ad{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,n,r,o,s,l,c,d,u,A,h,g,p,m,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Promise(()=>new Set)}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var hr=(i=>(i.SelectFrame="SelectFrame",i.SelectImage="SelectImage",i.Position="Position",i))(hr||{});class gr extends Z{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Ar(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return pt.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await pt.selectImage(this.step,t,this.manager,a),e){const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Ue.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await G.removeBackgroundFromAsset(e);t&&await pt.selectImage(this.step,a,this.manager,!1);const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}async vectorize(t,e=void 0){const a=t??await this.getOriginalImageSelection();if(!a)throw new Error("You must supply an image selection before attempting to vectorize the image.");const n=await G.vectorizeAsset(a,e);await this.selectImage(n,t!==void 0);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,vectorizedAssetKey:n.key,useOriginalAsset:!1}}),n}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return G.getLocalOrFromServer(t)}async getVectorizedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.vectorizedAssetKey;if(t)return G.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}async changeColors(t){await pt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?pt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await rt(t.svg)).colors:void 0}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return pt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return G.getLocalOrFromServer(t)}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const n=await this.getBackgroundRemovedImageSelection();if(!n)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(n,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const hd=C.gql`
2491
2491
  query GetLoggedInCustomer($email: String!) {
2492
2492
  customer(emailAddress: $email) {
2493
2493
  id
@@ -2688,5 +2688,5 @@
2688
2688
  }
2689
2689
  }
2690
2690
  }
2691
- `,jd=async i=>(await y.getShadowGraphqlClient().query({query:Gd,variables:{ids:i}})).data.integrationProducts;exports.AddonHandle=Ue;exports.AddressValidationJobStatus=wr;exports.AddressValidationResultConfirmationLevel=Cr;exports.AddressValidationStatus=Ra;exports.ArrayInput=Jc;exports.AspectType=z;exports.AssetNotFoundError=yt;exports.AssetType=ne;exports.BringForwardCommand=Zs;exports.BringToBackCommand=Xs;exports.BringToFrontCommand=_s;exports.BundleDesignCreationCartAddMode=Gn;exports.CanvasCommand=$;exports.CollectionProduct=Jt;exports.ColorOptionGlobalPropertyHandle=ka;exports.CommandContext=bi;exports.ConversionDataType=Zt;exports.ConversionLocation=mr;exports.CreateElementCommand=H;exports.CreateLayoutCommand=Ya;exports.CurrencyContext=or;exports.CurrencyService=rr;exports.DeleteElementCommand=Dt;exports.DigitalContentStepHandle=Wi;exports.FileUploadGlobalPropertyHandle=_i;exports.FlowExecutionNodeResult=Kt;exports.FlowExecutionResult=nr;exports.FlowService=ar;exports.FontAlignmentCommand=Di;exports.FontColorCommand=xi;exports.FontSizeCommand=Fi;exports.FontSourceCommand=xa;exports.FrameService=Ar;exports.FrameStep=hr;exports.FrameStepHandle=gr;exports.GlobalPropertyHandle=Ze;exports.GroupCommand=V;exports.IllustrationStepHandle=Vi;exports.InformationMessageType=pe;exports.InformationStepHandle=Hi;exports.IntegrationProduct=Ta;exports.IntegrationType=Hn;exports.LayoutElementFactory=qs;exports.LayoutElementType=D;exports.LayoutNotFoundError=J;exports.LayoutRenderingPurpose=Rt;exports.MaterialStepHandle=Ui;exports.MisconfigurationError=lt;exports.MockWorkflowManager=Ad;exports.ModelStepHandle=Li;exports.ModuleStepHandle=Yi;exports.MoveCommand=Gs;exports.ObjectInput=on;exports.ObjectInputType=ir;exports.OptionGlobalPropertyHandle=an;exports.OptionNotFoundError=ie;exports.ParseError=Bt;exports.PictureStepHandle=zi;exports.ProductCameraRig=Wn;exports.ProductCollection=nn;exports.ProductCollectionProductSortKey=er;exports.ProductWorkflow=Qt;exports.PromiseCache=oe;exports.PromiseQueue=qa;exports.QuestionStepHandle=qi;exports.QueueablePromise=za;exports.ResizeCommand=Hs;exports.ResourceNotFoundError=Ot;exports.RotateCommand=js;exports.ScaleAxis=Y;exports.SendBackwardsCommand=tl;exports.ShapeStepHandle=Gi;exports.ShareActionType=jn;exports.SpiffCommerceClient=id;exports.StakeholderType=Oa;exports.StepAspectType=qn;exports.StepHandle=Z;exports.StepType=E;exports.TextAlgorithm=xt;exports.TextChangeCommand=ki;exports.TextGlobalPropertyHandle=Xi;exports.TextInput=Yc;exports.TextStepHandle=ji;exports.UnhandledBehaviorError=R;exports.UnitOfMeasurement=Yn;exports.UpdateImageSourceCommand=Js;exports.Variant=nt;exports.WorkflowExperienceEventType=$e;exports.WorkflowExperienceImpl=Ki;exports.amtChannelsForAspect=Zi;exports.assetService=G;exports.browserColorToHex=ii;exports.cmPerPixel=Bs;exports.currentDirection=Es;exports.dataUrlFromExternalUrl=_r;exports.deleteBundle=dd;exports.designService=Fe;exports.determineCorrectFontSizeAndLines=Xt;exports.digitalContentStepService=Ja;exports.domParser=ct;exports.duplicateBundle=Ed;exports.duplicateTransaction=bd;exports.fetchAsString=et;exports.findAngle=ps;exports.findElement=U;exports.findPmsColors=fo;exports.frameDataCache=Mt;exports.frameStepService=At;exports.generate=N;exports.generateCommands=Ri;exports.generateSVGWithUnknownColors=rt;exports.generateStateFromDesignInputSteps=Rl;exports.getAddressValidationJobs=Ud;exports.getAttributesFromArrayBuffer=ue;exports.getAxisAlignedBoundingBox=ms;exports.getBoundedOffsets=ur;exports.getBundleIdForTransaction=ud;exports.getBundleThemeConfiguration=sd;exports.getCustomer=Id;exports.getCustomerBundles=Bd;exports.getElementVertices=bs;exports.getFrameData=me;exports.getGlobalPropertyStateForBundle=Ul;exports.getIntegration=lr;exports.getIntegrationProducts=jd;exports.getNEPoint=Ss;exports.getNWPoint=ys;exports.getOrderedTransactions=Fd;exports.getOverrideThemeConfiguration=od;exports.getPointOfRotation=ws;exports.getProductCollections=zc;exports.getSEPoint=vs;exports.getSvgElement=Ke;exports.getTemplateBundles=kd;exports.getTemplateTransactions=Dd;exports.getTransaction=rd;exports.getTransactionThemeConfiguration=ld;exports.getTransactionsForBundle=Pd;exports.getTrueCoordinates=Cs;exports.getUnorderedTransactions=xd;exports.getValidationJobsForWorkflowExperiences=Vd;exports.getWorkflow=sr;exports.getWorkflows=sn;exports.graphQlManager=y;exports.illustrationStepService=_t;exports.isCloseToValue=fs;exports.loadFont=Ft;exports.matchHexToPms=go;exports.materialStepService=Ka;exports.metafieldManager=Ve;exports.mmPerPixel=Is;exports.modelStepService=_a;exports.modifySVGColors=We;exports.moduleStepService=Xa;exports.nameBundle=Sd;exports.nameTransaction=vd;exports.optionService=P;exports.outlineFontsInSvg=ks;exports.overrideWorkflowExperienceRecipientAddress=qd;exports.patternImageDataCache=gt;exports.persistenceService=Q;exports.pictureStepService=Za;exports.pmsToRgb=ho;exports.questionStepService=tn;exports.registerFetchImplementation=Hr;exports.registerWindowImplementation=jr;exports.rehydrateSerializedLayout=Pa;exports.rgbToPms=ni;exports.rotateAroundPoint=Yt;exports.sanitizeSvgTree=He;exports.setBearerAuthenticationToken=ei;exports.setCanvasModule=Va;exports.shapeStepService=Tt;exports.shortenUrl=Mi;exports.spiffCoreConfiguration=mt;exports.stepAspectValuesToDesignInputSteps=Ql;exports.svgColorValueToDefinition=Ea;exports.svgStringDimensions=Wa;exports.svgToDataUrl=je;exports.textStepService=W;exports.toast=Ni;exports.validateWorkflowExperienceRecipient=Ld;exports.validateWorkflowExperienceRecipients=zd;exports.xmlSerializer=bt;
2691
+ `,jd=async i=>(await y.getShadowGraphqlClient().query({query:Gd,variables:{ids:i}})).data.integrationProducts;exports.AddonHandle=Ue;exports.AddressValidationJobStatus=wr;exports.AddressValidationResultConfirmationLevel=Cr;exports.AddressValidationStatus=Ra;exports.ArrayInput=Jc;exports.AspectType=z;exports.AssetNotFoundError=yt;exports.AssetType=ne;exports.BringForwardCommand=Zs;exports.BringToBackCommand=Xs;exports.BringToFrontCommand=_s;exports.BundleDesignCreationCartAddMode=Gn;exports.CanvasCommand=$;exports.CollectionProduct=Jt;exports.ColorOptionGlobalPropertyHandle=ka;exports.CommandContext=bi;exports.ConversionDataType=Zt;exports.ConversionLocation=mr;exports.CreateElementCommand=H;exports.CreateLayoutCommand=Ya;exports.CurrencyContext=or;exports.CurrencyService=rr;exports.DeleteElementCommand=Dt;exports.DigitalContentStepHandle=Wi;exports.FileUploadGlobalPropertyHandle=_i;exports.FlowExecutionNodeResult=Kt;exports.FlowExecutionResult=nr;exports.FlowService=ar;exports.FontAlignmentCommand=Di;exports.FontColorCommand=xi;exports.FontSizeCommand=Fi;exports.FontSourceCommand=xa;exports.FrameService=Ar;exports.FrameStep=hr;exports.FrameStepHandle=gr;exports.GlobalPropertyHandle=Ze;exports.GroupCommand=V;exports.IllustrationStepHandle=Vi;exports.InformationMessageType=pe;exports.InformationStepHandle=Hi;exports.IntegrationProduct=Ta;exports.IntegrationType=Hn;exports.LayoutElementFactory=qs;exports.LayoutElementType=D;exports.LayoutNotFoundError=J;exports.LayoutRenderingPurpose=Rt;exports.MaterialStepHandle=Ui;exports.MisconfigurationError=lt;exports.MockWorkflowManager=Ad;exports.ModelStepHandle=Li;exports.ModuleStepHandle=Yi;exports.MoveCommand=Gs;exports.ObjectInput=on;exports.ObjectInputType=ir;exports.OptionGlobalPropertyHandle=an;exports.OptionNotFoundError=ie;exports.ParseError=Bt;exports.PictureStepHandle=zi;exports.ProductCameraRig=Wn;exports.ProductCollection=nn;exports.ProductCollectionProductSortKey=er;exports.ProductWorkflow=Qt;exports.PromiseCache=oe;exports.PromiseQueue=qa;exports.QuestionStepHandle=qi;exports.QueueablePromise=za;exports.ResizeCommand=Hs;exports.ResourceNotFoundError=Ot;exports.RotateCommand=js;exports.ScaleAxis=Y;exports.SendBackwardsCommand=tl;exports.ShapeStepHandle=Gi;exports.ShareActionType=jn;exports.SpiffCommerceClient=id;exports.StakeholderType=Oa;exports.StepAspectType=qn;exports.StepHandle=Z;exports.StepType=E;exports.TextAlgorithm=xt;exports.TextChangeCommand=ki;exports.TextGlobalPropertyHandle=Xi;exports.TextInput=Yc;exports.TextStepHandle=ji;exports.UnhandledBehaviorError=R;exports.UnitOfMeasurement=Yn;exports.UpdateImageSourceCommand=Js;exports.Variant=nt;exports.WorkflowExperienceEventType=$e;exports.WorkflowExperienceImpl=Ki;exports.amtChannelsForAspect=Zi;exports.assetService=G;exports.browserColorToHex=ii;exports.cmPerPixel=Bs;exports.currentDirection=Es;exports.dataUrlFromExternalUrl=_r;exports.deleteBundle=dd;exports.designService=Fe;exports.determineCorrectFontSizeAndLines=Xt;exports.digitalContentStepService=Ja;exports.domParser=ct;exports.duplicateBundle=Ed;exports.duplicateTransaction=bd;exports.fetchAsString=et;exports.findAngle=ps;exports.findElement=U;exports.findPmsColors=fo;exports.frameDataCache=Mt;exports.frameStepService=pt;exports.generate=N;exports.generateCommands=Ri;exports.generateSVGWithUnknownColors=rt;exports.generateStateFromDesignInputSteps=Rl;exports.getAddressValidationJobs=Ud;exports.getAttributesFromArrayBuffer=ue;exports.getAxisAlignedBoundingBox=ms;exports.getBoundedOffsets=ur;exports.getBundleIdForTransaction=ud;exports.getBundleThemeConfiguration=sd;exports.getCustomer=Id;exports.getCustomerBundles=Bd;exports.getElementVertices=bs;exports.getFrameData=me;exports.getGlobalPropertyStateForBundle=Ul;exports.getIntegration=lr;exports.getIntegrationProducts=jd;exports.getNEPoint=Ss;exports.getNWPoint=ys;exports.getOrderedTransactions=Fd;exports.getOverrideThemeConfiguration=od;exports.getPointOfRotation=ws;exports.getProductCollections=zc;exports.getSEPoint=vs;exports.getSvgElement=Ke;exports.getTemplateBundles=kd;exports.getTemplateTransactions=Dd;exports.getTransaction=rd;exports.getTransactionThemeConfiguration=ld;exports.getTransactionsForBundle=Pd;exports.getTrueCoordinates=Cs;exports.getUnorderedTransactions=xd;exports.getValidationJobsForWorkflowExperiences=Vd;exports.getWorkflow=sr;exports.getWorkflows=sn;exports.graphQlManager=y;exports.illustrationStepService=_t;exports.isCloseToValue=fs;exports.loadFont=Ft;exports.matchHexToPms=go;exports.materialStepService=Ka;exports.metafieldManager=Ve;exports.mmPerPixel=Is;exports.modelStepService=_a;exports.modifySVGColors=We;exports.moduleStepService=Xa;exports.nameBundle=Sd;exports.nameTransaction=vd;exports.optionService=P;exports.outlineFontsInSvg=ks;exports.overrideWorkflowExperienceRecipientAddress=qd;exports.patternImageDataCache=ht;exports.persistenceService=Q;exports.pictureStepService=Za;exports.pmsToRgb=ho;exports.questionStepService=tn;exports.registerFetchImplementation=Hr;exports.registerWindowImplementation=jr;exports.rehydrateSerializedLayout=Pa;exports.rgbToPms=ni;exports.rotateAroundPoint=Yt;exports.sanitizeSvgTree=He;exports.setBearerAuthenticationToken=ei;exports.setCanvasModule=Va;exports.shapeStepService=Tt;exports.shortenUrl=Mi;exports.spiffCoreConfiguration=gt;exports.stepAspectValuesToDesignInputSteps=Ql;exports.svgColorValueToDefinition=Ea;exports.svgStringDimensions=Wa;exports.svgToDataUrl=je;exports.textStepService=W;exports.toast=Ni;exports.validateWorkflowExperienceRecipient=Ld;exports.validateWorkflowExperienceRecipients=zd;exports.xmlSerializer=bt;
2692
2692
  //# sourceMappingURL=index.cjs.map