@spiffcommerce/core 32.2.7 → 32.3.0-beta.0216b2a2-df3f-5d89-bac8-e2dc336adf63

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,12 +1,12 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const w=require("@apollo/client/core"),ni=require("@apollo/client/link/context"),ri=require("@apollo/client/link/error"),ii=require("preact-render-to-string"),oi=require("@apollo/client/link/remove-typename"),si=require("exifr/dist/mini.umd.cjs"),bn=require("css"),li=require("fuse.js"),ba=require("pith"),It=require("lodash.clonedeep"),Bn=require("qrcode"),ci=require("svg-path-bbox"),sa=require("opentype.js"),I=require("preact/jsx-runtime"),di=require("handlebars"),Ai=require("data-uri-to-buffer"),Xa=require("lodash.chunk"),fe=require("@aws-sdk/client-cognito-identity-provider"),ui=require("dinero.js"),hi=require("currency-codes"),xe=require("lodash.isequal"),la=require("unicode-default-word-boundary"),In=require("lodash.debounce");require("fs");require("path");const gi=require("lodash.omit");function mi(n){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const e in n)if(e!=="default"){const a=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(t,e,a.get?a:{enumerable:!0,get:()=>n[e]})}}return t.default=n,Object.freeze(t)}const Za=mi(hi);var te=(n=>(n.Data="Data",n.Font="Font",n.Frame="Frame",n.Illustration="Illustration",n.Image="Image",n.Model="Model",n.Material="Material",n.Color="Color",n.QuestionnaireCollateral="QuestionnaireCollateral",n.RequestCollateral="RequestCollateral",n.SignupCollateral="SignupCollateral",n.Video="Video",n.ColorProfile="ColorProfile",n.Environment="Environment",n))(te||{}),U=(n=>(n.FileUpload="FileUpload",n.Option="Option",n.ColorOption="ColorOption",n.Text="Text",n))(U||{}),v=(n=>(n.Information="Information",n.Bulk="Bulk",n.DigitalContent="DigitalContent",n.Finish="Finish",n.Frame="Frame",n.Illustration="Illustration",n.Introduction="Introduction",n.Material="Material",n.Model="Model",n.Module="Module",n.Picture="Picture",n.Photo="Photo",n.ProductOverlay="ProductOverlay",n.Question="Question",n.Shape="Shape",n.SilentIllustration="SilentIllustration",n.Text="Text",n))(v||{}),Pn=(n=>(n.Color="Color",n.Colors="Colors",n.Selection="Selection",n.Selections="Selections",n.Text="Text",n.Upload="Upload",n))(Pn||{}),Nt=(n=>(n.ThreeD="ThreeD",n.FreeDesign="FreeDesign",n.Print="Print",n))(Nt||{}),F=(n=>(n.Frame="frame",n.Group="group",n.Image="image",n.Pattern="pattern",n.Illustration="illustration",n.Textbox="textbox",n))(F||{}),xn=(n=>(n.Default="Default",n.FirstTransaction="FirstTransaction",n.OneToOne="OneToOne",n))(xn||{}),Ba=(n=>(n.Pending="Pending",n.Failed="Failed",n.Validated="Validated",n.Overridden="Overridden",n))(Ba||{}),Dn=(n=>(n.Hyperlink="Hyperlink",n.Edit="Edit",n.Approve="Approve",n))(Dn||{}),Fn=(n=>(n.Hub="Hub",n.Shopify="Shopify",n))(Fn||{}),Qe=(n=>(n.BackgroundRemover="BackgroundRemover",n.ConversionAccelerator="Conversion Accelerator",n.ProcessBuilder="ProcessBuilder",n))(Qe||{}),kn=(n=>(n[n.Orbit=0]="Orbit",n[n.Pan=1]="Pan",n))(kn||{}),ee=(n=>(n.Owner="Owner",n.Approver="Approver",n.Editor="Editor",n.Viewer="Viewer",n))(ee||{}),Pt=(n=>(n.Autosize="Autosize",n.Traditional="Traditional",n))(Pt||{}),G=(n=>(n[n.North=0]="North",n[n.Northeast=1]="Northeast",n[n.East=2]="East",n[n.Southeast=3]="Southeast",n[n.South=4]="South",n[n.Southwest=5]="Southwest",n[n.West=6]="West",n[n.Northwest=7]="Northwest",n))(G||{}),Mn=(n=>(n.Pixel="px",n.Millimeter="mm",n.Centimeter="cm",n))(Mn||{});class Tn extends Error{constructor(t){super(t),this.name=this.constructor.name}}class oe extends Tn{constructor(t){super(`ConfigurationError - ${t}`)}}class ae extends oe{constructor(t){super(`Option not Configured: ${t.stepTitle}`),this.optionId=t?.optionId||"N/A"}}class j extends oe{constructor(t){super(`Panel not Found: ${t.panelId}`),this.panelId=t?.panelId||"N/A"}}class pt extends oe{constructor(t){super(`Asset not found for variant: ${t.name}`),this.variant=t}}class Qt extends oe{constructor(t){super(`Resource not found for asset: ${t.name}`),this.asset=t}}class ne extends oe{constructor(t,e){super(`Workflow Misconfiguration: ${t.stepName} - ${e}`),this.step=t}}class Re extends Tn{constructor(t){super(`ImplementationError - ${t}`)}}class L extends Re{constructor(t){super(`Unhandled Behavior Encountered: ${t}`)}}class bt extends Re{constructor(t){super(`Parsing Error: ${t}`)}}class gt extends Re{constructor(t){super(`Client Error: ${t}`)}}class Oe extends Re{constructor(t){super(`Resource Generation Failed: ${t}`)}}class pi{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 tn{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 fi=()=>{try{return localStorage?new pi:new tn}catch{return console.warn("Local storage was unavilable due to browser security settings. Using in-memory storage instead."),new tn}},k=fi();class Ci{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 At=new Ci;let ca,da;function wi(n){ca=n}function yi(n){da=n}function se(){return ca?new ca().window:(console.log("DOM constructor is not registered. Assuming browser environment. If not, please register DOM constructor before calling this function."),window)}function it(n,t){if(!da){if(typeof window<"u"&&window.fetch)return window.fetch(n,t);if(typeof global<"u"&&global.fetch)return global.fetch(n,t);throw new Error("Fetch implementation is not registered. Please register it before calling this function.")}return da(n,t)}const Nn=new Map,en=new Map,an=new Map,Qn=async n=>{const t=en.get(n);if(t)return t;const a=(async()=>{const r=await it(n);return Nn.set(n,r.headers?.get("content-type")||""),await r.arrayBuffer()})();return en.set(n,a),a},Si=async n=>{const t=an.get(n);if(t)return t;const a=(async()=>await(await it(n)).text())();return an.set(n,a),a},Ut=n=>n.every(t=>t!=="undefined"),Ce=n=>Ut([typeof document])?document.createElement(n):se().document.createElement(n),vi=(n,t)=>{if(Ut([typeof document]))return document.createElementNS(n,t);const a=se().document.createElement(t);return a.setAttribute("xmlns",n),a},lt=()=>{if(Ut([typeof DOMParser]))return new DOMParser;const n=se();return new n.DOMParser},Ei=()=>Ut([typeof DOMParser])?DOMParser:se().DOMParser,$e=(n,t)=>new Promise((e,a)=>{t?Qn(n).then(e).catch(a):it(n).then(r=>{r.arrayBuffer().then(e).catch(a)}).catch(r=>{a(r)})}),tt=(n,t)=>new Promise((e,a)=>{t?Si(n).then(e).catch(a):it(n).then(r=>{r.text().then(e).catch(a)}).catch(a)}),Rn=n=>ii.renderToStaticMarkup(n),He=new Map,bi=async(n,t)=>{if(Ut([typeof FontFace])){if(He.has(t))return He.get(t);const e=n.names.fullName.en,a=new FontFace(e,`url(${t})`);document.fonts.add(a);const r=a.load();return He.set(t,r),r}},St=()=>{if(Ut([typeof XMLSerializer]))return new XMLSerializer;const n=se();return new n.XMLSerializer},nn=n=>btoa(n),Ue=n=>{function t(){const a=new Uint8Array(n),r=4;if(a.length>=r){const i=new Array(r);for(let l=0;l<r;l++)i[l]=new Uint8Array(n)[l].toString(16);const o=i.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"},Bi=async n=>{const t=await Qn(n),e=Nn.get(n)||Ue(t);return await xi(new Blob([t],{type:e}))},Ii=n=>{let t="";const e=n.byteLength;for(let a=0;a<e;a++)t+=String.fromCharCode(n[a]);return t},Pi=async n=>{const t=Ue(n),e=new Uint8Array(n),a=Ii(e),r=btoa(a);return`data:${t};base64,${r}`},Le=n=>`data:image/svg+xml;base64,${btoa(n)}`,On=n=>{const t=n.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 r=!1;for(let o=1;o<a.length;o++)a[o]==="base64"&&(r=!0);const i=decodeURI(t.substring(e+1));return r?new Uint8Array(atob(i).split("").map(s=>s.charCodeAt(0))).buffer:new Uint8Array(i.split("").map(s=>s.charCodeAt(0))).buffer},xi=n=>new Promise((t,e)=>{const a=new FileReader;a.onload=function(r){const i=r.target;!i||!i.result?e():t(i.result.toString())},a.readAsDataURL(n)});let Di,Ia;const Fi=n=>{Ia=n},ki=()=>Ia;let $n;const Un=n=>{$n=n},Mi=()=>new Promise(n=>{const t=At.getHubUrl(),e=a=>{a.origin===t&&(window.removeEventListener("message",e),n(a.data))};window.parent!==window&&(window.addEventListener("message",e,!1),window.parent.postMessage("ready",t))}),Ti=async()=>{const n={applicationKey:Ia,customerToken:Di,bearer:$n};return typeof window<"u"&&(window.location.href.includes("/workflows/product/")||window.location.href.includes("hub=true"))?{...await Mi(),...n}:n};async function Ni(n,t){const e=At.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 r=await it(n,{...t,redirect:"manual"});return r.type==="opaqueredirect"&&(typeof n!="string"&&"url"in n?r=await it({...n,url:`${a}/graphql`},t):r=await it(`${a}/graphql`,t)),r}class Qi{constructor(){this.shadowGraphqlClient=this.constructShadowGraphqlClient(),At.addServerUrlCallback(()=>{this.shadowGraphqlClient=this.constructShadowGraphqlClient()})}setSpiffCommerceClient(t){this.spiffClient=t,this.shadowGraphqlClient=this.constructShadowGraphqlClient()}getShadowGraphqlClient(){return this.shadowGraphqlClient}constructShadowGraphqlClient(){const t=w.createHttpLink({uri:`${At.getServerUrl()}/graphql`,fetch:Ni}),e=ni.setContext(async(i,o)=>{const{headers:s}=o,l=s||{},c=await Ti();let d=o.bearer??c.bearer;if(this.spiffClient)try{d=await this.spiffClient.loggedInBearerToken()}catch{}const A=o.partnerId??c.partnerId,u=o.activeIntegration??c.activeIntegration,h=o.transactionOwnerId,g=o.customerToken??c.customerToken,m=o.applicationKey??c.applicationKey,p=o.bundleOwnerId;try{if(window&&window.__SENTRY__){const f=window.__SENTRY__.hub;if(f){const S=f.traceHeaders();Object.entries(S).forEach(([b,P])=>{l[b]=P})}}}catch{}return d&&(l.Authorization=`Bearer ${d}`),A&&(l.partnerId=A),u&&(l.activeIntegration=u),h&&(l.transactionOwnerId=h),g&&(l.customerToken=g),m&&(l["X-Application-Key"]=m),p&&(l.bundleOwnerId=p),l["Allow-Moonlight-Redirect"]="true",{headers:l}}),a=ri.onError(({operation:i,graphQLErrors:o,networkError:s})=>{const l=o||[],c=i.getContext();s&&!c?.fetchOptions?.signal?.aborted&&console.log("GraphQL Network error"),l.forEach(()=>console.log("GraphQL Error: "+i.operationName))}),r=oi.removeTypenameFromVariables();return new w.ApolloClient({link:w.from([r,a,e,t]),cache:new w.InMemoryCache,name:"Core"})}}const y=new Qi;let Aa,ua;const ft=(n,t,e)=>{if(Aa!==void 0)return Aa(n,t,e);try{const a=Ln(!0);return Pa(a),a.createCanvas(n,t,e)}catch{throw new Error("Canvas module not set")}},le=(n,t)=>{if(ua!==void 0)return ua(n,t);try{const e=Ln(!0);return Pa(e),e.loadImage(n,t)}catch{throw new Error("Canvas module not set")}};function Pa(n){Aa=n?.createCanvas,ua=n?.loadImage}function Ln(n){try{if(document.createElement("canvas").getContext("2d"))return{createCanvas:(e,a,r)=>{const i=document.createElement("canvas");return e!=null&&(i.width=e),a!=null&&(i.height=a),i},loadImage:(e,a)=>new Promise((r,i)=>{const o=document.createElement("img");a!==!1&&(o.crossOrigin="Anonymous"),o.onload=()=>{r(o)},o.onerror=i,o.src=e})}}catch(t){throw t}}let Ye;function xa(){return Ye===void 0&&(Ye=Ei()),Ye}let we=null;const Ri=n=>new Promise(t=>{if(Ue(n)!=="image/jpeg")return t(1);si.orientation(n).then(a=>t(a||1)).catch(()=>t(1))}),Oi=async()=>{if(we!==null)return!we;const t=await le("data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAAAAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/xABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAAAAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQvoP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXwH/9k=");return we=t.width===2&&t.height===3,!we},$i=n=>{const e=n.naturalWidth/n.naturalHeight;return n.naturalHeight<=8192&&n.naturalWidth<=8192?[n.naturalWidth,n.naturalHeight]:n.naturalHeight>n.naturalWidth?[e*8192,8192]:[8192,8192/e]},Ui=async n=>{const t=await Pi(n),e=await le(t),[a,r]=$i(e);if(!await Oi()){const A=ft(a,r);return A.getContext("2d")?.drawImage(e,0,0,a,r),A}const o=await Ri(n),[s,l]=o>4?[r,a]:[a,r],c=ft(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},ce=async n=>{const t=await Ui(n);return Ue(n)==="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"],Rt=["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"],Je=Rt.map(n=>[parseInt(n.substring(0,2),16),parseInt(n.substring(2,4),16),parseInt(n.substring(4,6),16)]);function Li(n){const t=re.indexOf(n);return t>=0?Rt[t]:""}function Vn(n){const t=Rt.indexOf(n);return t>=0?re[t]:""}function Vi(n,t=64){const e=[],a=[],r=Vn(n);r&&e.push({pms:r,hex:n,distance:0});const i=parseInt(n.substring(0,2),16),o=parseInt(n.substring(2,4),16),s=parseInt(n.substring(4,6),16);let l,c,d;for(let A=0;A<Rt.length;A++){l=Je[A][0],c=Je[A][1],d=Je[A][2];const u=Math.sqrt(Math.pow(i-l,2)+Math.pow(o-c,2)+Math.pow(s-d,2));a.push(u)}for(let A=0;A<a.length;A++)a[A]<=t&&!e.some(u=>u.pms===re[A])&&e.push({pms:re[A],hex:Rt[A],distance:a[A]});return e.sort((A,u)=>A.distance-u.distance)}const zi=re.map((n,t)=>({pms:n,hex:Rt[t]})),qi=new li(zi,{keys:["pms"]});function Gi(n,t){return qi.search(n,t?{limit:t}:void 0)}let Lt=null;function zn(n){if(n.startsWith("#"))return rn(n);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=n;const t=rn(Lt.fillStyle);return t||console.error(`Unknown browser color ${n}`),t}function rn(n){const t=n.substring(1).toUpperCase();return t.length===6?t:t.length===3?`${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`:""}const ye=n=>{const t=qn(n.spotColor);return t?`${n.browserValue} ${t}`:n.browserValue},qn=n=>{if(!n)return"";if(n.profileName.includes("/")&&n.profileName.includes(".icc")){const t=n.profileName.replace(/\s/g,"-"),e=t.lastIndexOf("/");return`icc-named-color(${t.slice(e+1).slice(0,-4)}, ${n.namedColor})`}return`icc-named-color(${n.profileName}, ${n.namedColor})`},ha=n=>{const t=n.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]}}},Wi=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],ji=["fill","stroke"],Ot=(n,t)=>{t(n),n.children.length>0&&Array.from(n.children).forEach(e=>Ot(e,t))},Hi=(n,t)=>{try{return n.matches(t)}catch{return n.classList.contains(t.substring(1))}},Ve=(n,t=!1)=>{!t&&n.setAttribute("preserveAspectRatio","none");const e=[];Ot(n,a=>{if(a.tagName==="script"){a.remove();return}if(a.tagName==="style"){try{bn.parse(a.innerHTML).stylesheet?.rules.forEach(o=>{e.push(o)}),a.remove()}catch(i){console.error(i)}return}const r=a.attributes.getNamedItem("style")?.value?.trim();if(r){const i=[];r.split(";").forEach(s=>{const l=s.trim();if(l){const[c,d]=l.split(":"),A=c.toLowerCase();ji.indexOf(A)>-1?a.setAttribute(A,d.trim()):i.push(l)}}),i.length>0?a.setAttribute("style",i.join(";")):a.removeAttribute("style")}}),Ot(n,a=>{e.forEach(r=>{r.selectors?.forEach(i=>{Hi(a,i)&&r.declarations?.forEach(o=>{o.property&&o.value&&a.setAttribute(o.property,o.value)})})})})},Yi=n=>{const t=/pt|pc|mm|cm|in/gm,e=n.getAttribute("viewBox"),a=n.getAttribute("width"),r=n.getAttribute("height");if(!e)throw new Error("viewBox not specified on SVG!");a&&n.setAttribute("width",a.replace(t,"")),r&&n.setAttribute("height",r.replace(t,""))},Gn=n=>lt().parseFromString(n,"image/svg+xml").firstElementChild,Ji=(n,t,e)=>{n.setAttribute("height",`${e}px`),n.setAttribute("width",`${t}px`)},Wn=(n,t,e)=>{Ot(n,a=>{const r=a.attributes.getNamedItem("fill");r&&r.value!=="none"&&a.classList.forEach(o=>{if(o.startsWith("spiff-fill")){const s=t[o.replace("spiff-fill-","")];if(s)a.setAttribute("fill",e?ye(s):s.browserValue);else{const l=t[o];l&&a.setAttribute("fill",e?ye(l):l.browserValue)}}});const i=a.attributes.getNamedItem("stroke");i&&i.value!=="none"&&a.classList.forEach(o=>{if(o.startsWith("spiff-stroke")){const s=t[o.replace("spiff-stroke-","")];if(s)a.setAttribute("stroke",e?ye(s):s.browserValue);else{const l=t[o];l&&a.setAttribute("fill",e?ye(l):l.browserValue)}}})})},jn=n=>St().serializeToString(n),Da=(n,t,e,a,r)=>{const i=Gn(n);if(!i)throw new Error("Failed to read SVG.");return Ji(i,t,e),Wn(i,a,r),jn(i)},ze=(n,t,e)=>{const a=Gn(n);if(!a)throw new Error("Failed to read SVG.");return Wn(a,t,e),jn(a)},Ki=n=>{const t=/<svg.*<\/svg>/s,e=n.match(t)||[],a=e?.length>0?e[0]:"";return lt().parseFromString(a,"image/svg+xml")},ot=async n=>{const e=Ki(n).firstElementChild;if(!e)throw new Error("Failed to read SVG.");Ve(e);const a={};Ot(e,o=>{Wi.includes(o.tagName)&&!o.attributes.getNamedItem("fill")&&o.setAttribute("fill","black");const s=o.attributes.getNamedItem("fill");if(s&&s.value!=="none"&&!s.value.startsWith("url(")){const c=ha(s.value),d=c.browserValue.replace(/\W/g,""),A=`spiff-fill-${d}`;o.setAttribute("fill",c.browserValue),o.classList.add(A),a[d]=c}const l=o.attributes.getNamedItem("stroke");if(l&&l.value!=="none"&&!l.value.startsWith("url(")){const c=ha(l.value),d=c.browserValue.replace(/\W/g,""),A=`spiff-stroke-${d}`;o.classList.add(A),o.setAttribute("stroke",c.browserValue),a[d]=c}});const i=St().serializeToString(e);return{colors:a,svg:i}},_i=w.gql`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const C=require("@apollo/client/core"),ri=require("@apollo/client/link/context"),ii=require("@apollo/client/link/error"),oi=require("preact-render-to-string"),si=require("@apollo/client/link/remove-typename"),li=require("exifr/dist/mini.umd.cjs"),Bn=require("css"),ci=require("fuse.js"),Ba=require("pith"),It=require("lodash.clonedeep"),In=require("qrcode"),di=require("svg-path-bbox"),la=require("opentype.js"),I=require("preact/jsx-runtime"),Ai=require("handlebars"),ui=require("data-uri-to-buffer"),Za=require("lodash.chunk"),fe=require("@aws-sdk/client-cognito-identity-provider"),hi=require("dinero.js"),gi=require("currency-codes"),De=require("lodash.isequal"),ca=require("unicode-default-word-boundary"),Pn=require("lodash.debounce");require("fs");require("path");const mi=require("lodash.omit");function pi(n){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(n){for(const e in n)if(e!=="default"){const a=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(t,e,a.get?a:{enumerable:!0,get:()=>n[e]})}}return t.default=n,Object.freeze(t)}const tn=pi(gi);var te=(n=>(n.Data="Data",n.Font="Font",n.Frame="Frame",n.Illustration="Illustration",n.Image="Image",n.Model="Model",n.Material="Material",n.Color="Color",n.QuestionnaireCollateral="QuestionnaireCollateral",n.RequestCollateral="RequestCollateral",n.SignupCollateral="SignupCollateral",n.Video="Video",n.ColorProfile="ColorProfile",n.Environment="Environment",n))(te||{}),$=(n=>(n.FileUpload="FileUpload",n.Option="Option",n.ColorOption="ColorOption",n.Text="Text",n))($||{}),E=(n=>(n.Information="Information",n.Bulk="Bulk",n.DigitalContent="DigitalContent",n.Finish="Finish",n.Frame="Frame",n.Illustration="Illustration",n.Introduction="Introduction",n.Material="Material",n.Model="Model",n.Module="Module",n.Picture="Picture",n.Photo="Photo",n.ProductOverlay="ProductOverlay",n.Question="Question",n.Shape="Shape",n.SilentIllustration="SilentIllustration",n.Text="Text",n))(E||{}),Dn=(n=>(n.Color="Color",n.Colors="Colors",n.Selection="Selection",n.Selections="Selections",n.Text="Text",n.Upload="Upload",n))(Dn||{}),Nt=(n=>(n.ThreeD="ThreeD",n.FreeDesign="FreeDesign",n.Print="Print",n))(Nt||{}),x=(n=>(n.Frame="frame",n.Group="group",n.Image="image",n.Pattern="pattern",n.Illustration="illustration",n.Textbox="textbox",n))(x||{}),Fn=(n=>(n.Default="Default",n.FirstTransaction="FirstTransaction",n.OneToOne="OneToOne",n))(Fn||{}),Ia=(n=>(n.Pending="Pending",n.Failed="Failed",n.Validated="Validated",n.Overridden="Overridden",n))(Ia||{}),xn=(n=>(n.Hyperlink="Hyperlink",n.Edit="Edit",n.Approve="Approve",n))(xn||{}),kn=(n=>(n.Hub="Hub",n.Shopify="Shopify",n))(kn||{}),Qe=(n=>(n.BackgroundRemover="BackgroundRemover",n.ConversionAccelerator="Conversion Accelerator",n.ProcessBuilder="ProcessBuilder",n))(Qe||{}),Mn=(n=>(n[n.Orbit=0]="Orbit",n[n.Pan=1]="Pan",n))(Mn||{}),ee=(n=>(n.Owner="Owner",n.Approver="Approver",n.Editor="Editor",n.Viewer="Viewer",n))(ee||{}),Pt=(n=>(n.Autosize="Autosize",n.Traditional="Traditional",n))(Pt||{}),W=(n=>(n[n.North=0]="North",n[n.Northeast=1]="Northeast",n[n.East=2]="East",n[n.Southeast=3]="Southeast",n[n.South=4]="South",n[n.Southwest=5]="Southwest",n[n.West=6]="West",n[n.Northwest=7]="Northwest",n))(W||{}),Tn=(n=>(n.Pixel="px",n.Millimeter="mm",n.Centimeter="cm",n))(Tn||{});class Nn extends Error{constructor(t){super(t),this.name=this.constructor.name}}class oe extends Nn{constructor(t){super(`ConfigurationError - ${t}`)}}class ae extends oe{constructor(t){super(`Option not Configured: ${t.stepTitle}`),this.optionId=t?.optionId||"N/A"}}class H extends oe{constructor(t){super(`Panel not Found: ${t.panelId}`),this.panelId=t?.panelId||"N/A"}}class pt extends oe{constructor(t){super(`Asset not found for variant: ${t.name}`),this.variant=t}}class Qt extends oe{constructor(t){super(`Resource not found for asset: ${t.name}`),this.asset=t}}class ne extends oe{constructor(t,e){super(`Workflow Misconfiguration: ${t.stepName} - ${e}`),this.step=t}}class Re extends Nn{constructor(t){super(`ImplementationError - ${t}`)}}class U extends Re{constructor(t){super(`Unhandled Behavior Encountered: ${t}`)}}class bt extends Re{constructor(t){super(`Parsing Error: ${t}`)}}class gt extends Re{constructor(t){super(`Client Error: ${t}`)}}class Oe extends Re{constructor(t){super(`Resource Generation Failed: ${t}`)}}class fi{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 en{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 Ci=()=>{try{return localStorage?new fi:new en}catch{return console.warn("Local storage was unavilable due to browser security settings. Using in-memory storage instead."),new en}},k=Ci();class wi{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 At=new wi;let da,Aa;function yi(n){da=n}function Si(n){Aa=n}function se(){return da?new da().window:(console.log("DOM constructor is not registered. Assuming browser environment. If not, please register DOM constructor before calling this function."),window)}function it(n,t){if(!Aa){if(typeof window<"u"&&window.fetch)return window.fetch(n,t);if(typeof global<"u"&&global.fetch)return global.fetch(n,t);throw new Error("Fetch implementation is not registered. Please register it before calling this function.")}return Aa(n,t)}const Qn=new Map,an=new Map,nn=new Map,Rn=async n=>{const t=an.get(n);if(t)return t;const a=(async()=>{const r=await it(n);return Qn.set(n,r.headers?.get("content-type")||""),await r.arrayBuffer()})();return an.set(n,a),a},vi=async n=>{const t=nn.get(n);if(t)return t;const a=(async()=>await(await it(n)).text())();return nn.set(n,a),a},Ut=n=>n.every(t=>t!=="undefined"),Ce=n=>Ut([typeof document])?document.createElement(n):se().document.createElement(n),Ei=(n,t)=>{if(Ut([typeof document]))return document.createElementNS(n,t);const a=se().document.createElement(t);return a.setAttribute("xmlns",n),a},lt=()=>{if(Ut([typeof DOMParser]))return new DOMParser;const n=se();return new n.DOMParser},bi=()=>Ut([typeof DOMParser])?DOMParser:se().DOMParser,$e=(n,t)=>new Promise((e,a)=>{t?Rn(n).then(e).catch(a):it(n).then(r=>{r.arrayBuffer().then(e).catch(a)}).catch(r=>{a(r)})}),at=(n,t)=>new Promise((e,a)=>{t?vi(n).then(e).catch(a):it(n).then(r=>{r.text().then(e).catch(a)}).catch(a)}),On=n=>oi.renderToStaticMarkup(n),Ye=new Map,Bi=async(n,t)=>{if(Ut([typeof FontFace])){if(Ye.has(t))return Ye.get(t);const e=n.names.fullName.en,a=new FontFace(e,`url(${t})`);document.fonts.add(a);const r=a.load();return Ye.set(t,r),r}},St=()=>{if(Ut([typeof XMLSerializer]))return new XMLSerializer;const n=se();return new n.XMLSerializer},rn=n=>btoa(n),Ue=n=>{function t(){const a=new Uint8Array(n),r=4;if(a.length>=r){const i=new Array(r);for(let l=0;l<r;l++)i[l]=new Uint8Array(n)[l].toString(16);const o=i.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"},Ii=async n=>{const t=await Rn(n),e=Qn.get(n)||Ue(t);return await Fi(new Blob([t],{type:e}))},Pi=n=>{let t="";const e=n.byteLength;for(let a=0;a<e;a++)t+=String.fromCharCode(n[a]);return t},Di=async n=>{const t=Ue(n),e=new Uint8Array(n),a=Pi(e),r=btoa(a);return`data:${t};base64,${r}`},Le=n=>`data:image/svg+xml;base64,${btoa(n)}`,$n=n=>{const t=n.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 r=!1;for(let o=1;o<a.length;o++)a[o]==="base64"&&(r=!0);const i=decodeURI(t.substring(e+1));return r?new Uint8Array(atob(i).split("").map(s=>s.charCodeAt(0))).buffer:new Uint8Array(i.split("").map(s=>s.charCodeAt(0))).buffer},Fi=n=>new Promise((t,e)=>{const a=new FileReader;a.onload=function(r){const i=r.target;!i||!i.result?e():t(i.result.toString())},a.readAsDataURL(n)});let xi,Pa;const ki=n=>{Pa=n},Mi=()=>Pa;let Un;const Ln=n=>{Un=n},Ti=()=>new Promise(n=>{const t=At.getHubUrl(),e=a=>{a.origin===t&&(window.removeEventListener("message",e),n(a.data))};window.parent!==window&&(window.addEventListener("message",e,!1),window.parent.postMessage("ready",t))}),Ni=async()=>{const n={applicationKey:Pa,customerToken:xi,bearer:Un};return typeof window<"u"&&(window.location.href.includes("/workflows/product/")||window.location.href.includes("hub=true"))?{...await Ti(),...n}:n};async function Qi(n,t){const e=At.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 r=await it(n,{...t,redirect:"manual"});return r.type==="opaqueredirect"&&(typeof n!="string"&&"url"in n?r=await it({...n,url:`${a}/graphql`},t):r=await it(`${a}/graphql`,t)),r}class Ri{constructor(){this.shadowGraphqlClient=this.constructShadowGraphqlClient(),At.addServerUrlCallback(()=>{this.shadowGraphqlClient=this.constructShadowGraphqlClient()})}setSpiffCommerceClient(t){this.spiffClient=t,this.shadowGraphqlClient=this.constructShadowGraphqlClient()}getShadowGraphqlClient(){return this.shadowGraphqlClient}constructShadowGraphqlClient(){const t=C.createHttpLink({uri:`${At.getServerUrl()}/graphql`,fetch:Qi}),e=ri.setContext(async(i,o)=>{const{headers:s}=o,l=s||{},c=await Ni();let d=o.bearer??c.bearer;if(this.spiffClient)try{d=await this.spiffClient.loggedInBearerToken()}catch{}const A=o.partnerId??c.partnerId,u=o.activeIntegration??c.activeIntegration,h=o.transactionOwnerId,g=o.customerToken??c.customerToken,p=o.applicationKey??c.applicationKey,m=o.bundleOwnerId;try{if(window&&window.__SENTRY__){const f=window.__SENTRY__.hub;if(f){const v=f.traceHeaders();Object.entries(v).forEach(([b,D])=>{l[b]=D})}}}catch{}return d&&(l.Authorization=`Bearer ${d}`),A&&(l.partnerId=A),u&&(l.activeIntegration=u),h&&(l.transactionOwnerId=h),g&&(l.customerToken=g),p&&(l["X-Application-Key"]=p),m&&(l.bundleOwnerId=m),l["Allow-Moonlight-Redirect"]="true",{headers:l}}),a=ii.onError(({operation:i,graphQLErrors:o,networkError:s})=>{const l=o||[],c=i.getContext();s&&!c?.fetchOptions?.signal?.aborted&&console.log("GraphQL Network error"),l.forEach(()=>console.log("GraphQL Error: "+i.operationName))}),r=si.removeTypenameFromVariables();return new C.ApolloClient({link:C.from([r,a,e,t]),cache:new C.InMemoryCache,name:"Core"})}}const y=new Ri;let ua,ha;const ft=(n,t,e)=>{if(ua!==void 0)return ua(n,t,e);try{const a=Vn(!0);return Da(a),a.createCanvas(n,t,e)}catch{throw new Error("Canvas module not set")}},le=(n,t)=>{if(ha!==void 0)return ha(n,t);try{const e=Vn(!0);return Da(e),e.loadImage(n,t)}catch{throw new Error("Canvas module not set")}};function Da(n){ua=n?.createCanvas,ha=n?.loadImage}function Vn(n){try{if(document.createElement("canvas").getContext("2d"))return{createCanvas:(e,a,r)=>{const i=document.createElement("canvas");return e!=null&&(i.width=e),a!=null&&(i.height=a),i},loadImage:(e,a)=>new Promise((r,i)=>{const o=document.createElement("img");a!==!1&&(o.crossOrigin="Anonymous"),o.onload=()=>{r(o)},o.onerror=i,o.src=e})}}catch(t){throw t}}let Je;function Fa(){return Je===void 0&&(Je=bi()),Je}let we=null;const Oi=n=>new Promise(t=>{if(Ue(n)!=="image/jpeg")return t(1);li.orientation(n).then(a=>t(a||1)).catch(()=>t(1))}),$i=async()=>{if(we!==null)return!we;const t=await le("data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAAAAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/xABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAAAAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQvoP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXwH/9k=");return we=t.width===2&&t.height===3,!we},Ui=n=>{const e=n.naturalWidth/n.naturalHeight;return n.naturalHeight<=8192&&n.naturalWidth<=8192?[n.naturalWidth,n.naturalHeight]:n.naturalHeight>n.naturalWidth?[e*8192,8192]:[8192,8192/e]},Li=async n=>{const t=await Di(n),e=await le(t),[a,r]=Ui(e);if(!await $i()){const A=ft(a,r);return A.getContext("2d")?.drawImage(e,0,0,a,r),A}const o=await Oi(n),[s,l]=o>4?[r,a]:[a,r],c=ft(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},ce=async n=>{const t=await Li(n);return Ue(n)==="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"],Rt=["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"],Ke=Rt.map(n=>[parseInt(n.substring(0,2),16),parseInt(n.substring(2,4),16),parseInt(n.substring(4,6),16)]);function Vi(n){const t=re.indexOf(n);return t>=0?Rt[t]:""}function zn(n){const t=Rt.indexOf(n);return t>=0?re[t]:""}function zi(n,t=64){const e=[],a=[],r=zn(n);r&&e.push({pms:r,hex:n,distance:0});const i=parseInt(n.substring(0,2),16),o=parseInt(n.substring(2,4),16),s=parseInt(n.substring(4,6),16);let l,c,d;for(let A=0;A<Rt.length;A++){l=Ke[A][0],c=Ke[A][1],d=Ke[A][2];const u=Math.sqrt(Math.pow(i-l,2)+Math.pow(o-c,2)+Math.pow(s-d,2));a.push(u)}for(let A=0;A<a.length;A++)a[A]<=t&&!e.some(u=>u.pms===re[A])&&e.push({pms:re[A],hex:Rt[A],distance:a[A]});return e.sort((A,u)=>A.distance-u.distance)}const qi=re.map((n,t)=>({pms:n,hex:Rt[t]})),Gi=new ci(qi,{keys:["pms"]});function Wi(n,t){return Gi.search(n,t?{limit:t}:void 0)}let Lt=null;function qn(n){if(n.startsWith("#"))return on(n);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=n;const t=on(Lt.fillStyle);return t||console.error(`Unknown browser color ${n}`),t}function on(n){const t=n.substring(1).toUpperCase();return t.length===6?t:t.length===3?`${t[0]}${t[0]}${t[1]}${t[1]}${t[2]}${t[2]}`:""}const ye=n=>{const t=Gn(n.spotColor);return t?`${n.browserValue} ${t}`:n.browserValue},Gn=n=>{if(!n)return"";if(n.profileName.includes("/")&&n.profileName.includes(".icc")){const t=n.profileName.replace(/\s/g,"-"),e=t.lastIndexOf("/");return`icc-named-color(${t.slice(e+1).slice(0,-4)}, ${n.namedColor})`}return`icc-named-color(${n.profileName}, ${n.namedColor})`},ga=n=>{const t=n.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]}}},ji=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],Hi=["fill","stroke"],Ot=(n,t)=>{t(n),n.children.length>0&&Array.from(n.children).forEach(e=>Ot(e,t))},Yi=(n,t)=>{try{return n.matches(t)}catch{return n.classList.contains(t.substring(1))}},Ve=(n,t=!1)=>{!t&&n.setAttribute("preserveAspectRatio","none");const e=[];Ot(n,a=>{if(a.tagName==="script"){a.remove();return}if(a.tagName==="style"){try{Bn.parse(a.innerHTML).stylesheet?.rules.forEach(o=>{e.push(o)}),a.remove()}catch(i){console.error(i)}return}const r=a.attributes.getNamedItem("style")?.value?.trim();if(r){const i=[];r.split(";").forEach(s=>{const l=s.trim();if(l){const[c,d]=l.split(":"),A=c.toLowerCase();Hi.indexOf(A)>-1?a.setAttribute(A,d.trim()):i.push(l)}}),i.length>0?a.setAttribute("style",i.join(";")):a.removeAttribute("style")}}),Ot(n,a=>{e.forEach(r=>{r.selectors?.forEach(i=>{Yi(a,i)&&r.declarations?.forEach(o=>{o.property&&o.value&&a.setAttribute(o.property,o.value)})})})})},Ji=n=>{const t=/pt|pc|mm|cm|in/gm,e=n.getAttribute("viewBox"),a=n.getAttribute("width"),r=n.getAttribute("height");if(!e)throw new Error("viewBox not specified on SVG!");a&&n.setAttribute("width",a.replace(t,"")),r&&n.setAttribute("height",r.replace(t,""))},Wn=n=>lt().parseFromString(n,"image/svg+xml").firstElementChild,Ki=(n,t,e)=>{n.setAttribute("height",`${e}px`),n.setAttribute("width",`${t}px`)},jn=(n,t,e)=>{Ot(n,a=>{const r=a.attributes.getNamedItem("fill");r&&r.value!=="none"&&a.classList.forEach(o=>{if(o.startsWith("spiff-fill")){const s=t[o.replace("spiff-fill-","")];if(s)a.setAttribute("fill",e?ye(s):s.browserValue);else{const l=t[o];l&&a.setAttribute("fill",e?ye(l):l.browserValue)}}});const i=a.attributes.getNamedItem("stroke");i&&i.value!=="none"&&a.classList.forEach(o=>{if(o.startsWith("spiff-stroke")){const s=t[o.replace("spiff-stroke-","")];if(s)a.setAttribute("stroke",e?ye(s):s.browserValue);else{const l=t[o];l&&a.setAttribute("fill",e?ye(l):l.browserValue)}}})})},Hn=n=>St().serializeToString(n),xa=(n,t,e,a,r)=>{const i=Wn(n);if(!i)throw new Error("Failed to read SVG.");return Ki(i,t,e),jn(i,a,r),Hn(i)},ze=(n,t,e)=>{const a=Wn(n);if(!a)throw new Error("Failed to read SVG.");return jn(a,t,e),Hn(a)},_i=n=>{const t=/<svg.*<\/svg>/s,e=n.match(t)||[],a=e?.length>0?e[0]:"";return lt().parseFromString(a,"image/svg+xml")},ot=async n=>{const e=_i(n).firstElementChild;if(!e)throw new Error("Failed to read SVG.");Ve(e);const a={};Ot(e,o=>{ji.includes(o.tagName)&&!o.attributes.getNamedItem("fill")&&o.setAttribute("fill","black");const s=o.attributes.getNamedItem("fill");if(s&&s.value!=="none"&&!s.value.startsWith("url(")){const c=ga(s.value),d=c.browserValue.replace(/\W/g,""),A=`spiff-fill-${d}`;o.setAttribute("fill",c.browserValue),o.classList.add(A),a[d]=c}const l=o.attributes.getNamedItem("stroke");if(l&&l.value!=="none"&&!l.value.startsWith("url(")){const c=ga(l.value),d=c.browserValue.replace(/\W/g,""),A=`spiff-stroke-${d}`;o.classList.add(A),o.setAttribute("stroke",c.browserValue),a[d]=c}});const i=St().serializeToString(e);return{colors:a,svg:i}},Xi=C.gql`
2
2
  fragment AssetMetadataFields on Asset {
3
3
  metadata {
4
4
  key
5
5
  value
6
6
  }
7
7
  }
8
- `,de=n=>w.gql`
9
- ${n&&_i||""}
8
+ `,de=n=>C.gql`
9
+ ${n&&Xi||""}
10
10
  fragment AssetFields on Asset {
11
11
  name
12
12
  key
@@ -48,14 +48,14 @@
48
48
  }
49
49
  ${n&&"...AssetMetadataFields"||""}
50
50
  }
51
- `,Xi=w.gql`
51
+ `,Zi=C.gql`
52
52
  ${de(!1)}
53
53
  query GetAssets($keys: [String]!) {
54
54
  assets(keys: $keys) {
55
55
  ...AssetFields
56
56
  }
57
57
  }
58
- `,Fa=w.gql`
58
+ `,ka=C.gql`
59
59
  fragment MaterialFields on Material {
60
60
  id
61
61
  name
@@ -102,14 +102,14 @@
102
102
  fileLink
103
103
  }
104
104
  }
105
- `,Zi=w.gql`
106
- ${Fa}
105
+ `,to=C.gql`
106
+ ${ka}
107
107
  query GetMaterials($ids: [String]) {
108
108
  materials(id: $ids) {
109
109
  ...MaterialFields
110
110
  }
111
111
  }
112
- `,to=w.gql`
112
+ `,eo=C.gql`
113
113
  mutation CreateAsset($name: String!, $type: String!, $mimeType: String!, $anonymous: Boolean, $temporary: Boolean) {
114
114
  assetCreate(name: $name, type: $type, mimeType: $mimeType, anonymous: $anonymous, temporary: $temporary) {
115
115
  uploadUrl
@@ -123,14 +123,14 @@
123
123
  }
124
124
  }
125
125
  }
126
- `,eo=w.gql`
126
+ `,ao=C.gql`
127
127
  ${de(!1)}
128
128
  mutation RemoveBackgroundFromAsset($key: String!) {
129
129
  assetRemoveBackground(key: $key) {
130
130
  ...AssetFields
131
131
  }
132
132
  }
133
- `,De=async n=>(await y.getShadowGraphqlClient().query({query:Xi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{keys:n}})).data.assets,ao=async n=>(await y.getShadowGraphqlClient().query({query:Zi,errorPolicy:"all",variables:{ids:n}})).data.materials,no=async(n,t,e,a,r)=>(await y.getShadowGraphqlClient().mutate({mutation:to,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:n,type:t,mimeType:e,anonymous:a,temporary:r}})).data?.assetCreate;class ro{constructor(){this.cache=new Map,this.bgrmProcessCache=new Map,this.materialCache=new Map,this.loadImageAsFileInfo=async t=>{const e=await t.arrayBuffer(),a=await ce(e),r=(i,o)=>{const s=atob(i.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:r(a.dataUrl,t.type)}}}async getLocalOrFromServer(t){if(this.cache.has(t)){const r=this.cache.get(t);if(!r)throw new L("Failed to get asset from cache!");return r}const a=(async()=>(await De([t]))[0])();return this.cache.set(t,a),a}async getFromServer(t){const a=(async()=>(await De([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 L("Asset has no key!");this.cache.has(t.key)||this.cache.set(t.key,Promise.resolve(t))}cacheMaterial(t){if(!t.id)throw new L("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 ao([t]))[0])();return this.materialCache.set(t,a),a}async uploadAssetWithProgress(t,e,a,r,i){const o=await this.dispatchCreateAssetRequest(t,e,r,i);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,r){return this.uploadAssetWithProgress(t,e,()=>{},a,r)}async uploadFile(t,e){const r=this.isRaster(t)?te.Image:te.Illustration,i=await this.loadImageAsFileInfo(t);return await this.uploadAssetWithProgress(i,r,e,!0)}async removeBackgroundFromAsset(t){const e=t.key;if(this.bgrmProcessCache.has(e))return this.bgrmProcessCache.get(e);if(J.has(e)){const i=this.getLocalOrFromServer(J.get(e));return this.bgrmProcessCache.set(e,i),i}const r=(async()=>{const i=await y.getShadowGraphqlClient().mutate({mutation:eo,fetchPolicy:"no-cache",errorPolicy:"all",variables:{key:e}});if(this.bgrmProcessCache.delete(e),!i.data?.assetRemoveBackground?.key)throw new Error("Failed to remove background from image");return ut.add(i.data.assetRemoveBackground),J.add(e,i.data.assetRemoveBackground.key),this.cache.set(i.data.assetRemoveBackground.key,Promise.resolve(i.data.assetRemoveBackground)),i.data.assetRemoveBackground})();return this.bgrmProcessCache.set(e,r),r}removePersistedAsset(t){ut.remove(t),J.delete(t),J.deleteForBgRemovedKey(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.");Yi(o);const l=St().serializeToString(o);return{name:t.name,blob:new Blob([l],{type:"image/svg+xml"})}}return t}async dispatchCreateAssetRequest(t,e,a,r){const i=t.blob.type?t.blob.type:this.guessMIME(t.name),o=await no(t.name,e,i,a,r);if(o)return{assetResponse:o,mimeType:i}}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 L("Unexpected mimetype: "+e)}}}const Vt="persistentAssets",ct=class ct{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=k.getMap(Vt);a&&a.forEach((r,i)=>{e.set(i,r)}),k.setMap(Vt,e),ct.executeCallbacks()}static remove(t){const e=k.getMap(Vt);if(!e)return;const a=Array.from(e.entries()).find(r=>r[0]===t);a&&(e.delete(a[0]),k.setMap(Vt,e),ct.executeCallbacks())}static list(){const t=k.getMap(Vt);return t?Array.from(t.entries()).map(e=>({assetKey:e[0],src:e[1]})):[]}static addCallback(t){ct.callbacks.push(t)}static removeCallback(t){ct.callbacks=ct.callbacks.filter(e=>e!==t)}static executeCallbacks(){ct.callbacks.forEach(t=>t())}};ct.callbacks=[];let ut=ct;const on="bgrmPersistentAssets";class J{static has(t){return J.getMap().has(t)}static get(t){return J.getMap().get(t)}static keys(){return J.getMap().keys()}static values(){return J.getMap().values()}static add(t,e){const a=J.getMap();a.set(t,e),J.setMap(a)}static delete(t){const e=J.getMap();e.delete(t),J.setMap(e)}static deleteForBgRemovedKey(t){const e=J.getMap(),a=Array.from(e.keys()).find(r=>e.get(r)===t);a&&(e.delete(a),J.setMap(e))}static getMap(){return k.getMap(on)||new Map}static setMap(t){k.setMap(on,t)}}const R=new ro;class io{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 $t=new io,Hn=w.gql`
133
+ `,Fe=async n=>(await y.getShadowGraphqlClient().query({query:Zi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{keys:n}})).data.assets,no=async n=>(await y.getShadowGraphqlClient().query({query:to,errorPolicy:"all",variables:{ids:n}})).data.materials,ro=async(n,t,e,a,r)=>(await y.getShadowGraphqlClient().mutate({mutation:eo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:n,type:t,mimeType:e,anonymous:a,temporary:r}})).data?.assetCreate;class io{constructor(){this.cache=new Map,this.bgrmProcessCache=new Map,this.materialCache=new Map,this.loadImageAsFileInfo=async t=>{const e=await t.arrayBuffer(),a=await ce(e),r=(i,o)=>{const s=atob(i.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:r(a.dataUrl,t.type)}}}async getLocalOrFromServer(t){if(this.cache.has(t)){const r=this.cache.get(t);if(!r)throw new U("Failed to get asset from cache!");return r}const a=(async()=>(await Fe([t]))[0])();return this.cache.set(t,a),a}async getFromServer(t){const a=(async()=>(await Fe([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 U("Asset has no key!");this.cache.has(t.key)||this.cache.set(t.key,Promise.resolve(t))}cacheMaterial(t){if(!t.id)throw new U("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 no([t]))[0])();return this.materialCache.set(t,a),a}async uploadAssetWithProgress(t,e,a,r,i){const o=await this.dispatchCreateAssetRequest(t,e,r,i);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,r){return this.uploadAssetWithProgress(t,e,()=>{},a,r)}async uploadFile(t,e){const r=this.isRaster(t)?te.Image:te.Illustration,i=await this.loadImageAsFileInfo(t);return await this.uploadAssetWithProgress(i,r,e,!0)}async removeBackgroundFromAsset(t){const e=t.key;if(this.bgrmProcessCache.has(e))return this.bgrmProcessCache.get(e);if(J.has(e)){const i=this.getLocalOrFromServer(J.get(e));return this.bgrmProcessCache.set(e,i),i}const r=(async()=>{const i=await y.getShadowGraphqlClient().mutate({mutation:ao,fetchPolicy:"no-cache",errorPolicy:"all",variables:{key:e}});if(this.bgrmProcessCache.delete(e),!i.data?.assetRemoveBackground?.key)throw new Error("Failed to remove background from image");return ut.add(i.data.assetRemoveBackground),J.add(e,i.data.assetRemoveBackground.key),this.cache.set(i.data.assetRemoveBackground.key,Promise.resolve(i.data.assetRemoveBackground)),i.data.assetRemoveBackground})();return this.bgrmProcessCache.set(e,r),r}removePersistedAsset(t){ut.remove(t),J.delete(t),J.deleteForBgRemovedKey(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.");Ji(o);const l=St().serializeToString(o);return{name:t.name,blob:new Blob([l],{type:"image/svg+xml"})}}return t}async dispatchCreateAssetRequest(t,e,a,r){const i=t.blob.type?t.blob.type:this.guessMIME(t.name),o=await ro(t.name,e,i,a,r);if(o)return{assetResponse:o,mimeType:i}}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 U("Unexpected mimetype: "+e)}}}const Vt="persistentAssets",ct=class ct{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=k.getMap(Vt);a&&a.forEach((r,i)=>{e.set(i,r)}),k.setMap(Vt,e),ct.executeCallbacks()}static remove(t){const e=k.getMap(Vt);if(!e)return;const a=Array.from(e.entries()).find(r=>r[0]===t);a&&(e.delete(a[0]),k.setMap(Vt,e),ct.executeCallbacks())}static list(){const t=k.getMap(Vt);return t?Array.from(t.entries()).map(e=>({assetKey:e[0],src:e[1]})):[]}static addCallback(t){ct.callbacks.push(t)}static removeCallback(t){ct.callbacks=ct.callbacks.filter(e=>e!==t)}static executeCallbacks(){ct.callbacks.forEach(t=>t())}};ct.callbacks=[];let ut=ct;const sn="bgrmPersistentAssets";class J{static has(t){return J.getMap().has(t)}static get(t){return J.getMap().get(t)}static keys(){return J.getMap().keys()}static values(){return J.getMap().values()}static add(t,e){const a=J.getMap();a.set(t,e),J.setMap(a)}static delete(t){const e=J.getMap();e.delete(t),J.setMap(e)}static deleteForBgRemovedKey(t){const e=J.getMap(),a=Array.from(e.keys()).find(r=>e.get(r)===t);a&&(e.delete(a),J.setMap(e))}static getMap(){return k.getMap(sn)||new Map}static setMap(t){k.setMap(sn,t)}}const R=new io;class oo{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 $t=new oo,Yn=C.gql`
134
134
  fragment OptionFields on Option {
135
135
  id
136
136
  name
@@ -167,16 +167,16 @@
167
167
  ...AssetFields
168
168
  }
169
169
  }
170
- `,oo=w.gql`
170
+ `,so=C.gql`
171
171
  ${de(!1)}
172
- ${Fa}
173
- ${Hn}
172
+ ${ka}
173
+ ${Yn}
174
174
  query GetOptions($ids: [String]!) {
175
175
  options(ids: $ids) {
176
176
  ...OptionFields
177
177
  }
178
178
  }
179
- `,so=async n=>{const t=await y.getShadowGraphqlClient().query({query:oo,errorPolicy:"all",variables:{ids:n}});return t.data.options.forEach(e=>{e.defaultVariant?.asset&&R.cacheAsset(e.defaultVariant.asset),e.colorProfile&&R.cacheAsset(e.colorProfile),e.variants?.forEach(a=>{a.asset&&R.cacheAsset(a.asset),a.thumbnail&&R.cacheAsset(a.thumbnail),a.material&&R.cacheMaterial(a.material)})}),t.data.options},lo=async(n,t)=>(await t).find(a=>a.id===n),co=async n=>{const t=n.map(o=>$t.get({id:o})),e=n.filter((o,s)=>t[s]===void 0);if(e.length===0)return Promise.all(t);const a=so(e),r=e.map(o=>$t.set({id:o},lo(o,a))),i=t.filter(o=>o!==void 0);return await Promise.all(i.concat(r))};class Ao{constructor(){this.getSelectedVariant=(t,e)=>{if(!(!t||e.length===0))return t.variants?.find(a=>a.id===e[0])}}async getOption(t){return(async()=>{const r=(await co([t]))[0];if(r)return r})()}async getAssetTileImageForVariant(t){const e=t.thumbnail;if(e){const r=e.versions?.find(o=>o.name==="thumbnail"),i=e.fileLink;return r?.link||i}const a=t.asset;if(a){const r=a.versions?.find(o=>o.name==="thumbnail"),i=a.fileLink;return r?.link||i}return t.material?t.material.id:""}getDefaultVariant(t){const e=t.variants;if(e){if(e.length===1)return e[0];if(t.defaultVariant!==void 0)return e.find(a=>a.id===t.defaultVariant?.id)}}}const W=new Ao,Yn=w.gql`
179
+ `,lo=async n=>{const t=await y.getShadowGraphqlClient().query({query:so,errorPolicy:"all",variables:{ids:n}});return t.data.options.forEach(e=>{e.defaultVariant?.asset&&R.cacheAsset(e.defaultVariant.asset),e.colorProfile&&R.cacheAsset(e.colorProfile),e.variants?.forEach(a=>{a.asset&&R.cacheAsset(a.asset),a.thumbnail&&R.cacheAsset(a.thumbnail),a.material&&R.cacheMaterial(a.material)})}),t.data.options},co=async(n,t)=>(await t).find(a=>a.id===n),Ao=async n=>{const t=n.map(o=>$t.get({id:o})),e=n.filter((o,s)=>t[s]===void 0);if(e.length===0)return Promise.all(t);const a=lo(e),r=e.map(o=>$t.set({id:o},co(o,a))),i=t.filter(o=>o!==void 0);return await Promise.all(i.concat(r))};class uo{constructor(){this.getSelectedVariant=(t,e)=>{if(!(!t||e.length===0))return t.variants?.find(a=>a.id===e[0])}}async getOption(t){return(async()=>{const r=(await Ao([t]))[0];if(r)return r})()}async getAssetTileImageForVariant(t){const e=t.thumbnail;if(e){const r=e.versions?.find(o=>o.name==="thumbnail"),i=e.fileLink;return r?.link||i}const a=t.asset;if(a){const r=a.versions?.find(o=>o.name==="thumbnail"),i=a.fileLink;return r?.link||i}return t.material?t.material.id:""}getDefaultVariant(t){const e=t.variants;if(e){if(e.length===1)return e[0];if(t.defaultVariant!==void 0)return e.find(a=>a.id===t.defaultVariant?.id)}}}const j=new uo,Jn=C.gql`
180
180
  fragment ActiveIntegrationFields on Integration {
181
181
  id
182
182
  logo
@@ -195,7 +195,7 @@
195
195
  currencyCode
196
196
  }
197
197
  }
198
- `,qe=w.gql`
198
+ `,qe=C.gql`
199
199
  fragment AdditionalIntegrationProductFields on IntegrationProduct {
200
200
  id
201
201
  product {
@@ -213,7 +213,7 @@
213
213
  preloadImageUrl
214
214
  }
215
215
  }
216
- `,uo=w.gql`
216
+ `,ho=C.gql`
217
217
  ${qe}
218
218
  mutation CreateTransactions(
219
219
  $inputs: [TransactionCreateInput]!
@@ -304,7 +304,7 @@
304
304
  }
305
305
  }
306
306
  }
307
- `,Jn=w.gql`
307
+ `,Kn=C.gql`
308
308
  fragment StakeholderFields on Stakeholder {
309
309
  id
310
310
  type
@@ -312,7 +312,7 @@
312
312
  authorizationNote
313
313
  authorizationStatus
314
314
  }
315
- `,Kn=w.gql`
315
+ `,_n=C.gql`
316
316
  fragment TransactionShareActionFields on TransactionShareAction {
317
317
  id
318
318
  title
@@ -321,11 +321,11 @@
321
321
  precedence
322
322
  url
323
323
  }
324
- `,ho=w.gql`
324
+ `,go=C.gql`
325
325
  ${qe}
326
- ${Jn}
327
326
  ${Kn}
328
- ${Yn}
327
+ ${_n}
328
+ ${Jn}
329
329
  query ReadTransactions($ids: [String]!) {
330
330
  transactions(ids: $ids) {
331
331
  customLogoLink
@@ -488,19 +488,19 @@
488
488
  }
489
489
  }
490
490
  }
491
- `,go=w.gql`
491
+ `,mo=C.gql`
492
492
  mutation UpdateTransactionWorkflowState($id: String!, $workflowState: String!) {
493
493
  transactionUpdate(id: $id, workflowState: $workflowState) {
494
494
  id
495
495
  }
496
496
  }
497
- `,mo=w.gql`
497
+ `,po=C.gql`
498
498
  mutation UpdateTransactionQuantity($id: String!, $quantity: Int) {
499
499
  transactionUpdate(id: $id, quantity: $quantity) {
500
500
  id
501
501
  }
502
502
  }
503
- `,po=w.gql`
503
+ `,fo=C.gql`
504
504
  query ReadConversionConfigurationQuery($id: String!) {
505
505
  conversionConfiguration(id: $id) {
506
506
  id
@@ -518,7 +518,7 @@
518
518
  mandatory
519
519
  }
520
520
  }
521
- `,fo=w.gql`
521
+ `,Co=C.gql`
522
522
  query ReadTransactionForDesignCreation($id: String!) {
523
523
  transactions(ids: [$id]) {
524
524
  id
@@ -588,8 +588,8 @@
588
588
  workflowViewerReadOnlyLink
589
589
  }
590
590
  }
591
- `,Co=w.gql`
592
- ${Kn}
591
+ `,wo=C.gql`
592
+ ${_n}
593
593
  query ReadTransactionForShareActions($id: String!) {
594
594
  transactions(ids: [$id]) {
595
595
  id
@@ -599,14 +599,14 @@
599
599
  }
600
600
  }
601
601
  }
602
- `,_n=w.gql`
602
+ `,Xn=C.gql`
603
603
  query ReadWorkflowStates($ids: [String]!) {
604
604
  transactions(ids: $ids) {
605
605
  id
606
606
  workflowState
607
607
  }
608
608
  }
609
- `,Xn=n=>w.gql`
609
+ `,Zn=n=>C.gql`
610
610
  ${qe}
611
611
  fragment IntegrationProductFields on IntegrationProduct {
612
612
  id
@@ -689,15 +689,15 @@
689
689
  `:""}
690
690
  }
691
691
  }
692
- `,wo=n=>w.gql`
693
- ${Xn(n)}
692
+ `,yo=n=>C.gql`
693
+ ${Zn(n)}
694
694
  query GetIntegrationProducts($ids: [String!]!) {
695
695
  integrationProducts(ids: $ids) {
696
696
  ...IntegrationProductFields
697
697
  }
698
698
  }
699
- `,yo=n=>w.gql`
700
- ${Xn(n)}
699
+ `,So=n=>C.gql`
700
+ ${Zn(n)}
701
701
  query GetIntegrationProductFromExternalIds($externalIntegrationId: String!, $externalProductId: String!) {
702
702
  integrationProductFromExternalIds(
703
703
  externalIntegrationId: $externalIntegrationId
@@ -706,8 +706,8 @@
706
706
  ...IntegrationProductFields
707
707
  }
708
708
  }
709
- `,So=w.gql`
710
- ${Jn}
709
+ `,vo=C.gql`
710
+ ${Kn}
711
711
  query ReadTransactionForStakeholders($id: String!) {
712
712
  transactions(ids: [$id]) {
713
713
  stakeholders {
@@ -718,11 +718,11 @@
718
718
  }
719
719
  }
720
720
  }
721
- `,vo=w.gql`
721
+ `,Eo=C.gql`
722
722
  mutation FinalizeUpdateTransaction($transactionId: String!) {
723
723
  transactionFinalizeUpdate(transactionId: $transactionId)
724
724
  }
725
- `,Eo=w.gql`
725
+ `,bo=C.gql`
726
726
  fragment RegionFields on Region {
727
727
  width
728
728
  top
@@ -740,7 +740,7 @@
740
740
  height
741
741
  }
742
742
  }
743
- `,bo=w.gql`
743
+ `,Bo=C.gql`
744
744
  fragment LookAtAnimationFields on LookAtAnimation {
745
745
  latDeg
746
746
  lonDeg
@@ -751,7 +751,7 @@
751
751
  z
752
752
  }
753
753
  }
754
- `,Bo=w.gql`
754
+ `,Io=C.gql`
755
755
  fragment RenderingPipelineConfigurationFields on RenderingPipelineConfiguration {
756
756
  antiAliasing {
757
757
  samples
@@ -835,21 +835,21 @@
835
835
  weight
836
836
  }
837
837
  }
838
- `,Io=w.gql`
838
+ `,Po=C.gql`
839
839
  fragment ModelAnimationFields on ModelAnimation {
840
840
  from
841
841
  to
842
842
  loop
843
843
  name
844
844
  }
845
- `,Po=n=>w.gql`
845
+ `,Do=n=>C.gql`
846
846
  ${de(n)}
847
- ${Fa}
848
- ${Hn}
849
- ${Eo}
847
+ ${ka}
848
+ ${Yn}
850
849
  ${bo}
851
850
  ${Bo}
852
851
  ${Io}
852
+ ${Po}
853
853
  query GetWorkflows($ids: [String!]!) {
854
854
  workflows(ids: $ids) {
855
855
  partner {
@@ -1244,7 +1244,7 @@
1244
1244
  }
1245
1245
  }
1246
1246
  }
1247
- `,xo=w.gql`
1247
+ `,Fo=C.gql`
1248
1248
  query GetTransactionForPartner($id: String!) {
1249
1249
  transactions(ids: [$id]) {
1250
1250
  id
@@ -1262,7 +1262,7 @@
1262
1262
  }
1263
1263
  }
1264
1264
  }
1265
- `,Do=w.gql`
1265
+ `,xo=C.gql`
1266
1266
  ${de(!1)}
1267
1267
  query GetWorkflowForTheme($id: String!) {
1268
1268
  workflow(id: $id) {
@@ -1284,7 +1284,7 @@
1284
1284
  }
1285
1285
  }
1286
1286
  }
1287
- `,Ge=w.gql`
1287
+ `,Ge=C.gql`
1288
1288
  fragment MarketplaceThemeInstallConfigurationFields on MarketplaceThemeInstallConfiguration {
1289
1289
  id
1290
1290
  themeInstallId
@@ -1363,15 +1363,15 @@
1363
1363
  }
1364
1364
  }
1365
1365
  }
1366
- `,Fo=w.gql`
1366
+ `,ko=C.gql`
1367
1367
  ${Ge}
1368
1368
  query GetMarketplaceThemeInstallConfiguration($themeConfigurationId: String!, $themeInstallId: String!) {
1369
1369
  marketplaceThemeInstallConfiguration(id: $themeConfigurationId, themeInstallId: $themeInstallId, raw: false) {
1370
1370
  ...MarketplaceThemeInstallConfigurationFields
1371
1371
  }
1372
1372
  }
1373
- `,ko=w.gql`
1374
- ${Yn}
1373
+ `,Mo=C.gql`
1374
+ ${Jn}
1375
1375
  ${Ge}
1376
1376
  query GetCurrentIntegration($themeConfigurationId: String) {
1377
1377
  currentIntegration {
@@ -1383,7 +1383,7 @@
1383
1383
  ...ActiveIntegrationFields
1384
1384
  }
1385
1385
  }
1386
- `,Mo=w.gql`
1386
+ `,To=C.gql`
1387
1387
  ${Ge}
1388
1388
  query ReadTransactionForMarketplaceTheme($id: String!) {
1389
1389
  transactions(ids: [$id]) {
@@ -1392,7 +1392,7 @@
1392
1392
  }
1393
1393
  }
1394
1394
  }
1395
- `,To=w.gql`
1395
+ `,No=C.gql`
1396
1396
  ${Ge}
1397
1397
  query ReadBundleForMarketplaceTheme($id: String!) {
1398
1398
  bundles(ids: [$id]) {
@@ -1401,14 +1401,14 @@
1401
1401
  }
1402
1402
  }
1403
1403
  }
1404
- `,No=w.gql`
1404
+ `,Qo=C.gql`
1405
1405
  mutation CreateOrder($orderItems: [OrderItemInput]!) {
1406
1406
  orderCreate(orderItems: $orderItems, paid: false, generateInternalId: true) {
1407
1407
  id
1408
1408
  internalId
1409
1409
  }
1410
1410
  }
1411
- `,Qo=w.gql`
1411
+ `,Ro=C.gql`
1412
1412
  query CurrencyConversion($from: String!, $to: String!) {
1413
1413
  currencyConversion(from: $from, to: $to) {
1414
1414
  rateFrom
@@ -1416,48 +1416,48 @@
1416
1416
  timestamp
1417
1417
  }
1418
1418
  }
1419
- `,zt=[v.SilentIllustration,v.ProductOverlay],Ro=async n=>{const t=[];n.introduction&&t.push({name:"Introduction",title:n.name,renderableSteps:[{type:v.Introduction,stepName:"Introduction",stepTitle:n.name,helpText:n.introduction,data:{},conditions:[]}],silentSteps:[]});for(const a of n.steps){const r=Oo(a.stepName,n.stepGroups);if(!r)t.push({name:a.stepName,title:a.stepTitle,renderableSteps:zt.includes(a.type)?[]:[a],silentSteps:zt.includes(a.type)?[a]:[]});else{const i=t.find(o=>o.name===r.name);i?zt.includes(a.type)?i.silentSteps.push(a):i.renderableSteps.push(a):t.push({name:r.name,title:r.name,renderableSteps:zt.includes(a.type)?[]:[a],silentSteps:zt.includes(a.type)?[a]:[]})}}const e="workflow.steps.finish.confirmDesign";return t.push({name:"Finish",title:e,renderableSteps:[{type:v.Finish,stepName:"Finish",stepTitle:e,helpText:"",data:{modelAnimation:n.finalizeStepConfig?n.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:n.finalizeStepConfig?n.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),t},Oo=(n,t)=>t.find(e=>e.stepNames.includes(n)),Bt=(n,t)=>(n.conditions||[]).every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const r=a.selectedVariants;return e.requiredVariantSelections.some(i=>r.find(o=>o.id===i)!==void 0)}return!1}),$o=(n,t)=>{const e={name:n.name,title:n.title,renderableSteps:n.renderableSteps.filter(a=>Bt(a,t)),silentSteps:n.silentSteps.filter(a=>Bt(a,t))};return e.silentSteps.length===0&&e.renderableSteps.length===0?null:e},Et=(n,t)=>n.map(e=>$o(e,t)).filter(e=>e!==null),Uo=async(n,t,e=!1)=>{const a=Et(n,t),r=[];for(const o of a)for(const s of o.renderableSteps){const l=(s.option?.variants||[]).length;s.silent||(s.type===v.Model||s.type===v.Material||s.type===v.Picture||s.type===v.Shape?(l>1||e)&&r.push(s.stepName):r.push(s.stepName))}const i=a.filter(o=>o.renderableSteps.filter(l=>r.includes(l.stepName)).length>0);for(const o of i)o.renderableSteps=o.renderableSteps.filter(s=>r.includes(s.stepName));return i};class ka{constructor(){this.timestamp=Date.now()}}class Ma{constructor(t,e=!0){this.queue=[],this.activePromise=void 0,this.queueMaxSize=void 0,this.queueMaxSize=t,this.isEnabled=e}enqueue(t){if(this.queue.push(t),this.queueMaxSize!==void 0&&this.queue.length>this.queueMaxSize){const e=this.queue.length-1;for(let a=0;a<e;++a)this.queue.shift()}this.isEnabled&&(this.activePromise||(this.activePromise=this.dequeue()))}get enabled(){return this.isEnabled}set enabled(t){!this.isEnabled&&t&&!this.activePromise&&this.getRemainingQueueSize()>0&&(this.activePromise=this.dequeue()),this.isEnabled=t}hasActivePromise(){return!!this.activePromise}getRemainingQueueSize(){return this.queue.length}async finalize(){return this.activePromise?this.activePromise:Promise.resolve()}async dequeue(){const t=this.queue.shift();if(!t){this.activePromise=void 0;return}try{await t.execute()}catch(e){console.log(e)}finally{await this.dequeue()}}}const M=()=>{const n=()=>Math.floor((1+Math.random())*65536).toString(16).substring(1);return n()+n()+"-"+n()+"-"+n()+"-"+n()+"-"+n()+n()+n()},Lo=({backgroundColor:n,outlineColor:t,borderRadius:e,configuration:a,elements:r,height:i,maxHeight:o,maxWidth:s,outlineArea:l,position:c,preserveAspectRatio:d,viewBox:A,width:u})=>{const h=e||0,g=2*(l?.scale||1),m=A||{x:0,y:0,width:u,height:i},p=`${m.x} ${m.y} ${m.width} ${m.height}`,f=M(),S=a.purpose===Nt.FreeDesign&&I.jsx("defs",{children:I.jsx("clipPath",{id:"viewboxClip",children:I.jsx("rect",{width:m.width,height:m.height,rx:h})})}),b=a.colorProfiles?.map((E,x)=>I.jsx("color-profile",{name:E.name,xlinkHref:E.key,children:" "},x)),P=r.map(E=>({...E,_renderingConfiguration:a,mask:l?`url(#viewmask-${f})`:void 0})),C=Ta(P);return I.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",xmlSpace:"preserve",version:"1.1",preserveAspectRatio:d,width:u,height:i,style:{gridColumn:1,gridRow:1,maxWidth:s,maxHeight:o,position:c},viewBox:p,children:[b,S,!!n&&I.jsx("rect",{id:"layout-background",width:m.width,height:m.height,fill:n,rx:h}),I.jsx("g",{id:"element-group",clipPath:a.purpose===Nt.FreeDesign?"url(#viewboxClip)":void 0,children:C.map(E=>sr(E)).filter(E=>!!E)}),l&&I.jsx("rect",{x:l.x,y:l.y,width:l.width,height:l.height,fill:"none",stroke:l.hidden?"none":t||"#aaaaaa",strokeWidth:g/2,strokeDasharray:`${g*2} ${g}`}),l&&I.jsxs("mask",{id:`viewmask-${f}`,children:[I.jsx("rect",{x:m.x,y:m.y,width:m.width,height:m.height,fill:"black"}),I.jsx("rect",{x:l.x,y:l.y,width:l.width,height:l.height,fill:"white"})]})]})},Vo=(n,t,e,a,r)=>{const i=Ct(r),o=e/2,s=a/2,l=n+o,c=t+s,d=Math.sin(i),A=Math.cos(i),u=o,h=o,g=-s,m=s,p=u*A-g*d,f=h*A-m*d,S=u*d+g*A,b=h*d+m*A,P=Math.max(Math.abs(p),Math.abs(f)),C=Math.max(Math.abs(S),Math.abs(b));return{minX:l-P,maxX:l+P,minY:c-C,maxY:c+C}},zo=(n,t,e)=>{const a=Math.sqrt(Math.pow(t.x-n.x,2)+Math.pow(t.y-n.y,2)),r=Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2)),i=Math.sqrt(Math.pow(e.x-n.x,2)+Math.pow(e.y-n.y,2));return Math.acos((r*r+a*a-i*i)/(2*r*a))*(180/Math.PI)},Ct=n=>n*(Math.PI/180),qo=(n,t,e)=>Math.abs(n-t)<e,Go=(n,t,e)=>{const a=Math.sin(Ct(e)),r=Math.cos(Ct(e));return{x:(n.x-t.x)*r-(n.y-t.y)*a+t.x,y:(n.x-t.x)*a+(n.y-t.y)*r+t.y}},Wo=(n,t)=>({x:(n.x+t.x)/2,y:(n.y+t.y)/2}),jo=(n,t,e,a)=>({x:n.x+t?.x*e,y:n.y+t?.y*a}),Ho=(n,t,e,a)=>({x:n.x+(t?.x+t?.width)*e,y:n.y+t?.y*a}),Yo=(n,t,e,a)=>({x:n.x+(t?.x+t?.width)*e,y:n.y+(t?.y+t?.height)*a}),Dt=n=>{switch(n){case G.North:return G.East;case G.East:return G.South;case G.South:return G.West;case G.West:return G.North;case G.Northwest:return G.Northeast;case G.Northeast:return G.Southeast;case G.Southeast:return G.Southwest;case G.Southwest:return G.Northwest}},Jo=(n,t)=>t>45&&t<=135?Dt(n):t>135&&t<=225?Dt(Dt(n)):t>225&&t<=315?Dt(Dt(Dt(n))):n,Ko=(n,t={x:0,y:0},e={x:1,y:1})=>{const a=Ct(n.rotation),r={x:t.x+n.x*e.x,y:t.x+n.y*e.y},i={x:n.x+n.width,y:n.y},o={x:t.x+(n.x+n.width)*e.x,y:t.y+(n.height+n.y)*e.y},s={x:t.x+n.x*e.x,y:t.y+(n.height+n.y)*e.y},l={x:(s.x+o.x)/2,y:s.y-n.height*e.y/2};return{a:jt(r,l,a),b:jt(i,l,a),c:jt(o,l,a),d:jt(s,l,a),center:l}},jt=(n,t,e)=>{const a=Math.sin(e),r=Math.cos(e);return{x:(n.x-t.x)*r-(n.y-t.y)*a+t.x,y:(n.x-t.x)*a+(n.y-t.y)*r+t.y}},_o=.352778,Xo=.035277,Zn=n=>{const t=n.rotation||0,e=Ct(t),a=Math.cos(e),r=-Math.sin(e);return I.jsx("g",{mask:n.stepName||n.productOverlay?void 0:n.mask,children:I.jsx("g",{transform:`
1419
+ `,zt=[E.SilentIllustration,E.ProductOverlay],Oo=async n=>{const t=[];n.introduction&&t.push({name:"Introduction",title:n.name,renderableSteps:[{type:E.Introduction,stepName:"Introduction",stepTitle:n.name,helpText:n.introduction,data:{},conditions:[]}],silentSteps:[]});for(const a of n.steps){const r=$o(a.stepName,n.stepGroups);if(!r)t.push({name:a.stepName,title:a.stepTitle,renderableSteps:zt.includes(a.type)?[]:[a],silentSteps:zt.includes(a.type)?[a]:[]});else{const i=t.find(o=>o.name===r.name);i?zt.includes(a.type)?i.silentSteps.push(a):i.renderableSteps.push(a):t.push({name:r.name,title:r.name,renderableSteps:zt.includes(a.type)?[]:[a],silentSteps:zt.includes(a.type)?[a]:[]})}}const e="workflow.steps.finish.confirmDesign";return t.push({name:"Finish",title:e,renderableSteps:[{type:E.Finish,stepName:"Finish",stepTitle:e,helpText:"",data:{modelAnimation:n.finalizeStepConfig?n.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:n.finalizeStepConfig?n.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),t},$o=(n,t)=>t.find(e=>e.stepNames.includes(n)),Bt=(n,t)=>(n.conditions||[]).every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const r=a.selectedVariants;return e.requiredVariantSelections.some(i=>r.find(o=>o.id===i)!==void 0)}return!1}),Uo=(n,t)=>{const e={name:n.name,title:n.title,renderableSteps:n.renderableSteps.filter(a=>Bt(a,t)),silentSteps:n.silentSteps.filter(a=>Bt(a,t))};return e.silentSteps.length===0&&e.renderableSteps.length===0?null:e},Et=(n,t)=>n.map(e=>Uo(e,t)).filter(e=>e!==null),Lo=async(n,t,e=!1)=>{const a=Et(n,t),r=[];for(const o of a)for(const s of o.renderableSteps){const l=(s.option?.variants||[]).length;s.silent||(s.type===E.Model||s.type===E.Material||s.type===E.Picture||s.type===E.Shape?(l>1||e)&&r.push(s.stepName):r.push(s.stepName))}const i=a.filter(o=>o.renderableSteps.filter(l=>r.includes(l.stepName)).length>0);for(const o of i)o.renderableSteps=o.renderableSteps.filter(s=>r.includes(s.stepName));return i};class Ma{constructor(){this.timestamp=Date.now()}}class Ta{constructor(t,e=!0){this.queue=[],this.activePromise=void 0,this.queueMaxSize=void 0,this.queueMaxSize=t,this.isEnabled=e}enqueue(t){if(this.queue.push(t),this.queueMaxSize!==void 0&&this.queue.length>this.queueMaxSize){const e=this.queue.length-1;for(let a=0;a<e;++a)this.queue.shift()}this.isEnabled&&(this.activePromise||(this.activePromise=this.dequeue()))}get enabled(){return this.isEnabled}set enabled(t){!this.isEnabled&&t&&!this.activePromise&&this.getRemainingQueueSize()>0&&(this.activePromise=this.dequeue()),this.isEnabled=t}hasActivePromise(){return!!this.activePromise}getRemainingQueueSize(){return this.queue.length}async finalize(){return this.activePromise?this.activePromise:Promise.resolve()}async dequeue(){const t=this.queue.shift();if(!t){this.activePromise=void 0;return}try{await t.execute()}catch(e){console.log(e)}finally{await this.dequeue()}}}const M=()=>{const n=()=>Math.floor((1+Math.random())*65536).toString(16).substring(1);return n()+n()+"-"+n()+"-"+n()+"-"+n()+"-"+n()+n()+n()},Vo=({backgroundColor:n,outlineColor:t,borderRadius:e,configuration:a,elements:r,height:i,maxHeight:o,maxWidth:s,outlineArea:l,position:c,preserveAspectRatio:d,viewBox:A,width:u})=>{const h=e||0,g=2*(l?.scale||1),p=A||{x:0,y:0,width:u,height:i},m=`${p.x} ${p.y} ${p.width} ${p.height}`,f=M(),v=a.purpose===Nt.FreeDesign&&I.jsx("defs",{children:I.jsx("clipPath",{id:"viewboxClip",children:I.jsx("rect",{width:p.width,height:p.height,rx:h})})}),b=a.colorProfiles?.map((S,P)=>I.jsx("color-profile",{name:S.name,xlinkHref:S.key,children:" "},P)),D=r.map(S=>({...S,_renderingConfiguration:a,mask:l?`url(#viewmask-${f})`:void 0})),w=Na(D);return I.jsxs("svg",{xmlns:"http://www.w3.org/2000/svg",xmlnsXlink:"http://www.w3.org/1999/xlink",xmlSpace:"preserve",version:"1.1",preserveAspectRatio:d,width:u,height:i,style:{gridColumn:1,gridRow:1,maxWidth:s,maxHeight:o,position:c},viewBox:m,children:[b,v,!!n&&I.jsx("rect",{id:"layout-background",width:p.width,height:p.height,fill:n,rx:h}),I.jsx("g",{id:"element-group",clipPath:a.purpose===Nt.FreeDesign?"url(#viewboxClip)":void 0,children:w.map(S=>lr(S)).filter(S=>!!S)}),l&&I.jsx("rect",{x:l.x,y:l.y,width:l.width,height:l.height,fill:"none",stroke:l.hidden?"none":t||"#aaaaaa",strokeWidth:g/2,strokeDasharray:`${g*2} ${g}`}),l&&I.jsxs("mask",{id:`viewmask-${f}`,children:[I.jsx("rect",{x:p.x,y:p.y,width:p.width,height:p.height,fill:"black"}),I.jsx("rect",{x:l.x,y:l.y,width:l.width,height:l.height,fill:"white"})]})]})},zo=(n,t,e,a,r)=>{const i=Ct(r),o=e/2,s=a/2,l=n+o,c=t+s,d=Math.sin(i),A=Math.cos(i),u=o,h=o,g=-s,p=s,m=u*A-g*d,f=h*A-p*d,v=u*d+g*A,b=h*d+p*A,D=Math.max(Math.abs(m),Math.abs(f)),w=Math.max(Math.abs(v),Math.abs(b));return{minX:l-D,maxX:l+D,minY:c-w,maxY:c+w}},qo=(n,t,e)=>{const a=Math.sqrt(Math.pow(t.x-n.x,2)+Math.pow(t.y-n.y,2)),r=Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2)),i=Math.sqrt(Math.pow(e.x-n.x,2)+Math.pow(e.y-n.y,2));return Math.acos((r*r+a*a-i*i)/(2*r*a))*(180/Math.PI)},Ct=n=>n*(Math.PI/180),Go=(n,t,e)=>Math.abs(n-t)<e,Wo=(n,t,e)=>{const a=Math.sin(Ct(e)),r=Math.cos(Ct(e));return{x:(n.x-t.x)*r-(n.y-t.y)*a+t.x,y:(n.x-t.x)*a+(n.y-t.y)*r+t.y}},jo=(n,t)=>({x:(n.x+t.x)/2,y:(n.y+t.y)/2}),Ho=(n,t,e,a)=>({x:n.x+t?.x*e,y:n.y+t?.y*a}),Yo=(n,t,e,a)=>({x:n.x+(t?.x+t?.width)*e,y:n.y+t?.y*a}),Jo=(n,t,e,a)=>({x:n.x+(t?.x+t?.width)*e,y:n.y+(t?.y+t?.height)*a}),Ft=n=>{switch(n){case W.North:return W.East;case W.East:return W.South;case W.South:return W.West;case W.West:return W.North;case W.Northwest:return W.Northeast;case W.Northeast:return W.Southeast;case W.Southeast:return W.Southwest;case W.Southwest:return W.Northwest}},Ko=(n,t)=>t>45&&t<=135?Ft(n):t>135&&t<=225?Ft(Ft(n)):t>225&&t<=315?Ft(Ft(Ft(n))):n,_o=(n,t={x:0,y:0},e={x:1,y:1})=>{const a=Ct(n.rotation),r={x:t.x+n.x*e.x,y:t.x+n.y*e.y},i={x:n.x+n.width,y:n.y},o={x:t.x+(n.x+n.width)*e.x,y:t.y+(n.height+n.y)*e.y},s={x:t.x+n.x*e.x,y:t.y+(n.height+n.y)*e.y},l={x:(s.x+o.x)/2,y:s.y-n.height*e.y/2};return{a:jt(r,l,a),b:jt(i,l,a),c:jt(o,l,a),d:jt(s,l,a),center:l}},jt=(n,t,e)=>{const a=Math.sin(e),r=Math.cos(e);return{x:(n.x-t.x)*r-(n.y-t.y)*a+t.x,y:(n.x-t.x)*a+(n.y-t.y)*r+t.y}},Xo=.352778,Zo=.035277,tr=n=>{const t=n.rotation||0,e=Ct(t),a=Math.cos(e),r=-Math.sin(e);return I.jsx("g",{mask:n.stepName||n.productOverlay?void 0:n.mask,children:I.jsx("g",{transform:`
1420
1420
  matrix(1, 0, 0, 1, ${n.x}, ${n.y})
1421
1421
  matrix(1, 0, 0, 1, ${n.width/2}, ${n.height/2})
1422
1422
  matrix(${a}, ${-r}, ${r}, ${a}, 0, 0)
1423
1423
  matrix(1, 0, 0, 1, ${-n.width/2}, ${-n.height/2})
1424
- `,children:I.jsx("image",{xlinkHref:n.src,preserveAspectRatio:n.preserveAspectRatio,width:n.width,height:n.height})})})},tr=n=>{const t=`spiff-group-clip-${n.id}`,e=n.rotation||0,a=Ct(e),r=Math.cos(a),i=-Math.sin(a),o=Ta(n.children),s=()=>I.jsx("clipPath",{id:t,preserveAspectRatio:"none",children:n.clipPath?I.jsx("path",{d:n.clipPath}):I.jsx("rect",{x:0,y:0,width:n.width,height:n.height})});return I.jsxs(I.Fragment,{children:[I.jsx("defs",{children:s()}),I.jsxs("g",{transform:`
1424
+ `,children:I.jsx("image",{xlinkHref:n.src,preserveAspectRatio:n.preserveAspectRatio,width:n.width,height:n.height})})})},er=n=>{const t=`spiff-group-clip-${n.id}`,e=n.rotation||0,a=Ct(e),r=Math.cos(a),i=-Math.sin(a),o=Na(n.children),s=()=>I.jsx("clipPath",{id:t,preserveAspectRatio:"none",children:n.clipPath?I.jsx("path",{d:n.clipPath}):I.jsx("rect",{x:0,y:0,width:n.width,height:n.height})});return I.jsxs(I.Fragment,{children:[I.jsx("defs",{children:s()}),I.jsxs("g",{transform:`
1425
1425
  matrix(1, 0, 0, 1, ${n.x}, ${n.y})
1426
1426
  matrix(1, 0, 0, 1, ${n.width/2}, ${n.height/2})
1427
1427
  matrix(${r}, ${-i}, ${i}, ${r}, 0, 0)
1428
1428
  matrix(1, 0, 0, 1, ${-n.width/2}, ${-n.height/2})
1429
- `,children:[n._renderingConfiguration?.debug?I.jsx("rect",{stroke:"red",opacity:.3,fill:"none",x:0,y:0,width:n.width,height:n.height}):void 0,o.map(l=>sr(l)).filter(l=>!!l).map(l=>I.jsx("g",{clipPath:`url(#${t})`,children:l}))]})]})},Zo=n=>{const t=`spiff-frame-${n.id}`,e=`spiff-frame-threshold-${n.id}`,a=()=>{if(!n.pattern)return"";if(n.pattern.svg){const A=ze(n.pattern.svg,n.pattern.colors||{},!1);return Le(A)}return n.pattern.src};if(!a())return I.jsx(I.Fragment,{});const r=()=>n.threshold?n.invertThreshold?"1 ".repeat(n.threshold)+"0 ".repeat(256-n.threshold):"0 ".repeat(n.threshold)+"1 ".repeat(256-n.threshold):"",i=()=>I.jsx(I.Fragment,{children:n.useThreshold&&I.jsx("defs",{children:I.jsxs("filter",{id:e,"color-interpolation-filters":"sRGB",children:[I.jsx("feColorMatrix",{type:"matrix",values:`
1429
+ `,children:[n._renderingConfiguration?.debug?I.jsx("rect",{stroke:"red",opacity:.3,fill:"none",x:0,y:0,width:n.width,height:n.height}):void 0,o.map(l=>lr(l)).filter(l=>!!l).map(l=>I.jsx("g",{clipPath:`url(#${t})`,children:l}))]})]})},ts=n=>{const t=`spiff-frame-${n.id}`,e=`spiff-frame-threshold-${n.id}`,a=()=>{if(!n.pattern)return"";if(n.pattern.svg){const A=ze(n.pattern.svg,n.pattern.colors||{},!1);return Le(A)}return n.pattern.src};if(!a())return I.jsx(I.Fragment,{});const r=()=>n.threshold?n.invertThreshold?"1 ".repeat(n.threshold)+"0 ".repeat(256-n.threshold):"0 ".repeat(n.threshold)+"1 ".repeat(256-n.threshold):"",i=()=>I.jsx(I.Fragment,{children:n.useThreshold&&I.jsx("defs",{children:I.jsxs("filter",{id:e,"color-interpolation-filters":"sRGB",children:[I.jsx("feColorMatrix",{type:"matrix",values:`
1430
1430
  ${n.thresholdSaturation} ${n.thresholdSaturation} ${n.thresholdSaturation} 0 0
1431
1431
  ${n.thresholdSaturation} ${n.thresholdSaturation} ${n.thresholdSaturation} 0 0
1432
1432
  ${n.thresholdSaturation} ${n.thresholdSaturation} ${n.thresholdSaturation} 0 0
1433
1433
  0 0 0 1 0
1434
- `,result:"greyscale"}),I.jsxs("feComponentTransfer",{in:"greyscale",children:[I.jsx("feFuncR",{type:"discrete",tableValues:r()}),I.jsx("feFuncG",{type:"discrete",tableValues:r()}),I.jsx("feFuncB",{type:"discrete",tableValues:r()})]})]})})}),o=n.rotation||0,s=Ct(o),l=Math.cos(s),c=-Math.sin(s),d=()=>{const A=n.pattern?.x||0,u=n.pattern?.y||0,h=n.pattern?.width||0,g=n.pattern?.height||0,m=n.pattern?.scaleX||1,p=n.pattern?.scaleY||1,f=n.pattern?.rotation||0;return[n.pattern?.svg?{id:`${t}-contents`,type:F.Illustration,x:A,y:u,rotation:f,width:h*m,height:g*p,src:a(),svg:n.pattern?.svg,colors:n.pattern?.colors}:{id:`${t}-contents`,type:F.Image,x:A,y:u,rotation:f,width:h*m,height:g*p,src:a()}]};return I.jsxs(I.Fragment,{children:[i(),I.jsx("g",{opacity:n.opacity,mask:n.stepName?void 0:n.mask,filter:n.useThreshold?`url(#${e})`:void 0,children:I.jsx("g",{transform:`
1434
+ `,result:"greyscale"}),I.jsxs("feComponentTransfer",{in:"greyscale",children:[I.jsx("feFuncR",{type:"discrete",tableValues:r()}),I.jsx("feFuncG",{type:"discrete",tableValues:r()}),I.jsx("feFuncB",{type:"discrete",tableValues:r()})]})]})})}),o=n.rotation||0,s=Ct(o),l=Math.cos(s),c=-Math.sin(s),d=()=>{const A=n.pattern?.x||0,u=n.pattern?.y||0,h=n.pattern?.width||0,g=n.pattern?.height||0,p=n.pattern?.scaleX||1,m=n.pattern?.scaleY||1,f=n.pattern?.rotation||0;return[n.pattern?.svg?{id:`${t}-contents`,type:x.Illustration,x:A,y:u,rotation:f,width:h*p,height:g*m,src:a(),svg:n.pattern?.svg,colors:n.pattern?.colors}:{id:`${t}-contents`,type:x.Image,x:A,y:u,rotation:f,width:h*p,height:g*m,src:a()}]};return I.jsxs(I.Fragment,{children:[i(),I.jsx("g",{opacity:n.opacity,mask:n.stepName?void 0:n.mask,filter:n.useThreshold?`url(#${e})`:void 0,children:I.jsx("g",{transform:`
1435
1435
  matrix(1, 0, 0, 1, ${n.x}, ${n.y})
1436
1436
  matrix(1, 0, 0, 1, ${n.width/2}, ${n.height/2})
1437
1437
  matrix(${l}, ${-c}, ${c}, ${l}, 0, 0)
1438
1438
  matrix(1, 0, 0, 1, ${-n.width/2}, ${-n.height/2})
1439
1439
  matrix(${n.scaleX}, 0, 0, ${n.scaleY}, 0, 0)
1440
- `,children:I.jsx(tr,{id:t,x:0,y:0,rotation:0,width:n.width,height:n.height,clipPath:n.path,children:d()})})})]})},er=new Map;class ts{constructor(t){this.font=t,this.glyphsFromText=new Map,this.kerningValues=new Map,this.height=this.calculateApproximateHeight()}getFont(){return this.font}getGlyphs(t){const e=this.glyphsFromText.get(t);if(e)return e;const a=this.font.stringToGlyphs(t);return this.glyphsFromText.set(t,a),a}getApproximateHeight(){return this.height}getExactHeight(t){const e=this.font.stringToGlyphs(t);let a=0,r=0;return e.forEach(i=>{const o=i.getMetrics();a=Math.max(a,o.yMax),r=Math.min(r,o.yMin)}),a-r}getKerningValue(t,e){if(!t.name||!e.name)return;let a=this.kerningValues.get(t.name);a||(a=new Map,this.kerningValues.set(t.name,a));let r=a.get(e.name);return r||(r=this.font.getKerningValue(t,e),a.set(e.name,r)),r}calculateApproximateHeight(){const e=this.font.stringToGlyphs("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");let a=0,r=0;return e.forEach(i=>{const o=i.getMetrics();a=Math.max(a,o.yMax),r=Math.min(r,o.yMin)}),a-r}}const es=n=>n.substring(0,5).toLowerCase().trim()==="data:",Ke=new Map,xt=async n=>{if(Ke.has(n))return Ke.get(n);const e=(async()=>{try{return wt(n).getFont()}catch{if(es(n)){const a=On(n),r=sa.parse(a);return ga(n,r),r}else{const a=await $e(n,!0),r=sa.parse(a);return ga(n,r),await bi(r,n),r}}})();return Ke.set(n,e),e},as=n=>{const t=On(n),e=sa.parse(t);return ga(n,e),e},wt=n=>{const t=er.get(n);if(t)return t;throw new Error("Font metrics unavailable for font")},ga=(n,t)=>{const e=new ts(t);return er.set(n,e),e},ns=async n=>{const t=lt(),e=t.parseFromString(n,"image/svg+xml"),a=e.firstElementChild,r=new Map;a.querySelectorAll("style").forEach(d=>{bn.parse(d.innerHTML).stylesheet?.rules.forEach(u=>{if(u.type==="font-face"&&u.declarations){const h=u.declarations.find(p=>p.property==="font-family")?.value,m=u.declarations.find(p=>p.property==="src")?.value?.match(/'(https.*?)'/)?.[1];h&&m&&r.set(h,m)}})});const o=e.querySelectorAll("tspan");for(let d=0;d<o.length;d++){const A=o.item(d),u=A.closest("text"),h=A.closest("g"),g=u.getAttribute("font-family"),m=await xt(r.get(g)),p=u.getAttribute("fill"),f=u.getAttribute("stroke"),S=u.getAttribute("stroke-width"),b=m.getPath(A.innerHTML,0,0,parseInt(u.getAttribute("font-size")??"72")),P=b.getBoundingBox().x2-b.getBoundingBox().x1;let C=0;const E=A.getAttribute("text-anchor");E==="middle"?C=P/2:E==="end"&&(C=P);const x=m.getPath(A.innerHTML,parseFloat(A.getAttribute("x")??"0")-C,parseFloat(A.getAttribute("y")??"0"),parseInt(u.getAttribute("font-size")??"72"));x.fill=p,x.stroke=f,x.strokeWidth=parseFloat(S??"0");const B=x.toSVG(2),O=t.parseFromString(B,"image/svg+xml").firstElementChild;h.appendChild(O)}return e.querySelectorAll("text").forEach(d=>d.remove()),St().serializeToString(a)},Fe=(n,t,e,a)=>Math.max(ss(n.join(`
1441
- `),e,a),t),sn=(n,t,e,a,r,i)=>{const o=(i||rr)*r.getApproximateHeight(),s=t.split(`
1442
- `);try{const l=s.flatMap(d=>Be(d,n.width,a,r)),c=l.flatMap(d=>d.lines);return{lines:c,requiredHeight:l.flatMap(d=>d.lines).length*(a*o),fontSize:e,requiredWidth:Fe(c,n.width,a,r)}}catch{const c=t.split("");return{lines:c,requiredHeight:c.length*(a*o),fontSize:e,requiredWidth:Fe(c,n.width,a,r)}}},Be=(n,t,e,a)=>{const r=mt(n,e,a);if(r<=t)return{lines:[n],width:r};if(!(n.indexOf(" ")>-1)){if(n.length<=1)throw new Error(`Character ${n} is wider than region`);const d=Math.floor(n.length/2),A=Be(n.slice(0,d),t,e,a),u=Be(n.slice(d),t,e,a);return{lines:[...A.lines,...u.lines],width:Math.max(A.width,u.width)}}const o=n.split(" "),s=[];let l=-1/0,c=0;for(;c<o.length;){const d=o[c];if(mt(d,e,a)>t){const A=Be(d,t,e,a);s.push(...A.lines),l=Math.max(l,A.width),c++}else{const A=[d];l=Math.max(l,mt(d,e,a));let u=c+1,h=!0;for(;u<o.length&&h;){const g=o[u],m=mt(`${A.join(" ")} ${g}`,e,a);m<=t?(A.push(g),l=Math.max(l,m),u++):h=!1}s.push(A.join(" ")),c=u}}if(l<0)throw new Error(`No max width calculated for text: ${s}.`);return{lines:s,width:l}},rs=(n,t,e,a,r,i)=>{const o=(i??rr)*t.getApproximateHeight(),s=1/e.unitsPerEm,l=ar(n,s,t),c=n.length*o*s,d=a/l,A=r/c;return Math.min(A,d)},is=(n,t,e,a)=>{const r=wt(t.fontData.assetUrl),i=r.getFont(),o=t.fontSize/i.unitsPerEm;if(!e)return sn(t,n,t.fontSize,o,r,a);let s;if(t.text?s=t.text.split(`
1440
+ `,children:I.jsx(er,{id:t,x:0,y:0,rotation:0,width:n.width,height:n.height,clipPath:n.path,children:d()})})})]})},ar=new Map;class es{constructor(t){this.font=t,this.glyphsFromText=new Map,this.kerningValues=new Map,this.height=this.calculateApproximateHeight()}getFont(){return this.font}getGlyphs(t){const e=this.glyphsFromText.get(t);if(e)return e;const a=this.font.stringToGlyphs(t);return this.glyphsFromText.set(t,a),a}getApproximateHeight(){return this.height}getExactHeight(t){const e=this.font.stringToGlyphs(t);let a=0,r=0;return e.forEach(i=>{const o=i.getMetrics();a=Math.max(a,o.yMax),r=Math.min(r,o.yMin)}),a-r}getKerningValue(t,e){if(!t.name||!e.name)return;let a=this.kerningValues.get(t.name);a||(a=new Map,this.kerningValues.set(t.name,a));let r=a.get(e.name);return r||(r=this.font.getKerningValue(t,e),a.set(e.name,r)),r}calculateApproximateHeight(){const e=this.font.stringToGlyphs("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");let a=0,r=0;return e.forEach(i=>{const o=i.getMetrics();a=Math.max(a,o.yMax),r=Math.min(r,o.yMin)}),a-r}}const as=n=>n.substring(0,5).toLowerCase().trim()==="data:",_e=new Map,Dt=async n=>{if(_e.has(n))return _e.get(n);const e=(async()=>{try{return wt(n).getFont()}catch{if(as(n)){const a=$n(n),r=la.parse(a);return ma(n,r),r}else{const a=await $e(n,!0),r=la.parse(a);return ma(n,r),await Bi(r,n),r}}})();return _e.set(n,e),e},ns=n=>{const t=$n(n),e=la.parse(t);return ma(n,e),e},wt=n=>{const t=ar.get(n);if(t)return t;throw new Error("Font metrics unavailable for font")},ma=(n,t)=>{const e=new es(t);return ar.set(n,e),e},rs=async n=>{const t=lt(),e=t.parseFromString(n,"image/svg+xml"),a=e.firstElementChild,r=new Map;a.querySelectorAll("style").forEach(d=>{Bn.parse(d.innerHTML).stylesheet?.rules.forEach(u=>{if(u.type==="font-face"&&u.declarations){const h=u.declarations.find(m=>m.property==="font-family")?.value,p=u.declarations.find(m=>m.property==="src")?.value?.match(/'(https.*?)'/)?.[1];h&&p&&r.set(h,p)}})});const o=e.querySelectorAll("tspan");for(let d=0;d<o.length;d++){const A=o.item(d),u=A.closest("text"),h=A.closest("g"),g=u.getAttribute("font-family"),p=await Dt(r.get(g)),m=u.getAttribute("fill"),f=u.getAttribute("stroke"),v=u.getAttribute("stroke-width"),b=p.getPath(A.innerHTML,0,0,parseInt(u.getAttribute("font-size")??"72")),D=b.getBoundingBox().x2-b.getBoundingBox().x1;let w=0;const S=A.getAttribute("text-anchor");S==="middle"?w=D/2:S==="end"&&(w=D);const P=p.getPath(A.innerHTML,parseFloat(A.getAttribute("x")??"0")-w,parseFloat(A.getAttribute("y")??"0"),parseInt(u.getAttribute("font-size")??"72"));P.fill=m,P.stroke=f,P.strokeWidth=parseFloat(v??"0");const F=P.toSVG(2),T=t.parseFromString(F,"image/svg+xml").firstElementChild;h.appendChild(T)}return e.querySelectorAll("text").forEach(d=>d.remove()),St().serializeToString(a)},xe=(n,t,e,a)=>Math.max(ls(n.join(`
1441
+ `),e,a),t),ln=(n,t,e,a,r,i)=>{const o=(i||ir)*r.getApproximateHeight(),s=t.split(`
1442
+ `);try{const l=s.flatMap(d=>Be(d,n.width,a,r)),c=l.flatMap(d=>d.lines);return{lines:c,requiredHeight:l.flatMap(d=>d.lines).length*(a*o),fontSize:e,requiredWidth:xe(c,n.width,a,r)}}catch{const c=t.split("");return{lines:c,requiredHeight:c.length*(a*o),fontSize:e,requiredWidth:xe(c,n.width,a,r)}}},Be=(n,t,e,a)=>{const r=mt(n,e,a);if(r<=t)return{lines:[n],width:r};if(!(n.indexOf(" ")>-1)){if(n.length<=1)throw new Error(`Character ${n} is wider than region`);const d=Math.floor(n.length/2),A=Be(n.slice(0,d),t,e,a),u=Be(n.slice(d),t,e,a);return{lines:[...A.lines,...u.lines],width:Math.max(A.width,u.width)}}const o=n.split(" "),s=[];let l=-1/0,c=0;for(;c<o.length;){const d=o[c];if(mt(d,e,a)>t){const A=Be(d,t,e,a);s.push(...A.lines),l=Math.max(l,A.width),c++}else{const A=[d];l=Math.max(l,mt(d,e,a));let u=c+1,h=!0;for(;u<o.length&&h;){const g=o[u],p=mt(`${A.join(" ")} ${g}`,e,a);p<=t?(A.push(g),l=Math.max(l,p),u++):h=!1}s.push(A.join(" ")),c=u}}if(l<0)throw new Error(`No max width calculated for text: ${s}.`);return{lines:s,width:l}},is=(n,t,e,a,r,i)=>{const o=(i??ir)*t.getApproximateHeight(),s=1/e.unitsPerEm,l=nr(n,s,t),c=n.length*o*s,d=a/l,A=r/c;return Math.min(A,d)},os=(n,t,e,a)=>{const r=wt(t.fontData.assetUrl),i=r.getFont(),o=t.fontSize/i.unitsPerEm;if(!e)return ln(t,n,t.fontSize,o,r,a);let s;if(t.text?s=t.text.split(`
1443
1443
  `):s=t.input?.split(`
1444
- `)??[""],e.input===n&&t.width===e.width&&t.height===e.height&&t.lineHeight===e.lineHeight)return{lines:s,requiredHeight:t.height,requiredWidth:Fe(s,t.width,o,r),fontSize:t.fontSize};const l=t.width!==e.width!=(t.height!==e.height);return t.lineHeight===e.lineHeight&&!l&&e.input===n?{lines:s,requiredHeight:t.height,requiredWidth:Fe(s,t.width,o,r),fontSize:rs(s,r,i,t.width,t.height,a)}:sn(t,n,t.fontSize,o,r,a)},os=(n,t,e,a,r)=>{const o=wt(t.assetUrl).getFont();let s={...n};const l={...n},c=ar(a,e/o.unitsPerEm,wt(t.assetUrl));return c&&c<s.width&&(l.width=c,r==="left"?(l.left+=Math.sin(s.rotation*Math.PI/360)*(s.width-c),l.top+=Math.sin(s.rotation*Math.PI/180)*(c-s.width)/2):r==="right"?l.left+=s.width-c:l.left+=(s.width-c)/2,a&&ls(a,a).every(([d,A])=>d===A)&&(s=l)),s},_e=1,mt=(n,t,e)=>{let a=0;const r=e.getGlyphs(n);return r.forEach((i,o)=>{if(i.advanceWidth&&(a+=i.advanceWidth),o<r.length-1){const s=e.getKerningValue(i,r[o+1]);a+=s||0}}),a*=t,a},ss=(n,t,e)=>{let a=0;const r=e.getGlyphs(n);return r.forEach((i,o)=>{if(i.advanceWidth&&(a=Math.max(a,i.advanceWidth)),o<r.length-1){const s=e.getKerningValue(i,r[o+1]);a=Math.max(a,s||0)}}),a*=t,a},ar=(n,t,e)=>{let a=0;return n.forEach(r=>{a=Math.max(a,mt(r,t,e))}),a},ln={stripControlCharacters:!0,vertical:!1,uppercase:!1},ke=(n,t=ln)=>{const e={...ln,...t};let a=n||"";return e.stripControlCharacters&&(a=a.replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,"")),e.uppercase&&(a=a.toUpperCase()),e.vertical&&(a=a.split("").join(`
1445
- `)),a},ls=(n,t)=>n.map((e,a)=>[e,t[a]]),cs=(n="center",t=!1)=>t?"center":n,nr=n=>n==="left"?"start":n==="right"?"end":"middle",Ae=(n,t,e)=>n.fontData?{...n,...(()=>{if(n.algorithm===Pt.Traditional){const r=is(t,n,e,n.lineHeight);return{text:r.lines.join(`
1446
- `),height:r.requiredHeight,width:r.requiredWidth,fontSize:r.fontSize,input:t}}else return{text:t}})()}:n,rr=1.1;function Mt(n,t){return ir(n,t.getTemplatingContext())}function ir(n,t){try{n=di.compile(n)(t)}catch(e){console.error("failed to render templated text",e)}return n}const ds=n=>{const e=(n.rotation||0)*Math.PI/180,a=Math.cos(e),r=-Math.sin(e),i=`text-path-${n.id}`,o=`text-fill-${n.id}`,s=n.x+(n.curved?0:n.width/2),l=n.y+(n.curved?0:n.height/2),c=ir(n.text||"",n._renderingConfiguration?.templatingContext),d=c.split(`
1447
- `),A=n.strokeColor?.browserValue&&n.strokeThickness?n.strokeColor?.browserValue:void 0,u=n.strokeColor?.browserValue&&n.strokeThickness?n.strokeThickness:void 0;if(n.curved&&!n.paths||!n.fontData)return null;const h=()=>n.textFillImage?`url("#${o}")`:n._renderingConfiguration?.spotColors&&n.fillSpotColorDefinition?`${n.fill} ${qn(n.fillSpotColorDefinition)}`:n.fill;return I.jsxs(I.Fragment,{children:[I.jsxs("defs",{children:[n.textFillImage&&I.jsx("pattern",{id:o,patternUnits:"userSpaceOnUse",width:n.textFillImage.scale*n.textFillImage.width,height:n.textFillImage.scale*n.textFillImage.height,x:0,y:0,children:I.jsx("image",{href:n.textFillImage.src,xlinkHref:n.textFillImage.src,width:n.textFillImage.scale*n.textFillImage.width,height:n.textFillImage.scale*n.textFillImage.height})}),I.jsx("style",{type:"text/css",dangerouslySetInnerHTML:{__html:`
1444
+ `)??[""],e.input===n&&t.width===e.width&&t.height===e.height&&t.lineHeight===e.lineHeight)return{lines:s,requiredHeight:t.height,requiredWidth:xe(s,t.width,o,r),fontSize:t.fontSize};const l=t.width!==e.width!=(t.height!==e.height);return t.lineHeight===e.lineHeight&&!l&&e.input===n?{lines:s,requiredHeight:t.height,requiredWidth:xe(s,t.width,o,r),fontSize:is(s,r,i,t.width,t.height,a)}:ln(t,n,t.fontSize,o,r,a)},ss=(n,t,e,a,r)=>{const o=wt(t.assetUrl).getFont();let s={...n};const l={...n},c=nr(a,e/o.unitsPerEm,wt(t.assetUrl));return c&&c<s.width&&(l.width=c,r==="left"?(l.left+=Math.sin(s.rotation*Math.PI/360)*(s.width-c),l.top+=Math.sin(s.rotation*Math.PI/180)*(c-s.width)/2):r==="right"?l.left+=s.width-c:l.left+=(s.width-c)/2,a&&cs(a,a).every(([d,A])=>d===A)&&(s=l)),s},Xe=1,mt=(n,t,e)=>{let a=0;const r=e.getGlyphs(n);return r.forEach((i,o)=>{if(i.advanceWidth&&(a+=i.advanceWidth),o<r.length-1){const s=e.getKerningValue(i,r[o+1]);a+=s||0}}),a*=t,a},ls=(n,t,e)=>{let a=0;const r=e.getGlyphs(n);return r.forEach((i,o)=>{if(i.advanceWidth&&(a=Math.max(a,i.advanceWidth)),o<r.length-1){const s=e.getKerningValue(i,r[o+1]);a=Math.max(a,s||0)}}),a*=t,a},nr=(n,t,e)=>{let a=0;return n.forEach(r=>{a=Math.max(a,mt(r,t,e))}),a},cn={stripControlCharacters:!0,vertical:!1,uppercase:!1},ke=(n,t=cn)=>{const e={...cn,...t};let a=n||"";return e.stripControlCharacters&&(a=a.replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,"")),e.uppercase&&(a=a.toUpperCase()),e.vertical&&(a=a.split("").join(`
1445
+ `)),a},cs=(n,t)=>n.map((e,a)=>[e,t[a]]),ds=(n="center",t=!1)=>t?"center":n,rr=n=>n==="left"?"start":n==="right"?"end":"middle",Ae=(n,t,e)=>n.fontData?{...n,...(()=>{if(n.algorithm===Pt.Traditional){const r=os(t,n,e,n.lineHeight);return{text:r.lines.join(`
1446
+ `),height:r.requiredHeight,width:r.requiredWidth,fontSize:r.fontSize,input:t}}else return{text:t}})()}:n,ir=1.1;function Mt(n,t){return or(n,t.getTemplatingContext())}function or(n,t){try{n=Ai.compile(n)(t)}catch(e){console.error("failed to render templated text",e)}return n}const As=n=>{const e=(n.rotation||0)*Math.PI/180,a=Math.cos(e),r=-Math.sin(e),i=`text-path-${n.id}`,o=`text-fill-${n.id}`,s=n.x+(n.curved?0:n.width/2),l=n.y+(n.curved?0:n.height/2),c=or(n.text||"",n._renderingConfiguration?.templatingContext),d=c.split(`
1447
+ `),A=n.strokeColor?.browserValue&&n.strokeThickness?n.strokeColor?.browserValue:void 0,u=n.strokeColor?.browserValue&&n.strokeThickness?n.strokeThickness:void 0;if(n.curved&&!n.paths||!n.fontData)return null;const h=()=>n.textFillImage?`url("#${o}")`:n._renderingConfiguration?.spotColors&&n.fillSpotColorDefinition?`${n.fill} ${Gn(n.fillSpotColorDefinition)}`:n.fill;return I.jsxs(I.Fragment,{children:[I.jsxs("defs",{children:[n.textFillImage&&I.jsx("pattern",{id:o,patternUnits:"userSpaceOnUse",width:n.textFillImage.scale*n.textFillImage.width,height:n.textFillImage.scale*n.textFillImage.height,x:0,y:0,children:I.jsx("image",{href:n.textFillImage.src,xlinkHref:n.textFillImage.src,width:n.textFillImage.scale*n.textFillImage.width,height:n.textFillImage.scale*n.textFillImage.height})}),I.jsx("style",{type:"text/css",dangerouslySetInnerHTML:{__html:`
1448
1448
  @font-face {
1449
1449
  font-family: '${n.fontData.name}';
1450
1450
  src: url('${n.fontData.assetUrl}') format('truetype');
1451
1451
  }
1452
- `}}),n.curved&&n.paths?I.jsx("path",{id:i,d:n.paths[0]}):void 0]}),n._renderingConfiguration?.debug?I.jsx("rect",{stroke:"blue",fill:"none",x:n.x,y:n.y,width:n.width,height:n.height}):void 0,I.jsx("g",{mask:n.stepName?void 0:n.mask,children:I.jsx("g",{transform:`matrix(${a}, ${-r}, ${r}, ${a}, ${s}, ${l})`,children:I.jsx("text",{xmlSpace:"preserve",fontFamily:`'${n.fontData.name}'`,fontSize:n.fontSize,fontStyle:"normal",fontWeight:"normal",fill:h(),style:{whiteSpace:"pre",userSelect:"none"},stroke:A,strokeWidth:u,children:n.curved?I.jsx(us,{text:c,curvedPathId:i,align:n.align}):d.map((g,m)=>I.jsx(As,{align:n.vertical?"center":n.align,fontSize:n.fontSize,thisLineIdx:m,amountLines:d.length,text:g,textboxHeight:n.height,textboxWidth:n.width,lineHeight:n.lineHeight,vertical:n.vertical,verticalAlign:n.verticalAlign,fontData:n.fontData},m))})})})]})},As=n=>{const t=()=>{if(n.lineHeight!==void 0)return n.lineHeight*n.fontSize;const r=wt(n.fontData.assetUrl),i=r.getFont(),o=n.fontSize/i.unitsPerEm;return r.getApproximateHeight()*o},e=()=>n.align==="left"?-n.textboxWidth/2:n.align==="right"?n.textboxWidth/2:0,a=()=>{const r=t(),i=n.textboxHeight/2;if(n.verticalAlign==="top")return-i+n.fontSize*3/4+n.thisLineIdx*r;if(n.verticalAlign==="bottom"){const s=n.amountLines-1-n.thisLineIdx;return i-n.fontSize/4-s*r}const o=(n.amountLines-1)/2;return(n.thisLineIdx-o)*r+n.fontSize/4};return I.jsx("tspan",{textAnchor:nr(n.align),x:e(),y:`${a()}px`,children:n.text})},us=n=>{const t=`#${n.curvedPathId}`,e=()=>n.align==="left"?"0%":n.align==="right"?"100%":"50%";return I.jsx("textPath",{startOffset:e(),textAnchor:nr(n.align),href:t,xlinkHref:t,children:n.text})},hs=n=>{if(n.cachedObjectURL&&!n._renderingConfiguration?.omitCachedFields)return I.jsx(Zn,{id:n.id,src:n.cachedObjectURL,x:n.x,y:n.y,width:n.width,height:n.height,rotation:n.rotation,preserveAspectRatio:"none",immutable:n.immutable,mask:n.stepName?void 0:n.mask});const t=n.rotation||0,e=Ct(t),a=Math.cos(e),r=-Math.sin(e),i=`
1452
+ `}}),n.curved&&n.paths?I.jsx("path",{id:i,d:n.paths[0]}):void 0]}),n._renderingConfiguration?.debug?I.jsx("rect",{stroke:"blue",fill:"none",x:n.x,y:n.y,width:n.width,height:n.height}):void 0,I.jsx("g",{mask:n.stepName?void 0:n.mask,children:I.jsx("g",{transform:`matrix(${a}, ${-r}, ${r}, ${a}, ${s}, ${l})`,children:I.jsx("text",{xmlSpace:"preserve",fontFamily:`'${n.fontData.name}'`,fontSize:n.fontSize,fontStyle:"normal",fontWeight:"normal",fill:h(),style:{whiteSpace:"pre",userSelect:"none"},stroke:A,strokeWidth:u,children:n.curved?I.jsx(hs,{text:c,curvedPathId:i,align:n.align}):d.map((g,p)=>I.jsx(us,{align:n.vertical?"center":n.align,fontSize:n.fontSize,thisLineIdx:p,amountLines:d.length,text:g,textboxHeight:n.height,textboxWidth:n.width,lineHeight:n.lineHeight,vertical:n.vertical,verticalAlign:n.verticalAlign,fontData:n.fontData},p))})})})]})},us=n=>{const t=()=>{if(n.lineHeight!==void 0)return n.lineHeight*n.fontSize;const r=wt(n.fontData.assetUrl),i=r.getFont(),o=n.fontSize/i.unitsPerEm;return r.getApproximateHeight()*o},e=()=>n.align==="left"?-n.textboxWidth/2:n.align==="right"?n.textboxWidth/2:0,a=()=>{const r=t(),i=n.textboxHeight/2;if(n.verticalAlign==="top")return-i+n.fontSize*3/4+n.thisLineIdx*r;if(n.verticalAlign==="bottom"){const s=n.amountLines-1-n.thisLineIdx;return i-n.fontSize/4-s*r}const o=(n.amountLines-1)/2;return(n.thisLineIdx-o)*r+n.fontSize/4};return I.jsx("tspan",{textAnchor:rr(n.align),x:e(),y:`${a()}px`,children:n.text})},hs=n=>{const t=`#${n.curvedPathId}`,e=()=>n.align==="left"?"0%":n.align==="right"?"100%":"50%";return I.jsx("textPath",{startOffset:e(),textAnchor:rr(n.align),href:t,xlinkHref:t,children:n.text})},gs=n=>{if(n.cachedObjectURL&&!n._renderingConfiguration?.omitCachedFields)return I.jsx(tr,{id:n.id,src:n.cachedObjectURL,x:n.x,y:n.y,width:n.width,height:n.height,rotation:n.rotation,preserveAspectRatio:"none",immutable:n.immutable,mask:n.stepName?void 0:n.mask});const t=n.rotation||0,e=Ct(t),a=Math.cos(e),r=-Math.sin(e),i=`
1453
1453
  matrix(1, 0, 0, 1, ${n.x}, ${n.y})
1454
1454
  matrix(1, 0, 0, 1, ${n.width/2}, ${n.height/2})
1455
1455
  matrix(${a}, ${-r}, ${r}, ${a}, 0, 0)
1456
1456
  matrix(1, 0, 0, 1, ${-n.width/2}, ${-n.height/2})
1457
- `;if(!n.svg)throw new Error(`Illustration element ${n.id} (stepName ${n.stepName}) lacked svg from src ${n.src} at render time.`);return I.jsx("g",{mask:n.stepName?void 0:n.mask,children:I.jsx("g",{transform:i,dangerouslySetInnerHTML:{__html:Da(n.svg,n.width,n.height,n.colors,n._renderingConfiguration?.spotColors)}})})};class or{constructor(){this.id=M(),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 r=this.prevCommands.filter(i=>i.sequenceId===t).pop();r&&(this.prevCommands=this.prevCommands.filter(i=>i.sequenceId!==t),r?.overrideOldState(e),this.prevCommands.push(r))}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 r=[...e?.elements||[]];return this.getLayoutDataWithState(a,r)}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=>We(t,e,a)}}initialize(t,e){if(e){this.state={transaction:e};return}let a={serializableWorkflow:{steps:[]},layouts:{}};t.forEach(r=>{a=new Oa(r).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 sr=n=>n.type===F.Image?I.jsx(Zn,{...n},n.id):n.type===F.Frame?I.jsx(Zo,{...n},n.id):n.type===F.Illustration?I.jsx(hs,{...n},n.id):n.type===F.Textbox?I.jsx(ds,{...n},n.id):n.type===F.Group?I.jsx(tr,{...n},n.id):null,We=(n,t,e)=>{const a=e.renderingConfiguration,r=a?.removeExcludedElements?t.filter(i=>!i.excludeFromExport):t;return I.jsx(Lo,{preserveAspectRatio:void 0,elements:r,backgroundColor:n.transparentBackground?void 0:e.backgroundColor?e.backgroundColor:"white",width:e.width||n.width,height:e.height||n.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:n.width,height:n.height},configuration:a,outlineArea:e.outlineArea,maxHeight:e.maxHeight,maxWidth:e.maxWidth,position:e.position,borderRadius:e.borderRadius,outlineColor:e.outlineColor})};function Ta(n){return n.sort((t,e)=>{const a=t.layer||0,r=e.layer||0;if(a<r)return-1;if(a>r)return 1;const i=t.layerIndex||0,o=e.layerIndex||0;return i<o?-1:i>o?1:0})}const ue=n=>{const t=n.variants;if(t){if(t.length===1)return t[0];if(n.defaultVariant!==void 0)return t.find(e=>e.id===n.defaultVariant)}},dt=new Map,Ft=new Map,Xe=new Map,lr=async(n,t)=>{if(!t){if(!n)throw new Error("No region or src supplied. Cannot construct frame!");return ma(n)}return tt(t)},ma=n=>{const t=n.width,e=n.height;return`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${t} ${e}'>
1457
+ `;if(!n.svg)throw new Error(`Illustration element ${n.id} (stepName ${n.stepName}) lacked svg from src ${n.src} at render time.`);return I.jsx("g",{mask:n.stepName?void 0:n.mask,children:I.jsx("g",{transform:i,dangerouslySetInnerHTML:{__html:xa(n.svg,n.width,n.height,n.colors,n._renderingConfiguration?.spotColors)}})})};class sr{constructor(){this.id=M(),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 r=this.prevCommands.filter(i=>i.sequenceId===t).pop();r&&(this.prevCommands=this.prevCommands.filter(i=>i.sequenceId!==t),r?.overrideOldState(e),this.prevCommands.push(r))}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 r=[...e?.elements||[]];return this.getLayoutDataWithState(a,r)}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=>We(t,e,a)}}initialize(t,e){if(e){this.state={transaction:e};return}let a={serializableWorkflow:{steps:[]},layouts:{}};t.forEach(r=>{a=new $a(r).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 lr=n=>n.type===x.Image?I.jsx(tr,{...n},n.id):n.type===x.Frame?I.jsx(ts,{...n},n.id):n.type===x.Illustration?I.jsx(gs,{...n},n.id):n.type===x.Textbox?I.jsx(As,{...n},n.id):n.type===x.Group?I.jsx(er,{...n},n.id):null,We=(n,t,e)=>{const a=e.renderingConfiguration,r=a?.removeExcludedElements?t.filter(i=>!i.excludeFromExport):t;return I.jsx(Vo,{preserveAspectRatio:void 0,elements:r,backgroundColor:n.transparentBackground?void 0:e.backgroundColor?e.backgroundColor:"white",width:e.width||n.width,height:e.height||n.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:n.width,height:n.height},configuration:a,outlineArea:e.outlineArea,maxHeight:e.maxHeight,maxWidth:e.maxWidth,position:e.position,borderRadius:e.borderRadius,outlineColor:e.outlineColor})};function Na(n){return n.sort((t,e)=>{const a=t.layer||0,r=e.layer||0;if(a<r)return-1;if(a>r)return 1;const i=t.layerIndex||0,o=e.layerIndex||0;return i<o?-1:i>o?1:0})}const ue=n=>{const t=n.variants;if(t){if(t.length===1)return t[0];if(n.defaultVariant!==void 0)return t.find(e=>e.id===n.defaultVariant)}},dt=new Map,xt=new Map,Ze=new Map,cr=async(n,t)=>{if(!t){if(!n)throw new Error("No region or src supplied. Cannot construct frame!");return pa(n)}return at(t)},pa=n=>{const t=n.width,e=n.height;return`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 ${t} ${e}'>
1458
1458
  <path id="target-path" d='M0 0 h ${t} v ${e} h ${-t} Z' />
1459
1459
  </svg>
1460
- `},gs=(n,t)=>{if(!t)return;const e=t.variants?.find(a=>a.id===n.frameVariantId)||ue(t);if(!e)throw new Error(`No variant with ID: ${n.frameVariantId}`);if(!e.asset)throw new Error(`No asset for variant with ID: ${n.frameVariantId}`);return e},he=async n=>{if(Xe.has(n))return Xe.get(n);const e=(async()=>{if(Ft.has(n))return Ft.get(n);await new Promise(u=>setTimeout(u,0));const r=lt().parseFromString(n,"image/svg+xml"),i=r.querySelector("svg");if(!i)throw new Error("Malformed frame SVG: <svg> tag not found");const o=i.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=r.getElementById("target-path"),A=r.getElementsByClassName("st0").item(0);if(d){const u=d.getAttribute("d");if(!u)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:u,width:c,height:l};return Ft.set(u,h),h}if(A){const u=A.getAttribute("d");if(!u)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:u,width:c,height:l};return Ft.set(u,h),h}throw new Error("Malformed frame SVG")})();return Xe.set(n,e),e},Na=(n,t,e,a)=>{const r=t.width/t.height,i=n.width/n.height;let o;a?i>r?o=t.height/n.height:o=t.width/n.width:i>r?o=t.width/n.width:o=t.height/n.height,e?.scale!==void 0&&(o*=e?.scale);const s=t.width/2,l=t.height/2,c=s-n.width/2*o,d=e?.left||c,A=l-n.height/2*o,u=e?.top||A;return{x:d,y:u,zoom:o}},pa=async n=>{if(dt.has(n))return dt.get(n);if(n.startsWith("data:image/svg+xml")){const e=Ai.dataUriToBuffer(n),a=new TextDecoder().decode(e.buffer),r=Ra(a),i={src:n,width:r.width,height:r.height,aspect:r.width/r.height};return dt.set(n,i),i}if((n.split(".").pop()?.toLowerCase()??"")==="svg"){const e=await Qa(n),a=e.width,r=e.height,i={src:n,width:a,height:r,aspect:a/r};return dt.set(n,i),i}else{const e=await $e(n,!0),a=await ce(e),r={src:n,width:a.width,height:a.height,aspect:a.width/a.height};return dt.set(n,r),r}},Qa=async n=>{const t=await tt(n);return Ra(t)},cn=n=>n.endsWith("mm")?Number(n.replace("mm",""))*3.7795275591:n.endsWith("px")?Number(n.replace("px","")):Number(n),Ra=n=>{const a=lt().parseFromString(n,"image/svg+xml").querySelector("svg");if(!a)throw new Error("No svg tag found, this svg must be malformed!");const r=a.getAttribute("viewBox"),i=a.getAttribute("width"),o=a.getAttribute("height"),s=o&&i?[0,0,cn(i),cn(o)]:r?.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]}},qt=(n,t)=>{const e=n.layoutState.elements.filter(r=>r.layer===t),a=Math.max(...e.map(r=>r.layerIndex).filter(r=>r!==void 0));return Math.max(a,0)+1},cr=async n=>new Promise(t=>{tt(n).then(e=>{t(e)}).catch(e=>console.error(e))}),Ze=new Map,ie=async n=>{if(Ze.has(n))return Ze.get(n);const t=async r=>new Promise((i,o)=>{try{if(!(!!URL&&!!URL.createObjectURL))throw new Error("Environment incapable of generating ObjectURL");r.toBlob(l=>{if(!l)throw r.width===0||r.height===0?new Error(`Canvas dimensions are invalid (${r.width},${r.height})`):r.width*r.height>=268435456?new Error(`Canvas dimensions exceed device limit (${r.width},${r.height})`):new Error("Couldn't generate object URL for Illustration, the blob was undefined!");i(URL.createObjectURL(l))})}catch(s){o(s)}}),a=(async()=>{const o=lt().parseFromString(n,"image/svg+xml").firstElementChild;if(!o)throw new Error("Failed to read SVG");const l=St().serializeToString(o),c=ft(),d=c.getContext("2d"),A=await ba.Pith.from(d,l,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:ft,createImage:le,DOMParser:xa(),fetch:it}),u=o.getAttribute("width"),h=o.getAttribute("height"),g=2048;if(h&&u){const m=parseFloat(h),f=parseFloat(u)/m;f>1?A.resize(g,g/f):A.resize(g*f,g)}else A.resize(g,g);return await A.render(),await t(c)})();return Ze.set(n,a),a},Gt=async(n,t,e,a)=>{const r=n.layoutState.layout.useEditableArea&&n.layoutState.layout.editableArea||{width:n.layoutState.layout.width,height:n.layoutState.layout.height,x:0,y:0},i=r.width<r.height?r.width:r.height,o=n.layoutState.layout.useEditableArea?i/1.3:i/2,s={top:r.y+r.height/2-o/2,left:r.x+r.width/2-o/2,width:o,height:o,rotation:0,panelId:n.layoutState.layout.panelId};if(e&&t===F.Illustration){const l=await ot(await cr(e)),u=lt().parseFromString(l.svg,"image/svg+xml").firstElementChild.getAttribute("viewBox");if(!u)throw new Error("SVG missing viewBox.");const h=s.height,g=u.split(" "),m=parseFloat(g[2])||1,p=parseFloat(g[3])||1,f=m/p;s.height=s.width/f,s.top+=(h-s.height)/2}if(e&&t===F.Image){const l=s.height,c=await $e(e),d=await ce(c),A=d.width/d.height;s.height=s.width/A,s.top+=(l-s.height)/2}if(e&&t===F.Textbox&&a?.text&&a?.fontScale){await xt(e);const l=wt(e),c=mt(a.text,a?.fontScale,l);s.width=Math.min(c,r.width*.85),s.left=r.x+r.width/2-s.width/2}return s};class ms{static async getFrame(t,e){const a=await lr(e.region,e.src),r=await he(a),i=e.region||await Gt(t,F.Frame);return{id:M(),x:i.left,y:i.top,width:i.width,height:i.height,layer:i.layer||0,layerIndex:i.layerIndex||qt(t,i.layer||0),rotation:i.rotation,scaleX:i.width/r.width,scaleY:i.height/r.height,path:r.path,dataWidth:r.width,dataHeight:r.height,type:F.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:i.immutable}}static async getImage(t,e){const a=e.region||await Gt(t,F.Image,e.src);return{id:M(),src:e.src,type:F.Image,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||qt(t,a.layer||0),immutable:a.immutable,preserveAspectRatio:"none"}}static async getTextbox(t,e){const{configuration:a,fontSrc:r,designInputStep:i}=e,o=await xt(r),s={assetUrl:r,name:o.names.fullName.en},l=i?.text||a.defaultText||"",c=a.replaceableText?a.replaceableText.replace("{{}}",l):l,d=ke(c,{vertical:a.vertical,uppercase:a.uppercase}),A=e.region||await Gt(t,F.Textbox,r,{text:d,fontScale:a.size?a.size/o.unitsPerEm:void 0}),u=Ae({id:M(),type:F.Textbox,x:A.left,y:A.top,width:A.width,height:A.height,align:cs(a.textAlign,a.vertical),curved:a.curved,fill:i?.color||a.colour||"#000000",fontData:s,layer:A.layer||0,layerIndex:A.layerIndex||qt(t,A.layer||0),paths:a.paths,rotation:A.rotation,vertical:a.vertical,verticalAlign:a.verticalAlign||"middle",algorithm:Pt.Traditional,fontSize:a.size||Math.max(Math.round(A.height*.025),1),text:d,input:l},d),h=os({...A,height:u.height},s,u.fontSize,u?.text?.split(`
1460
+ `},ms=(n,t)=>{if(!t)return;const e=t.variants?.find(a=>a.id===n.frameVariantId)||ue(t);if(!e)throw new Error(`No variant with ID: ${n.frameVariantId}`);if(!e.asset)throw new Error(`No asset for variant with ID: ${n.frameVariantId}`);return e},he=async n=>{if(Ze.has(n))return Ze.get(n);const e=(async()=>{if(xt.has(n))return xt.get(n);await new Promise(u=>setTimeout(u,0));const r=lt().parseFromString(n,"image/svg+xml"),i=r.querySelector("svg");if(!i)throw new Error("Malformed frame SVG: <svg> tag not found");const o=i.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=r.getElementById("target-path"),A=r.getElementsByClassName("st0").item(0);if(d){const u=d.getAttribute("d");if(!u)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:u,width:c,height:l};return xt.set(u,h),h}if(A){const u=A.getAttribute("d");if(!u)throw new Error("Malformed frame SVG: 'd' attribute not found on target element");const h={path:u,width:c,height:l};return xt.set(u,h),h}throw new Error("Malformed frame SVG")})();return Ze.set(n,e),e},Qa=(n,t,e,a)=>{const r=t.width/t.height,i=n.width/n.height;let o;a?i>r?o=t.height/n.height:o=t.width/n.width:i>r?o=t.width/n.width:o=t.height/n.height,e?.scale!==void 0&&(o*=e?.scale);const s=t.width/2,l=t.height/2,c=s-n.width/2*o,d=e?.left||c,A=l-n.height/2*o,u=e?.top||A;return{x:d,y:u,zoom:o}},fa=async n=>{if(dt.has(n))return dt.get(n);if(n.startsWith("data:image/svg+xml")){const e=ui.dataUriToBuffer(n),a=new TextDecoder().decode(e.buffer),r=Oa(a),i={src:n,width:r.width,height:r.height,aspect:r.width/r.height};return dt.set(n,i),i}if((n.split(".").pop()?.toLowerCase()??"")==="svg"){const e=await Ra(n),a=e.width,r=e.height,i={src:n,width:a,height:r,aspect:a/r};return dt.set(n,i),i}else{const e=await $e(n,!0),a=await ce(e),r={src:n,width:a.width,height:a.height,aspect:a.width/a.height};return dt.set(n,r),r}},Ra=async n=>{const t=await at(n);return Oa(t)},dn=n=>n.endsWith("mm")?Number(n.replace("mm",""))*3.7795275591:n.endsWith("px")?Number(n.replace("px","")):Number(n),Oa=n=>{const a=lt().parseFromString(n,"image/svg+xml").querySelector("svg");if(!a)throw new Error("No svg tag found, this svg must be malformed!");const r=a.getAttribute("viewBox"),i=a.getAttribute("width"),o=a.getAttribute("height"),s=o&&i?[0,0,dn(i),dn(o)]:r?.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]}},qt=(n,t)=>{const e=n.layoutState.elements.filter(r=>r.layer===t),a=Math.max(...e.map(r=>r.layerIndex).filter(r=>r!==void 0));return Math.max(a,0)+1},dr=async n=>new Promise(t=>{at(n).then(e=>{t(e)}).catch(e=>console.error(e))}),ta=new Map,ie=async n=>{if(ta.has(n))return ta.get(n);const t=async r=>new Promise((i,o)=>{try{if(!(!!URL&&!!URL.createObjectURL))throw new Error("Environment incapable of generating ObjectURL");r.toBlob(l=>{if(!l)throw r.width===0||r.height===0?new Error(`Canvas dimensions are invalid (${r.width},${r.height})`):r.width*r.height>=268435456?new Error(`Canvas dimensions exceed device limit (${r.width},${r.height})`):new Error("Couldn't generate object URL for Illustration, the blob was undefined!");i(URL.createObjectURL(l))})}catch(s){o(s)}}),a=(async()=>{const o=lt().parseFromString(n,"image/svg+xml").firstElementChild;if(!o)throw new Error("Failed to read SVG");const l=St().serializeToString(o),c=ft(),d=c.getContext("2d"),A=await Ba.Pith.from(d,l,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:ft,createImage:le,DOMParser:Fa(),fetch:it}),u=o.getAttribute("width"),h=o.getAttribute("height"),g=2048;if(h&&u){const p=parseFloat(h),f=parseFloat(u)/p;f>1?A.resize(g,g/f):A.resize(g*f,g)}else A.resize(g,g);return await A.render(),await t(c)})();return ta.set(n,a),a},Gt=async(n,t,e,a)=>{const r=n.layoutState.layout.useEditableArea&&n.layoutState.layout.editableArea||{width:n.layoutState.layout.width,height:n.layoutState.layout.height,x:0,y:0},i=r.width<r.height?r.width:r.height,o=n.layoutState.layout.useEditableArea?i/1.3:i/2,s={top:r.y+r.height/2-o/2,left:r.x+r.width/2-o/2,width:o,height:o,rotation:0,panelId:n.layoutState.layout.panelId};if(e&&t===x.Illustration){const l=await ot(await dr(e)),u=lt().parseFromString(l.svg,"image/svg+xml").firstElementChild.getAttribute("viewBox");if(!u)throw new Error("SVG missing viewBox.");const h=s.height,g=u.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===x.Image){const l=s.height,c=await $e(e),d=await ce(c),A=d.width/d.height;s.height=s.width/A,s.top+=(l-s.height)/2}if(e&&t===x.Textbox&&a?.text&&a?.fontScale){await Dt(e);const l=wt(e),c=mt(a.text,a?.fontScale,l);s.width=Math.min(c,r.width*.85),s.left=r.x+r.width/2-s.width/2}return s};class ps{static async getFrame(t,e){const a=await cr(e.region,e.src),r=await he(a),i=e.region||await Gt(t,x.Frame);return{id:M(),x:i.left,y:i.top,width:i.width,height:i.height,layer:i.layer||0,layerIndex:i.layerIndex||qt(t,i.layer||0),rotation:i.rotation,scaleX:i.width/r.width,scaleY:i.height/r.height,path:r.path,dataWidth:r.width,dataHeight:r.height,type:x.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:i.immutable}}static async getImage(t,e){const a=e.region||await Gt(t,x.Image,e.src);return{id:M(),src:e.src,type:x.Image,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||qt(t,a.layer||0),immutable:a.immutable,preserveAspectRatio:"none"}}static async getTextbox(t,e){const{configuration:a,fontSrc:r,designInputStep:i}=e,o=await Dt(r),s={assetUrl:r,name:o.names.fullName.en},l=i?.text||a.defaultText||"",c=a.replaceableText?a.replaceableText.replace("{{}}",l):l,d=ke(c,{vertical:a.vertical,uppercase:a.uppercase}),A=e.region||await Gt(t,x.Textbox,r,{text:d,fontScale:a.size?a.size/o.unitsPerEm:void 0}),u=Ae({id:M(),type:x.Textbox,x:A.left,y:A.top,width:A.width,height:A.height,align:ds(a.textAlign,a.vertical),curved:a.curved,fill:i?.color||a.colour||"#000000",fontData:s,layer:A.layer||0,layerIndex:A.layerIndex||qt(t,A.layer||0),paths:a.paths,rotation:A.rotation,vertical:a.vertical,verticalAlign:a.verticalAlign||"middle",algorithm:Pt.Traditional,fontSize:a.size||Math.max(Math.round(A.height*.025),1),text:d,input:l},d),h=ss({...A,height:u.height},s,u.fontSize,u?.text?.split(`
1461
1461
  `)||[],u.align);return{...u,x:h.left,y:h.top+(A.height-h.height)/2,width:h.width,height:h.height}}static async getShape(t,e){const a=`
1462
1462
  <svg
1463
1463
  xmlns="http://www.w3.org/2000/svg"
@@ -1478,7 +1478,7 @@
1478
1478
  fill="${e.color}"
1479
1479
  />
1480
1480
  </svg>
1481
- `,r={};r["spiff-fill-shape"]={browserValue:e.color};const i=e.region||await Gt(t,F.Illustration),o=M();return{stepRegion:e.region,colors:r,id:o,svg:a,type:F.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layer:i.layer||0,layerIndex:i.layerIndex||qt(t,i.layer||0),immutable:i.immutable}}static async getIllustration(t,e){const a=e.region||await Gt(t,F.Illustration,e.src),r=await ot(await cr(e.src)),i=await ie(r.svg),o=M();return{cachedObjectURL:i,stepRegion:e.region,colors:r.colors,id:o,src:e.src,svg:r.svg,type:F.Illustration,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||qt(t,a.layer||0),immutable:a.immutable}}}class V extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,V.prototype)}}const $=(n,t)=>_(n,t).elements.find(r=>r.id===n),_=(n,t)=>{const e=Object.values(t).find(a=>a.elements.some(r=>r.id===n));if(!e)throw new V;return e},Z=(n,t)=>{const e=[...t.elements.filter(r=>r.id!==n.id),n],a=Ta(e);return{layout:t.layout,elements:a,modificationID:M()}},fa=async n=>{const t=[...Object.keys(n.layouts)],e=[...new Set(t)];for(let a=0;a<e.length;a++){const r=e[a],i=n.layouts[r];await Promise.all(i.elements.map(async o=>{if(o.type==="illustration"){const s=o;if(s.src&&!s.svg){const l=await tt(s.src),c=await ot(l);s.svg=Da(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 tt(s.pattern?.src),c=await ot(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 n.layouts){const r=n.layouts[a].elements.filter(o=>o.type===F.Illustration);for(let o=0;o<r.length;++o){const s=r[o];if(s.src&&s.svg)try{s.cachedObjectURL=await ie(s.svg)}catch(l){console.log(l)}}const i=n.layouts[a].elements.filter(o=>o.type===F.Textbox);for(let o=0;o<i.length;++o){const s=i[o];s.fontData?.assetUrl&&await xt(s.fontData.assetUrl)}}};class N{undo(){if(!this.oldState)throw new Error("Cannot undo.");return this.oldState}overrideOldState(t){this.oldState=t}}class dn extends N{constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class ps extends N{constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;const a={...e,x:this.x,y:this.y},r=_(e.id,Object.values(t.layouts)),i=Z(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class fs extends N{constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;const a={...e,rotation:this.angle},r=_(e.id,Object.values(t.layouts)),i=Z(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class Cs extends N{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=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;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===Pt.Autosize?o.text:o.input)??"";a=Ae(o,s,e)}const r=_(e.id,Object.values(t.layouts)),i=Z(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class Q extends N{constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class Oa extends N{constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:M()}}}}}class z extends N{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:M()}}}}const r=e[e.length-1],i=r.productOverlay?r:null;i&&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 i&&o.push(i),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:o,modificationID:M()}}}}assignIndex(t,e){if(e.length===0)return 0;const a=e.filter(r=>(r.layer||0)===(t.layer||0)).sort((r,i)=>(r.layerIndex||0)-(i.layerIndex||0))[e.length-1]?.layerIndex;return a!==void 0?a+1:0}}class yt extends N{constructor(t){super(),this.id=t}apply(t){this.oldState=t;let e=!1;const a=Object.values(t.layouts).map(i=>(i.elements.filter(s=>s.id!==this.id).length!==i.elements.length&&(e=!0),{...i,elements:i.elements.filter(s=>s.id!==this.id),modificationID:M()}));e||console.log(`Failed to delete element ${this.id}`);const r={};return a.forEach(i=>{r[i.layout.id]=i}),{...t,layouts:r}}}class dr extends N{constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},r=_(e.id,Object.values(t.layouts)),i=Z(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class ta extends N{constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;const a={...e,textFillImage:this.imageFill},r=_(e.id,Object.values(t.layouts)),i=Z(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class Ar extends N{constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;const a={...e,fontSize:this.size},r=_(e.id,Object.values(t.layouts)),i=(!e.algorithm||e.algorithm===Pt.Autosize?e.text:e.input)??"",o=Z(Ae(a,i),r);return{...t,layouts:{...t.layouts,[r.layout.id]:o}}}}class Ca extends N{constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;const a={...e,fontData:this.fontData},r=_(e.id,Object.values(t.layouts)),i=(!e.algorithm||e.algorithm===Pt.Autosize?e.text:e.input)??"",o=Z(Ae(a,i),r);return{...t,layouts:{...t.layouts,[r.layout.id]:o}}}}class ur extends N{constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;const a={...e,align:this.align},r=_(e.id,Object.values(t.layouts)),i=Z(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class ws extends N{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),r=e.elements[a].pattern,i=[...e.elements];i.splice(a,1,{...e.elements[a],pattern:{...r,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:i,modificationID:M()};return{...t,layouts:{...t.layouts,[e.layout.id]:o}}}}class ys extends N{constructor(t,e,a,r,i){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=r,this.thresholdSaturation=i}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},r=_(e.id,Object.values(t.layouts)),i=Z(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class Ss extends N{constructor(t,e){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;const a={...e,src:this.src},r=_(e.id,Object.values(t.layouts)),i=Z(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class hr extends N{constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;const a=_(e.id,Object.values(t.layouts)),r=Z(Ae(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:r}}}}class ea extends N{constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},r=_(e.id,Object.values(t.layouts)),i=Z(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class wa extends N{constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;const a=e.colors||{},r=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:r?.spotColor,pmsValue:r?.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:r?.spotColor,pmsValue:this.fill.pmsValue};const i={...e,colors:a},o=_(e.id,Object.values(t.layouts)),s=Z(i,o);return{...t,layouts:{...t.layouts,[o.layout.id]:s}}}}class vs extends N{constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},r=_(e.id,Object.values(t.layouts)),i=Z(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class Es extends N{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!$(this.id,Object.values(t.layouts)).id)throw new V;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 r=a.elements.findIndex(o=>o.id===this.id);a.elements.push(a.elements.splice(r,1)[0]);const i=[...a.elements];return i.forEach((o,s)=>o.layerIndex=s),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:i,modificationID:M()}}}}}class bs extends N{constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=$(this.id,Object.values(t.layouts));if(!e.id)throw new V;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 r=a.elements.findIndex(s=>s.id===this.id);a.elements.splice(r,1),a.elements.unshift(e);const i=[...a.elements],o=i.splice(r,1)[0];return i.splice(r,0,o),i.forEach((s,l)=>s.layerIndex=l),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:i,modificationID:M()}}}}}class Bs extends N{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!$(this.id,Object.values(t.layouts)).id)throw new V;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 r=a.elements.findIndex(l=>l.id===this.id),i=r+1,o=[...a.elements],s=o.splice(r,1)[0];return o.splice(i,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:M()}}}}}class Is extends N{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!$(this.id,Object.values(t.layouts)).id)throw new V;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 r=a.elements.findIndex(l=>l.id===this.id),i=r-1,o=[...a.elements],s=o.splice(r,1)[0];return o.splice(i,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:M()}}}}}class An{constructor(t,e,a){this.processRegion=async r=>{const i=this.layouts.find(l=>l.panelId===r.panelId);if(!i)throw new j(r);let o="";if(this.configuration.type===v.ProductOverlay){let l="";if(this.product?.overlayImageUrl&&(l=this.product.overlayImageUrl),o=l,!l)throw new ne(this.configuration,"Couldn't find an asset for product overlay step")}const s=this.evaluateAssetType();if(s===F.Image){const l=this.configuration.type===v.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:M(),src:l,type:s,y:r.top,x:r.left,width:r.width,height:r.height,layer:r.layer,layerIndex:r.layerIndex,immutable:r.immutable,productOverlay:this.configuration.type===v.ProductOverlay?!0:void 0,rotation:r.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:c.id,region:r},command:new z(c,i)}}else{const l=this.configuration.type===v.SilentIllustration?this.configuration.data.asset?.fileLink:o,d=await ot(await(async()=>new Promise((u,h)=>{if(!l){h("Undefined vector silent step source");return}tt(l,!0).then(g=>{u(g)}).catch(g=>console.error(g))}))()),A={stepName:this.configuration.stepName,id:M(),cachedObjectURL:await ie(d.svg),src:l,svg:d.svg,colors:d.colors,type:s,y:r.top,x:r.left,width:r.width,height:r.height,layer:r.layer,layerIndex:r.layerIndex,rotation:r.rotation,immutable:r.immutable,productOverlay:this.configuration.type===v.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:A.id,region:r},command:new z(A,i)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new ne(this.configuration,"Missing regions.");if(this.configuration.type===v.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}else return this.configuration.type===v.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===v.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")?F.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),F.Illustration)}}const gr=async n=>{const t=`${At.getServicesApiUrl()}/shortener`;try{return(await(await it(t,{method:"POST",body:JSON.stringify({longUrl:n}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new Oe("Failed to shorten URL, see console.")}};class mr{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,r=3e3,i=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=r,this.maxAttempts=i,this.poll()}}class Ps{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const r=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}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{const c=r?.storage?.videoShortUrl,d=r?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,r){const i=async()=>{const h=(await De([e]))[0],g=h?.versions?.find(m=>m.name==="mpeg4")?.link;return{asset:h,link:g}},o=await new Promise((h,g)=>{new mr(async()=>!!(await i()).link,async()=>{const m=await i();if(!m.link||!m.link)throw new Qt(m.asset);h({rel:"mpeg4",href:m.link})},()=>{g("Poller timed out with 40 attempts @ 3 second interval")},3e3,40)});t.forEach(h=>a.getCommandDispatcher()(new yt(h.id)));const s=r.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(s+r.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 Oe("Cannot create QR code, URL too long.");const d=await gr(c);if(!r.data||!r.data.regions)throw new ne(r,"Missing regions.");const A=await this.regionElements(r),u=await this.command(d,A,a,r.stepName);return u&&(u.command&&a.getCommandDispatcher()(u.command),u.followup&&await u.followup()),await a.setSelectionsAndElements(r.stepName,[],A,async()=>{a.updateStorage(r.stepName,{videoShortUrl:d,videoUrl:o.href})}),d}async regionElements(t){const e=a=>({id:M(),region:a});return t.data.regions.map(e)}async command(t,e,a,r){const i=a.getLayouts(),s=`data:image/svg+xml;base64,${btoa(await Bn.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,A=i.find(u=>u.panelId===d?.panelId);if(!A&&d)throw new j(d);if(A&&!d)throw new Error("Region not found");if(!A||!d)throw new Error("Neither a region or layout found!");return new z({stepRegion:d,stepName:r,id:c.id,src:s,type:F.Image,y:d.top,x:d.left,width:d.width,height:d.height,rotation:0},A)});return{command:new Q(l),followup:async()=>{}}}}const $a=new Ps;class Me{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return ma(e);const a=t.asset;if(!a)throw new pt(t);const r=a.fileLink;if(r)return tt(r,!0);throw new Qt(a)}}async init(t,e,a){const r=a?.serializableWorkflow.steps.find(s=>s.stepName===t.stepName);if(r?.storage&&Object.keys(r.storage).length!==0||r?.selectedVariants&&r.selectedVariants.length!==0)return await this.reload(t,e,a),null;t.mandatory&&e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]);let i;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&&(i=(await R.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option&&t.option.variants&&t.option.variants.length>0){const s=t.option,l=W.getDefaultVariant(s);return l?this.selectVariantCommand(t,l,[],e,void 0,i||t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,i||t.data.placeholderImageUrl)}async reload(t,e,a){const r=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}));if(!t.option||(t.option.variants||[]).length===0){const c=t.data.regions.map(d=>ma(d));e.updateStorage(t.stepName,{currentFrameSources:c})}if(r){const c=async()=>{const d=r.storage?.colors,A=r.storage?.framePatternSrc,u=r.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:u,framePatternSrc:A}),A){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,h,!0,d),e.updateMetadata(t.stepName,{image:A}),e.updateStorage(t.stepName,{framePatternSrc:A}),this.validateColorCount(t,e)}if(u?.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(u)}e.setMandatoryFulfilled(t.stepName,!0)};if(r.selectedVariants&&r.selectedVariants.length>0){const d=r.selectedVariants[0].id;if(t.option&&d){const A=t.option.variants?.find(u=>u.id===d);A&&await e.setSelectionsAndElements(t.stepName,[A],l,async()=>{const u=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(A,h)));e.updateStorage(t.stepName,{currentFrameSources:u}),await c()})}}else await e.setSelectionsAndElements(t.stepName,[],l,c)}}async availableColors(t,e){return t.data.colorOption?.variants?.map(r=>({fill:r.color,stroke:r.color,variant:r,pmsValue:r.name}))??[]}selectImage(t,e,a,r=!0){const i=Me.patternSource(e),o=a.getStepStorage(t.stepName)?.framePatternSrc;if(o&&o===i)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 mr(async()=>{const d=(await R.getFromServer(e.key||"")).versions?.find(u=>u.name==="svg");return d?(await it(d.link)).status===200:!1},()=>{R.getLocalOrFromServer(e.key||"").then(c=>{this.loadPatternFromAsset(c,t,a,r).then(l)})},()=>{throw new Oe("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,r)}async selectVariant(t,e,a,r,i){const o=await this.selectVariantCommand(t,e,a,r,i);o&&(o.command&&r.getCommandDispatcher()(o.command),o.followup&&await o.followup())}getCreateElementCommand(t,e,a,r){return new z({id:t,type:F.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,stepName:r.stepName,disablePlaceholder:r.disablePlaceholder,pattern:r.pattern,immutable:e.immutable},a)}async loadPatternFromString(t,e,a=!0,r=void 0,i){if(t.endsWith("svg")){const o=await Qa(t),s=o.width,l=o.height,c=await tt(t);if(i){const u=c.match(/<(image|linearGradient|radialGradient)(\s|>|\/>)/gim);if(u&&u.length>0)throw new Error("Vector files may not include images or gradients when a color limit is specified.")}const d=await ot(c),A={src:t,width:s,height:l,aspect:s/l,svg:d.svg,colors:r??d.colors};dt.set(t,A),e.setPatternData(A,a)}else{const o=await $e(t,!0),s=await ce(o),l={src:t,width:s.width,height:s.height,aspect:s.width/s.height,svg:void 0,colors:void 0};dt.set(t,l),e.setPatternData(l,a)}}changeColors(t,e,a){const r=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!r||!r.getImageData()?.svg){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const i=this.calculateColorMetadata(r,t,a);e.updateMetadata(t.stepName,{colors:i.metadataColors}),e.updateStorage(t.stepName,{colors:i.storageColors}),r.setPatternData({...r.getImageData(),colors:i.newColors},!1),this.validateColorCount(t,e)}getUniqueColorCount(t,e){const a=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!a)return 0;const r=a.getImageData()?.colors??{},i=[];for(const o in r){const s=r[o];if(s.pmsValue){const l=s.pmsValue.trim().toLocaleLowerCase();i.includes(l)||i.push(l)}else if(s.browserValue){const l=zn(s.browserValue);i.includes(l)||i.push(l)}}return i.length}calculateColorMetadata(t,e,a){if(!t.getImageData()?.svg)return{newColors:void 0,metadataColors:void 0,storageColors:void 0};const r={...t.getImageData().colors??{}},i={};Object.entries(r).forEach(([l,c])=>{const d={browserValue:c.browserValue};i[l]=d});for(const[l,c]of a.entries())r[l]={browserValue:c.browserValue,pmsValue:c.pmsValue},i[l]=c;let o=Array.from(Object.values(r)).map(l=>l.browserValue);const s=e.data.colorOption;return s&&s.variants?.forEach(l=>{o=o.map(c=>c.toLowerCase()===l.color?.toLowerCase()?l.name:c)}),{newColors:r,metadataColors:o,storageColors:i}}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,r,i,o){const s=r.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)));i&&i(!0);const c=t.data.initialZoomLevel,d=await Promise.all(t.data.regions.map(async(h,g)=>{const m=await he(l[g]),p=s.getImageData(),f=a.map(x=>new yt(x.id)),S=p?Na(p,m,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,b=p?{id:M(),src:p.src,x:S?.x||0,y:S?.y||0,width:p.width,height:p.height,scaleX:S?.zoom||1,scaleY:S?.zoom||1,rotation:0}:void 0,P=M(),E=r.getLayouts().find(x=>x.panelId===h.panelId);if(!E)throw new j(h);return{command:this.getCreateElementCommand(P,h,E,{frameData:m,pattern:b,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:P,region:h},removeExistingCommands:f}})),A=d.map(h=>h.command),u=d.map(h=>h.removeExistingCommands).flat();return{command:new Q([...A,...u]),followup:async()=>{i&&i(!1),await r.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(h=>h.regionEl)],async()=>{if(r.updateStorage(t.stepName,{currentFrameSources:l}),o){const h=r.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(r=>r.name==="svg");if(e?.link)return e.link;const a=t.fileLink;if(a)return a;throw new Qt(t)}async loadPatternFromAsset(t,e,a,r){const i=Me.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(i,s,r,void 0,e.data.colorPickerEnabled&&!!e.data.maxColors&&e.data.maxColors>0)}catch(c){throw a.markUpdateCompleted(o),c}const l=this.calculateColorMetadata(s,e,new Map(Object.entries(s.getImageData()?.colors??{})));a.updateMetadata(e.stepName,{image:i,colors:l.metadataColors}),a.updateStorage(e.stepName,{framePatternSrc:i,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 ht=new Me;class xs{async getIllustrationBody(t){return new Promise(e=>{tt(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,r){return new z({stepRegion:e,stepName:r.stepName,colors:r.svg.colors,id:t,src:r.src,svg:r.svg.svg,cachedObjectURL:r.objectURL,type:F.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},a)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return $(a[0].id,e.getAllLayoutData()).colors}catch{return[]}}async init(t,e,a){const r=t.option;if(!r)return null;if(a)return this.reload(t,e,a);{const i=W.getDefaultVariant(r);if(i)return await this.selectVariantCommand(t,i,[],()=>{},e)}return null}async reload(t,e,a){const r=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(r?.selectedVariants){const c=r.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(A=>A.id===c);if(d){const A=s.map(u=>({id:u.id,region:u.stepRegion}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{e.updateMetadata(t.stepName,{colors:r.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){const a=t.data.colorOption;return a?a?a.variants?.map(r=>({fill:r.color,stroke:r.color,variant:r,pmsValue:r.name})):[]:[]}async changeColorsCommand(t,e,a,r,i){const o={};for(const[d,A]of i.entries())typeof A=="string"?o[d]={browserValue:A,spotColor:void 0,pmsValue:void 0}:o[d]={browserValue:A.browserValue,spotColor:A.spotColor,pmsValue:A.pmsValue};const s=Da(t,e,a,o),l=await ie(s),c=[];for(const d of r){for(const[A,u]of i.entries())c.push(new wa(d,A,u));c.push(new vs(d,s,l))}return new Q(c)}async changeColors(t,e,a,r,i){if(e.length===0)return;const o=$(e[0].id,r().map(h=>h.layoutState)),s={...o.colors},l={};Object.entries(s).forEach(([h,g])=>{const m={browserValue:g.browserValue,pmsValue:g.pmsValue},p=g.spotColor;p&&(m.spotColor={profileName:p.profileName,namedColor:p.namedColor}),l[h]=m});for(const[h,g]of i.entries()){const m=typeof g=="string"?g:g.browserValue,p=typeof g=="string"?void 0:g.pmsValue;s[h]={browserValue:m,spotColor:s[h]?.spotColor,pmsValue:p},l[h]={browserValue:m}}let c=Array.from(Object.values(s)).map(h=>h.browserValue);const d=t.data.colorOption;d&&d.variants?.forEach(h=>{c=c.map(g=>g.toLowerCase()===h.color?.toLowerCase()?h.name:g)}),a.updateMetadata(t.stepName,{colors:c});const A=new Map;if(Object.entries(s).forEach(([h,g])=>{A.set(h,g)}),!o.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const u=await this.changeColorsCommand(o.svg,o.width,o.height,e.map(h=>h.id),A);a.updateStorage(t.stepName,{colors:l}),a.getCommandDispatcher()(u)}async selectVariant(t,e,a,r,i){const o=await this.selectVariantCommand(t,e,a,r,i);o&&(o.command&&i.getCommandDispatcher()(o.command),o.followup&&await o.followup())}async selectVariantCommand(t,e,a,r,i){if(!t.data||!t.data.regions)throw new ne(t,"Missing regions.");r(!0);const o=a.map(f=>new yt(f.id));t.mandatory&&i.setMandatoryFulfilled(t.stepName,!1);const s=e.asset;if(!s)throw new pt(e);const l=s.fileLink;if(!l)throw new Qt(s);const c=await ot(await this.getIllustrationBody(l)),d=await ie(c.svg),A=f=>{const S=i.getLayouts().find(P=>P.panelId===f.panelId);if(!S)throw new j(f);const b=M();return{regionElement:{id:b,region:f},command:this.getCreateElementCommand(b,f,S,{stepName:t.stepName,src:l,objectURL:d,svg:c})}},u=t.data.regions.map(A),g=[...u.map(f=>f.command),...o];let m=Array.from(Object.values(c.colors)).map(f=>f.browserValue);const p=t.data.colorOption;return p&&p.variants?.forEach(f=>{m=m.map(S=>S.toLowerCase()===f.color?.toLowerCase()?f.name:S)}),i.updateMetadata(t.stepName,{colors:m}),{command:new Q(g),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],u.map(S=>S.regionElement),async()=>{i.setMandatoryFulfilled(t.stepName,!0),r(!1)});const f=s.assetConfiguration?.defaultColorVariants||[];if(f.length!==0){const S={};(s.assetConfiguration?.channelNumbers||[]).forEach(P=>{const C=f.find(E=>E.channelNumber===P.number);C&&(S[`${P.id.replace(/\W/g,"")}`]={browserValue:C?.variant?.color||""})}),await this.changeColors(t,u.map(P=>P.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map(Object.entries(S)))}if(t.data.colorPickerEnabled){const S=await this.availableColors(t,i)||[],b=Object.keys(c.colors),P=S.length===1&&b.length===1;if(P){const C=S[0],E=b[0];await this.changeColors(t,u.map(x=>x.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map([[E,C.variant.color]]))}!P&&f.length===0&&await this.changeColors(t,u.map(C=>C.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map)}}}}}const Jt=new xs;class Ds{async init(t,e,a){const r=t.option;if(!r)throw new ae(t);if(a)await this.reload(t,e,a);else{const i=W.getDefaultVariant(r);if(i)return await this.selectVariantLambda(t,i,e,()=>{})}return null}async reload(t,e,a){const r=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 ae(t);if(r?.selectedVariants){const c=r.selectedVariants[0].id;if(c){const d=l.variants?.find(A=>A.id===c);if(d){const A=d.material,u=s.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{const h=e.getModelContainer();if(h){const g=t.data.targetMaterials.map(m=>h.applyMaterialVariant(m,l.id||"",A||{}));Promise.all(g).then(()=>e.setMandatoryFulfilled(t.stepName,!0))}})}}}}async selectVariant(t,e,a,r){const i=await this.selectVariantLambda(t,e,a,r);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a,r){const i=a.getModelContainer();r(!0);const o=e.material;if(!o)throw r(!1),new pt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{i&&t.data.targetMaterials.forEach(s=>{t.option&&i.applyMaterialVariant(s,t.option.id||"",o)}),a.setMandatoryFulfilled(t.stepName,!0)}finally{r(!1)}})}}}}const Ua=new Ds;class Fs{async init(t,e,a){const r=t.option;if(!r)throw new ae(t);if(a)await this.reload(t,e,a);else{const i=W.getDefaultVariant(r);if(i)return await this.selectVariantLambda(t,i,e,()=>{})}return null}async reload(t,e,a){const r=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(r?.selectedVariants){const c=r.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(A=>A.id===c);if(d){const A=s.map(u=>({id:u.id,region:u.stepRegion}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{const u=e.getModelContainer();if(u&&t.option){const h=d.asset?.fileLink;if(!h)throw new pt(d);await u.applyModelVariant(t.stepName||"",{model:h,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}})}}}}async selectVariant(t,e,a,r){const i=await this.selectVariantLambda(t,e,a,r);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a,r){r(!0);const i=e.asset?.fileLink;if(!i)throw new pt(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:i,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1),a.setMandatoryFulfilled(t.stepName,!0)}finally{r(!1)}})}}}}const La=new Fs;class ks{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 r=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}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{e.updateStorage(t.stepName,{text:r?.storage?.text}),e.setMandatoryFulfilled(t.stepName,r?.storage?.text!=="")})}async changeText(t,e,a,r){const i=await this.changeTextCommand(t,e,a,r);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async changeTextCommand(t,e,a,r){const i=a.getRegionElements(t.stepName),o=a.getStepSpecificServices(t.stepName)?.module;if(!o)return console.error("Missing module."),null;const s=a.getProfanities(),l=this.validateInput(t,e,s,r);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,A,u)=>{const h=u||M(),m=a.getLayouts().find(f=>f.panelId===A.panelId);if(!m)return console.error(`Can not find layout for region: ${A.panelId}`),null;const p=[];return u&&p.push(new yt(h)),p.push(new z({stepRegion:A,stepName:t.stepName,colors:{},id:h,svg:d,type:F.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable},m)),{id:h,region:A,command:new Q(p)}};if(i.length>0){const A=i.map(u=>{if(!u.region)return null;const h=o.svgPrint(e,u.region);return c(h,u.region,u.id)}).filter(u=>!!u).filter(u=>!!u).map(u=>u&&u.command);return{command:new Q(A),followup:async()=>{}}}else{const d=t.data.regions.map(u=>c(o.svgPrint(e,u),u)),A=d.filter(u=>!!u).map(u=>u&&u.command);return{command:new Q(A),followup:async()=>{const u=d.filter(h=>h).map(h=>h&&{id:h.id,region:h.region});await a.setSelectionsAndElements(t.stepName,[],u)}}}}validateInput(t,e,a,r){if(t.data&&t.data.maxLength){const o=t.data.maxLength;if(e.length>o)return r("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return r("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const i=la.split(e.toLowerCase());for(const o of i)for(const s in a){const l=a[s].toLowerCase().replace(/\s/g,"");if(o===l)return r("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return r(""),{input:e,helperData:{}}}}const Va=new ks;class Ms{async init(t,e,a){const r=t.option;if(!r)return null;if(a)await this.reload(t,e,a);else if(r.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,r.defaultVariant,e,()=>{});return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,a){const r=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(r?.selectedVariants){const c=r.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(A=>A.id===c);if(d){const A=s.map(u=>({id:u.id,region:u.stepRegion}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{e.setMandatoryFulfilled(t.stepName,!0)})}}}}async selectVariant(t,e,a,r){const i=await this.selectVariantCommand(t,e,a,r);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,a,r){const i=e.asset;if(!i)throw new pt(e);const o=i?.fileLink;if(!o)return console.error("No URL for picture!"),null;r(!0),t.mandatory&&a.setMandatoryFulfilled(t.stepName,!1);const l=a.getRegionElements(t.stepName).map(A=>new yt(A.id)),c=A=>{const h=a.getLayouts().find(m=>m.panelId===A.panelId);if(!h)throw new j(A);const g=M();return{regionElement:{id:g,region:A},command:new z({stepName:t.stepName,stepRegion:A,id:g,src:o,type:F.Image,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,preserveAspectRatio:"none"},h)}},d=t.data.regions.map(c);return{command:new Q([...l,...d.map(A=>A.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(A=>A.regionElement),async()=>{a.setMandatoryFulfilled(t.stepName,!0),r(!1)})}}}}const za=new Ms;class Ts{async init(t,e,a){const r=t.option;if(!r)return null;if(a)await this.reload(t,e,a);else{const i=r.variants;if(W.getDefaultVariant(r)){const s=i?.find(l=>l.id===r.defaultVariant?.id);return this.selectVariantLambda(t,s?.id||"",e)}}return null}async reload(t,e,a){const r=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),i=t.option;if(r?.selectedVariants){const o=r.selectedVariants[0].id;if(i&&o){const s=i.variants?.find(l=>l.id===o);s&&await e.setSelectionsAndElements(t.stepName,[s],[])}}}async selectVariant(t,e,a){await a.getInitializationPromise();const r=await this.selectVariantLambda(t,e,a);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a){const r=t.option;if(!r)return null;const i=r.variants;if(!i)return null;const o=i.length>1?i.find(s=>s.id===e):i[0];if(!o)throw new Error(`Failed to find selected variant ${e} in option ${r.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[o],[],async()=>{a.setMandatoryFulfilled(t.stepName,!0)})}}}}const qa=new Ts;class Ns{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){const e=t.option;return e?e.variants?.map(a=>({fill:a.color,stroke:a.color,variant:a}))||[]:[]}setCustomColor(t,e,a){const r=a.getLayouts(),o=(a.getRegionElements(e.stepName)||[]).map(s=>{const l=s.region;if(!r.find(d=>d.panelId===l?.panelId))throw new j(l);return new wa(s.id,this.shapeFillId,t)}).filter(s=>!!s);a.getCommandDispatcher()(new Q(o)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const r=t.option;if(!r)throw new ae(t);if(a)await this.reload(t,e,a);else{const i=W.getDefaultVariant(r);return i?this.selectVariantCommand(t,{fill:i.color,stroke:i.color,variant:i},[],e):null}return null}async selectVariant(t,e,a,r){const i=await this.selectVariantCommand(t,e,a,r);i&&(i.command&&r.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async reload(t,e,a){const r=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(r?.selectedVariants){const c=r.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(A=>A.id===c);if(d){const A=s.map(u=>({id:u.id,region:u.stepRegion}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{e.updateStorage(t.stepName,{colour:r?.storage?.colour||""}),e.setMandatoryFulfilled(t.stepName,!0)})}}}}async selectVariantCommand(t,e,a,r){const i=r.getLayouts(),o=r.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 A=d.region;if(!i.find(g=>g.panelId===A?.panelId))throw new j(A);const h=s();return new wa(d.id,this.shapeFillId,h)},c=a.map(l).filter(d=>!!d);return{command:new Q(c),followup:async()=>{await r.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),r.updateStorage(t.stepName,{colour:s()})}}}else{const l=u=>{const h=i.find(S=>S.panelId===u.panelId);if(!h)throw new j(u);const g=s(),m=`
1481
+ `,r={};r["spiff-fill-shape"]={browserValue:e.color};const i=e.region||await Gt(t,x.Illustration),o=M();return{stepRegion:e.region,colors:r,id:o,svg:a,type:x.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layer:i.layer||0,layerIndex:i.layerIndex||qt(t,i.layer||0),immutable:i.immutable}}static async getIllustration(t,e){const a=e.region||await Gt(t,x.Illustration,e.src),r=await ot(await dr(e.src)),i=await ie(r.svg),o=M();return{cachedObjectURL:i,stepRegion:e.region,colors:r.colors,id:o,src:e.src,svg:r.svg,type:x.Illustration,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||qt(t,a.layer||0),immutable:a.immutable}}}class L extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,L.prototype)}}const O=(n,t)=>_(n,t).elements.find(r=>r.id===n),_=(n,t)=>{const e=Object.values(t).find(a=>a.elements.some(r=>r.id===n));if(!e)throw new L;return e},tt=(n,t)=>{const e=[...t.elements.filter(r=>r.id!==n.id),n],a=Na(e);return{layout:t.layout,elements:a,modificationID:M()}},Ca=async n=>{const t=[...Object.keys(n.layouts)],e=[...new Set(t)];for(let a=0;a<e.length;a++){const r=e[a],i=n.layouts[r];await Promise.all(i.elements.map(async o=>{if(o.type==="illustration"){const s=o;if(s.src&&!s.svg){const l=await at(s.src),c=await ot(l);s.svg=xa(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 at(s.pattern?.src),c=await ot(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 n.layouts){const r=n.layouts[a].elements.filter(o=>o.type===x.Illustration);for(let o=0;o<r.length;++o){const s=r[o];if(s.src&&s.svg)try{s.cachedObjectURL=await ie(s.svg)}catch(l){console.log(l)}}const i=n.layouts[a].elements.filter(o=>o.type===x.Textbox);for(let o=0;o<i.length;++o){const s=i[o];s.fontData?.assetUrl&&await Dt(s.fontData.assetUrl)}}};class N{undo(){if(!this.oldState)throw new Error("Cannot undo.");return this.oldState}overrideOldState(t){this.oldState=t}}class An extends N{constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class fs extends N{constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;const a={...e,x:this.x,y:this.y},r=_(e.id,Object.values(t.layouts)),i=tt(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class Cs extends N{constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;const a={...e,rotation:this.angle},r=_(e.id,Object.values(t.layouts)),i=tt(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class ws extends N{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=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;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===Pt.Autosize?o.text:o.input)??"";a=Ae(o,s,e)}const r=_(e.id,Object.values(t.layouts)),i=tt(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class Q extends N{constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class $a extends N{constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:M()}}}}}class z extends N{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:M()}}}}const r=e[e.length-1],i=r.productOverlay?r:null;i&&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 i&&o.push(i),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:o,modificationID:M()}}}}assignIndex(t,e){if(e.length===0)return 0;const a=e.filter(r=>(r.layer||0)===(t.layer||0)).sort((r,i)=>(r.layerIndex||0)-(i.layerIndex||0))[e.length-1]?.layerIndex;return a!==void 0?a+1:0}}class yt extends N{constructor(t){super(),this.id=t}apply(t){this.oldState=t;let e=!1;const a=Object.values(t.layouts).map(i=>(i.elements.filter(s=>s.id!==this.id).length!==i.elements.length&&(e=!0),{...i,elements:i.elements.filter(s=>s.id!==this.id),modificationID:M()}));e||console.log(`Failed to delete element ${this.id}`);const r={};return a.forEach(i=>{r[i.layout.id]=i}),{...t,layouts:r}}}class Ar extends N{constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},r=_(e.id,Object.values(t.layouts)),i=tt(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class ea extends N{constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;const a={...e,textFillImage:this.imageFill},r=_(e.id,Object.values(t.layouts)),i=tt(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class ur extends N{constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;const a={...e,fontSize:this.size},r=_(e.id,Object.values(t.layouts)),i=(!e.algorithm||e.algorithm===Pt.Autosize?e.text:e.input)??"",o=tt(Ae(a,i),r);return{...t,layouts:{...t.layouts,[r.layout.id]:o}}}}class wa extends N{constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;const a={...e,fontData:this.fontData},r=_(e.id,Object.values(t.layouts)),i=(!e.algorithm||e.algorithm===Pt.Autosize?e.text:e.input)??"",o=tt(Ae(a,i),r);return{...t,layouts:{...t.layouts,[r.layout.id]:o}}}}class hr extends N{constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;const a={...e,align:this.align},r=_(e.id,Object.values(t.layouts)),i=tt(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class ys extends N{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),r=e.elements[a].pattern,i=[...e.elements];i.splice(a,1,{...e.elements[a],pattern:{...r,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:i,modificationID:M()};return{...t,layouts:{...t.layouts,[e.layout.id]:o}}}}class Ss extends N{constructor(t,e,a,r,i){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=r,this.thresholdSaturation=i}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},r=_(e.id,Object.values(t.layouts)),i=tt(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class vs extends N{constructor(t,e){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;const a={...e,src:this.src},r=_(e.id,Object.values(t.layouts)),i=tt(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class gr extends N{constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;const a=_(e.id,Object.values(t.layouts)),r=tt(Ae(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:r}}}}class aa extends N{constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},r=_(e.id,Object.values(t.layouts)),i=tt(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class ya extends N{constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;const a=e.colors||{},r=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:r?.spotColor,pmsValue:r?.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:r?.spotColor,pmsValue:this.fill.pmsValue};const i={...e,colors:a},o=_(e.id,Object.values(t.layouts)),s=tt(i,o);return{...t,layouts:{...t.layouts,[o.layout.id]:s}}}}class Es extends N{constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},r=_(e.id,Object.values(t.layouts)),i=tt(a,r);return{...t,layouts:{...t.layouts,[r.layout.id]:i}}}}class bs extends N{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!O(this.id,Object.values(t.layouts)).id)throw new L;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 r=a.elements.findIndex(o=>o.id===this.id);a.elements.push(a.elements.splice(r,1)[0]);const i=[...a.elements];return i.forEach((o,s)=>o.layerIndex=s),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:i,modificationID:M()}}}}}class Bs extends N{constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=O(this.id,Object.values(t.layouts));if(!e.id)throw new L;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 r=a.elements.findIndex(s=>s.id===this.id);a.elements.splice(r,1),a.elements.unshift(e);const i=[...a.elements],o=i.splice(r,1)[0];return i.splice(r,0,o),i.forEach((s,l)=>s.layerIndex=l),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:i,modificationID:M()}}}}}class Is extends N{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!O(this.id,Object.values(t.layouts)).id)throw new L;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 r=a.elements.findIndex(l=>l.id===this.id),i=r+1,o=[...a.elements],s=o.splice(r,1)[0];return o.splice(i,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:M()}}}}}class Ps extends N{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!O(this.id,Object.values(t.layouts)).id)throw new L;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 r=a.elements.findIndex(l=>l.id===this.id),i=r-1,o=[...a.elements],s=o.splice(r,1)[0];return o.splice(i,0,s),o.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:o,modificationID:M()}}}}}class un{constructor(t,e,a){this.processRegion=async r=>{const i=this.layouts.find(l=>l.panelId===r.panelId);if(!i)throw new H(r);let o="";if(this.configuration.type===E.ProductOverlay){let l="";if(this.product?.overlayImageUrl&&(l=this.product.overlayImageUrl),o=l,!l)throw new ne(this.configuration,"Couldn't find an asset for product overlay step")}const s=this.evaluateAssetType();if(s===x.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:M(),src:l,type:s,y:r.top,x:r.left,width:r.width,height:r.height,layer:r.layer,layerIndex:r.layerIndex,immutable:r.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,rotation:r.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:c.id,region:r},command:new z(c,i)}}else{const l=this.configuration.type===E.SilentIllustration?this.configuration.data.asset?.fileLink:o,d=await ot(await(async()=>new Promise((u,h)=>{if(!l){h("Undefined vector silent step source");return}at(l,!0).then(g=>{u(g)}).catch(g=>console.error(g))}))()),A={stepName:this.configuration.stepName,id:M(),cachedObjectURL:await ie(d.svg),src:l,svg:d.svg,colors:d.colors,type:s,y:r.top,x:r.left,width:r.width,height:r.height,layer:r.layer,layerIndex:r.layerIndex,rotation:r.rotation,immutable:r.immutable,productOverlay:this.configuration.type===E.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:A.id,region:r},command:new z(A,i)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new ne(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 H(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")?x.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),x.Illustration)}}const mr=async n=>{const t=`${At.getServicesApiUrl()}/shortener`;try{return(await(await it(t,{method:"POST",body:JSON.stringify({longUrl:n}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new Oe("Failed to shorten URL, see console.")}};class pr{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,r=3e3,i=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=r,this.maxAttempts=i,this.poll()}}class Ds{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const r=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}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{const c=r?.storage?.videoShortUrl,d=r?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,r){const i=async()=>{const h=(await Fe([e]))[0],g=h?.versions?.find(p=>p.name==="mpeg4")?.link;return{asset:h,link:g}},o=await new Promise((h,g)=>{new pr(async()=>!!(await i()).link,async()=>{const p=await i();if(!p.link||!p.link)throw new Qt(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 yt(h.id)));const s=r.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(s+r.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 Oe("Cannot create QR code, URL too long.");const d=await mr(c);if(!r.data||!r.data.regions)throw new ne(r,"Missing regions.");const A=await this.regionElements(r),u=await this.command(d,A,a,r.stepName);return u&&(u.command&&a.getCommandDispatcher()(u.command),u.followup&&await u.followup()),await a.setSelectionsAndElements(r.stepName,[],A,async()=>{a.updateStorage(r.stepName,{videoShortUrl:d,videoUrl:o.href})}),d}async regionElements(t){const e=a=>({id:M(),region:a});return t.data.regions.map(e)}async command(t,e,a,r){const i=a.getLayouts(),s=`data:image/svg+xml;base64,${btoa(await In.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,A=i.find(u=>u.panelId===d?.panelId);if(!A&&d)throw new H(d);if(A&&!d)throw new Error("Region not found");if(!A||!d)throw new Error("Neither a region or layout found!");return new z({stepRegion:d,stepName:r,id:c.id,src:s,type:x.Image,y:d.top,x:d.left,width:d.width,height:d.height,rotation:0},A)});return{command:new Q(l),followup:async()=>{}}}}const Ua=new Ds;class Me{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return pa(e);const a=t.asset;if(!a)throw new pt(t);const r=a.fileLink;if(r)return at(r,!0);throw new Qt(a)}}async init(t,e,a){const r=a?.serializableWorkflow.steps.find(s=>s.stepName===t.stepName);if(r?.storage&&Object.keys(r.storage).length!==0||r?.selectedVariants&&r.selectedVariants.length!==0)return await this.reload(t,e,a),null;t.mandatory&&e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]);let i;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&&(i=(await R.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option&&t.option.variants&&t.option.variants.length>0){const s=t.option,l=j.getDefaultVariant(s);return l?this.selectVariantCommand(t,l,[],e,void 0,i||t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,i||t.data.placeholderImageUrl)}async reload(t,e,a){const r=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}));if(!t.option||(t.option.variants||[]).length===0){const c=t.data.regions.map(d=>pa(d));e.updateStorage(t.stepName,{currentFrameSources:c})}if(r){const c=async()=>{const d=r.storage?.colors,A=r.storage?.framePatternSrc,u=r.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:u,framePatternSrc:A}),A){const h=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!h)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,h,!0,d),e.updateMetadata(t.stepName,{image:A}),e.updateStorage(t.stepName,{framePatternSrc:A}),this.validateColorCount(t,e)}if(u?.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(u)}e.setMandatoryFulfilled(t.stepName,!0)};if(r.selectedVariants&&r.selectedVariants.length>0){const d=r.selectedVariants[0].id;if(t.option&&d){const A=t.option.variants?.find(u=>u.id===d);A&&await e.setSelectionsAndElements(t.stepName,[A],l,async()=>{const u=await Promise.all(t.data.regions.map(h=>this.frameSourceSvg(A,h)));e.updateStorage(t.stepName,{currentFrameSources:u}),await c()})}}else await e.setSelectionsAndElements(t.stepName,[],l,c)}}async availableColors(t,e){return t.data.colorOption?.variants?.map(r=>({fill:r.color,stroke:r.color,variant:r,pmsValue:r.name}))??[]}selectImage(t,e,a,r=!0){const i=Me.patternSource(e),o=a.getStepStorage(t.stepName)?.framePatternSrc;if(o&&o===i)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 pr(async()=>{const d=(await R.getFromServer(e.key||"")).versions?.find(u=>u.name==="svg");return d?(await it(d.link)).status===200:!1},()=>{R.getLocalOrFromServer(e.key||"").then(c=>{this.loadPatternFromAsset(c,t,a,r).then(l)})},()=>{throw new Oe("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,r)}async selectVariant(t,e,a,r,i){const o=await this.selectVariantCommand(t,e,a,r,i);o&&(o.command&&r.getCommandDispatcher()(o.command),o.followup&&await o.followup())}getCreateElementCommand(t,e,a,r){return new z({id:t,type:x.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,stepName:r.stepName,disablePlaceholder:r.disablePlaceholder,pattern:r.pattern,immutable:e.immutable},a)}async loadPatternFromString(t,e,a=!0,r=void 0,i){if(t.endsWith("svg")){const o=await Ra(t),s=o.width,l=o.height,c=await at(t);if(i){const u=c.match(/<(image|linearGradient|radialGradient)(\s|>|\/>)/gim);if(u&&u.length>0)throw new Error("Vector files may not include images or gradients when a color limit is specified.")}const d=await ot(c),A={src:t,width:s,height:l,aspect:s/l,svg:d.svg,colors:r??d.colors};dt.set(t,A),e.setPatternData(A,a)}else{const o=await $e(t,!0),s=await ce(o),l={src:t,width:s.width,height:s.height,aspect:s.width/s.height,svg:void 0,colors:void 0};dt.set(t,l),e.setPatternData(l,a)}}changeColors(t,e,a){const r=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!r||!r.getImageData()?.svg){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const i=this.calculateColorMetadata(r,t,a);e.updateMetadata(t.stepName,{colors:i.metadataColors}),e.updateStorage(t.stepName,{colors:i.storageColors}),r.setPatternData({...r.getImageData(),colors:i.newColors},!1),this.validateColorCount(t,e)}getUniqueColorCount(t,e){const a=e.getWorkflowExperience().getStepById(t.stepName)?.frameService;if(!a)return 0;const r=a.getImageData()?.colors??{},i=[];for(const o in r){const s=r[o];if(s.pmsValue){const l=s.pmsValue.trim().toLocaleLowerCase();i.includes(l)||i.push(l)}else if(s.browserValue){const l=qn(s.browserValue);i.includes(l)||i.push(l)}}return i.length}calculateColorMetadata(t,e,a){if(!t.getImageData()?.svg)return{newColors:void 0,metadataColors:void 0,storageColors:void 0};const r={...t.getImageData().colors??{}},i={};Object.entries(r).forEach(([l,c])=>{const d={browserValue:c.browserValue};i[l]=d});for(const[l,c]of a.entries())r[l]={browserValue:c.browserValue,pmsValue:c.pmsValue},i[l]=c;let o=Array.from(Object.values(r)).map(l=>l.browserValue);const s=e.data.colorOption;return s&&s.variants?.forEach(l=>{o=o.map(c=>c.toLowerCase()===l.color?.toLowerCase()?l.name:c)}),{newColors:r,metadataColors:o,storageColors:i}}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,r,i,o){const s=r.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)));i&&i(!0);const c=t.data.initialZoomLevel,d=await Promise.all(t.data.regions.map(async(h,g)=>{const p=await he(l[g]),m=s.getImageData(),f=a.map(P=>new yt(P.id)),v=m?Qa(m,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,b=m?{id:M(),src:m.src,x:v?.x||0,y:v?.y||0,width:m.width,height:m.height,scaleX:v?.zoom||1,scaleY:v?.zoom||1,rotation:0}:void 0,D=M(),S=r.getLayouts().find(P=>P.panelId===h.panelId);if(!S)throw new H(h);return{command:this.getCreateElementCommand(D,h,S,{frameData:p,pattern:b,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:D,region:h},removeExistingCommands:f}})),A=d.map(h=>h.command),u=d.map(h=>h.removeExistingCommands).flat();return{command:new Q([...A,...u]),followup:async()=>{i&&i(!1),await r.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(h=>h.regionEl)],async()=>{if(r.updateStorage(t.stepName,{currentFrameSources:l}),o){const h=r.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(r=>r.name==="svg");if(e?.link)return e.link;const a=t.fileLink;if(a)return a;throw new Qt(t)}async loadPatternFromAsset(t,e,a,r){const i=Me.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(i,s,r,void 0,e.data.colorPickerEnabled&&!!e.data.maxColors&&e.data.maxColors>0)}catch(c){throw a.markUpdateCompleted(o),c}const l=this.calculateColorMetadata(s,e,new Map(Object.entries(s.getImageData()?.colors??{})));a.updateMetadata(e.stepName,{image:i,colors:l.metadataColors}),a.updateStorage(e.stepName,{framePatternSrc:i,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 ht=new Me;class Fs{async getIllustrationBody(t){return new Promise(e=>{at(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,r){return new z({stepRegion:e,stepName:r.stepName,colors:r.svg.colors,id:t,src:r.src,svg:r.svg.svg,cachedObjectURL:r.objectURL,type:x.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},a)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return O(a[0].id,e.getAllLayoutData()).colors}catch{return[]}}async init(t,e,a){const r=t.option;if(!r)return null;if(a)return this.reload(t,e,a);{const i=j.getDefaultVariant(r);if(i)return await this.selectVariantCommand(t,i,[],()=>{},e)}return null}async reload(t,e,a){const r=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(r?.selectedVariants){const c=r.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(A=>A.id===c);if(d){const A=s.map(u=>({id:u.id,region:u.stepRegion}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{e.updateMetadata(t.stepName,{colors:r.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){const a=t.data.colorOption;return a?a?a.variants?.map(r=>({fill:r.color,stroke:r.color,variant:r,pmsValue:r.name})):[]:[]}async changeColorsCommand(t,e,a,r,i){const o={};for(const[d,A]of i.entries())typeof A=="string"?o[d]={browserValue:A,spotColor:void 0,pmsValue:void 0}:o[d]={browserValue:A.browserValue,spotColor:A.spotColor,pmsValue:A.pmsValue};const s=xa(t,e,a,o),l=await ie(s),c=[];for(const d of r){for(const[A,u]of i.entries())c.push(new ya(d,A,u));c.push(new Es(d,s,l))}return new Q(c)}async changeColors(t,e,a,r,i){if(e.length===0)return;const o=O(e[0].id,r().map(h=>h.layoutState)),s={...o.colors},l={};Object.entries(s).forEach(([h,g])=>{const p={browserValue:g.browserValue,pmsValue:g.pmsValue},m=g.spotColor;m&&(p.spotColor={profileName:m.profileName,namedColor:m.namedColor}),l[h]=p});for(const[h,g]of i.entries()){const p=typeof g=="string"?g:g.browserValue,m=typeof g=="string"?void 0:g.pmsValue;s[h]={browserValue:p,spotColor:s[h]?.spotColor,pmsValue:m},l[h]={browserValue:p}}let c=Array.from(Object.values(s)).map(h=>h.browserValue);const d=t.data.colorOption;d&&d.variants?.forEach(h=>{c=c.map(g=>g.toLowerCase()===h.color?.toLowerCase()?h.name:g)}),a.updateMetadata(t.stepName,{colors:c});const A=new Map;if(Object.entries(s).forEach(([h,g])=>{A.set(h,g)}),!o.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const u=await this.changeColorsCommand(o.svg,o.width,o.height,e.map(h=>h.id),A);a.updateStorage(t.stepName,{colors:l}),a.getCommandDispatcher()(u)}async selectVariant(t,e,a,r,i){const o=await this.selectVariantCommand(t,e,a,r,i);o&&(o.command&&i.getCommandDispatcher()(o.command),o.followup&&await o.followup())}async selectVariantCommand(t,e,a,r,i){if(!t.data||!t.data.regions)throw new ne(t,"Missing regions.");r(!0);const o=a.map(f=>new yt(f.id));t.mandatory&&i.setMandatoryFulfilled(t.stepName,!1);const s=e.asset;if(!s)throw new pt(e);const l=s.fileLink;if(!l)throw new Qt(s);const c=await ot(await this.getIllustrationBody(l)),d=await ie(c.svg),A=f=>{const v=i.getLayouts().find(D=>D.panelId===f.panelId);if(!v)throw new H(f);const b=M();return{regionElement:{id:b,region:f},command:this.getCreateElementCommand(b,f,v,{stepName:t.stepName,src:l,objectURL:d,svg:c})}},u=t.data.regions.map(A),g=[...u.map(f=>f.command),...o];let p=Array.from(Object.values(c.colors)).map(f=>f.browserValue);const m=t.data.colorOption;return m&&m.variants?.forEach(f=>{p=p.map(v=>v.toLowerCase()===f.color?.toLowerCase()?f.name:v)}),i.updateMetadata(t.stepName,{colors:p}),{command:new Q(g),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],u.map(v=>v.regionElement),async()=>{i.setMandatoryFulfilled(t.stepName,!0),r(!1)});const f=s.assetConfiguration?.defaultColorVariants||[];if(f.length!==0){const v={};(s.assetConfiguration?.channelNumbers||[]).forEach(D=>{const w=f.find(S=>S.channelNumber===D.number);w&&(v[`${D.id.replace(/\W/g,"")}`]={browserValue:w?.variant?.color||""})}),await this.changeColors(t,u.map(D=>D.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map(Object.entries(v)))}if(t.data.colorPickerEnabled){const v=await this.availableColors(t,i)||[],b=Object.keys(c.colors),D=v.length===1&&b.length===1;if(D){const w=v[0],S=b[0];await this.changeColors(t,u.map(P=>P.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map([[S,w.variant.color]]))}!D&&f.length===0&&await this.changeColors(t,u.map(w=>w.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map)}}}}}const Jt=new Fs;class xs{async init(t,e,a){const r=t.option;if(!r)throw new ae(t);if(a)await this.reload(t,e,a);else{const i=j.getDefaultVariant(r);if(i)return await this.selectVariantLambda(t,i,e,()=>{})}return null}async reload(t,e,a){const r=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 ae(t);if(r?.selectedVariants){const c=r.selectedVariants[0].id;if(c){const d=l.variants?.find(A=>A.id===c);if(d){const A=d.material,u=s.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{const h=e.getModelContainer();if(h){const g=t.data.targetMaterials.map(p=>h.applyMaterialVariant(p,l.id||"",A||{}));Promise.all(g).then(()=>e.setMandatoryFulfilled(t.stepName,!0))}})}}}}async selectVariant(t,e,a,r){const i=await this.selectVariantLambda(t,e,a,r);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a,r){const i=a.getModelContainer();r(!0);const o=e.material;if(!o)throw r(!1),new pt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{i&&t.data.targetMaterials.forEach(s=>{t.option&&i.applyMaterialVariant(s,t.option.id||"",o)}),a.setMandatoryFulfilled(t.stepName,!0)}finally{r(!1)}})}}}}const La=new xs;class ks{async init(t,e,a){const r=t.option;if(!r)throw new ae(t);if(a)await this.reload(t,e,a);else{const i=j.getDefaultVariant(r);if(i)return await this.selectVariantLambda(t,i,e,()=>{})}return null}async reload(t,e,a){const r=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(r?.selectedVariants){const c=r.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(A=>A.id===c);if(d){const A=s.map(u=>({id:u.id,region:u.stepRegion}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{const u=e.getModelContainer();if(u&&t.option){const h=d.asset?.fileLink;if(!h)throw new pt(d);await u.applyModelVariant(t.stepName||"",{model:h,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}})}}}}async selectVariant(t,e,a,r){const i=await this.selectVariantLambda(t,e,a,r);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a,r){r(!0);const i=e.asset?.fileLink;if(!i)throw new pt(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:i,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1),a.setMandatoryFulfilled(t.stepName,!0)}finally{r(!1)}})}}}}const Va=new ks;class Ms{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 r=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}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{e.updateStorage(t.stepName,{text:r?.storage?.text}),e.setMandatoryFulfilled(t.stepName,r?.storage?.text!=="")})}async changeText(t,e,a,r){const i=await this.changeTextCommand(t,e,a,r);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async changeTextCommand(t,e,a,r){const i=a.getRegionElements(t.stepName),o=a.getStepSpecificServices(t.stepName)?.module;if(!o)return console.error("Missing module."),null;const s=a.getProfanities(),l=this.validateInput(t,e,s,r);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,A,u)=>{const h=u||M(),p=a.getLayouts().find(f=>f.panelId===A.panelId);if(!p)return console.error(`Can not find layout for region: ${A.panelId}`),null;const m=[];return u&&m.push(new yt(h)),m.push(new z({stepRegion:A,stepName:t.stepName,colors:{},id:h,svg:d,type:x.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable},p)),{id:h,region:A,command:new Q(m)}};if(i.length>0){const A=i.map(u=>{if(!u.region)return null;const h=o.svgPrint(e,u.region);return c(h,u.region,u.id)}).filter(u=>!!u).filter(u=>!!u).map(u=>u&&u.command);return{command:new Q(A),followup:async()=>{}}}else{const d=t.data.regions.map(u=>c(o.svgPrint(e,u),u)),A=d.filter(u=>!!u).map(u=>u&&u.command);return{command:new Q(A),followup:async()=>{const u=d.filter(h=>h).map(h=>h&&{id:h.id,region:h.region});await a.setSelectionsAndElements(t.stepName,[],u)}}}}validateInput(t,e,a,r){if(t.data&&t.data.maxLength){const o=t.data.maxLength;if(e.length>o)return r("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return r("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const i=ca.split(e.toLowerCase());for(const o of i)for(const s in a){const l=a[s].toLowerCase().replace(/\s/g,"");if(o===l)return r("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return r(""),{input:e,helperData:{}}}}const za=new Ms;class Ts{async init(t,e,a){const r=t.option;if(!r)return null;if(a)await this.reload(t,e,a);else if(r.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,r.defaultVariant,e,()=>{});return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,a){const r=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(r?.selectedVariants){const c=r.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(A=>A.id===c);if(d){const A=s.map(u=>({id:u.id,region:u.stepRegion}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{e.setMandatoryFulfilled(t.stepName,!0)})}}}}async selectVariant(t,e,a,r){const i=await this.selectVariantCommand(t,e,a,r);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,a,r){const i=e.asset;if(!i)throw new pt(e);const o=i?.fileLink;if(!o)return console.error("No URL for picture!"),null;r(!0),t.mandatory&&a.setMandatoryFulfilled(t.stepName,!1);const l=a.getRegionElements(t.stepName).map(A=>new yt(A.id)),c=A=>{const h=a.getLayouts().find(p=>p.panelId===A.panelId);if(!h)throw new H(A);const g=M();return{regionElement:{id:g,region:A},command:new z({stepName:t.stepName,stepRegion:A,id:g,src:o,type:x.Image,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,preserveAspectRatio:"none"},h)}},d=t.data.regions.map(c);return{command:new Q([...l,...d.map(A=>A.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(A=>A.regionElement),async()=>{a.setMandatoryFulfilled(t.stepName,!0),r(!1)})}}}}const qa=new Ts;class Ns{async init(t,e,a){const r=t.option;if(!r)return null;if(a)await this.reload(t,e,a);else{const i=r.variants;if(j.getDefaultVariant(r)){const s=i?.find(l=>l.id===r.defaultVariant?.id);return this.selectVariantLambda(t,s?.id||"",e)}}return null}async reload(t,e,a){const r=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),i=t.option;if(r?.selectedVariants){const o=r.selectedVariants[0].id;if(i&&o){const s=i.variants?.find(l=>l.id===o);s&&await e.setSelectionsAndElements(t.stepName,[s],[])}}}async selectVariant(t,e,a){await a.getInitializationPromise();const r=await this.selectVariantLambda(t,e,a);r&&(r.command&&a.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantLambda(t,e,a){const r=t.option;if(!r)return null;const i=r.variants;if(!i)return null;const o=i.length>1?i.find(s=>s.id===e):i[0];if(!o)throw new Error(`Failed to find selected variant ${e} in option ${r.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[o],[],async()=>{a.setMandatoryFulfilled(t.stepName,!0)})}}}}const Ga=new Ns;class Qs{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){const e=t.option;return e?e.variants?.map(a=>({fill:a.color,stroke:a.color,variant:a}))||[]:[]}setCustomColor(t,e,a){const r=a.getLayouts(),o=(a.getRegionElements(e.stepName)||[]).map(s=>{const l=s.region;if(!r.find(d=>d.panelId===l?.panelId))throw new H(l);return new ya(s.id,this.shapeFillId,t)}).filter(s=>!!s);a.getCommandDispatcher()(new Q(o)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const r=t.option;if(!r)throw new ae(t);if(a)await this.reload(t,e,a);else{const i=j.getDefaultVariant(r);return i?this.selectVariantCommand(t,{fill:i.color,stroke:i.color,variant:i},[],e):null}return null}async selectVariant(t,e,a,r){const i=await this.selectVariantCommand(t,e,a,r);i&&(i.command&&r.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async reload(t,e,a){const r=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(r?.selectedVariants){const c=r.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(A=>A.id===c);if(d){const A=s.map(u=>({id:u.id,region:u.stepRegion}));await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{e.updateStorage(t.stepName,{colour:r?.storage?.colour||""}),e.setMandatoryFulfilled(t.stepName,!0)})}}}}async selectVariantCommand(t,e,a,r){const i=r.getLayouts(),o=r.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 A=d.region;if(!i.find(g=>g.panelId===A?.panelId))throw new H(A);const h=s();return new ya(d.id,this.shapeFillId,h)},c=a.map(l).filter(d=>!!d);return{command:new Q(c),followup:async()=>{await r.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),r.updateStorage(t.stepName,{colour:s()})}}}else{const l=u=>{const h=i.find(v=>v.panelId===u.panelId);if(!h)throw new H(u);const g=s(),p=`
1482
1482
  <svg
1483
1483
  xmlns="http://www.w3.org/2000/svg"
1484
1484
  xmlnsXlink="http://www.w3.org/1999/xlink"
@@ -1498,14 +1498,14 @@
1498
1498
  fill="${g}"
1499
1499
  />
1500
1500
  </svg>
1501
- `,p={};p[this.shapeFillId]={browserValue:g};const f=M();return{id:f,region:u,command:new z({stepRegion:u,stepName:t.stepName,colors:p,id:f,svg:m,type:F.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,excludeFromExport:t.data.excludeFromPrint},h)}},c=t.data.regions.map(l),d=c.filter(u=>!!u).map(u=>u?.command),A=c.filter(u=>!!u).map(u=>({id:u.id,region:u.region}));return{command:new Q(d),followup:async()=>{await r.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],A,async()=>{r.updateStorage(t.stepName,{colour:s()})})}}}}}const kt=new Ns;class Qs{constructor(){this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(t){t({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(t)}removeToastCallback(t){this.toastCallbacks=this.toastCallbacks.filter(e=>e!==t)}setLatestToast(t,e){this.latestToast=t,this.toastType=e,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach(t=>t({toastMessage:this.latestToast,toastType:this.toastType}))}}const pr=new Qs,aa=(n,t,e,a,r)=>{if(t.some(d=>d==null))throw new Error(`Failed to autosize lines: ${t.join(", ")}`);let i=t.map(d=>d.split(`
1502
- `)).flat(),o=i.length,s=i.map(d=>mt(d,a,r));const l=r.getApproximateHeight()*a;let c=!0;for(;c;){if(l+(o-1)*e>n.height)return[null,null];const A=Math.max(...s);if(A<=n.width)return[i,A];const u=s.reduce((p,f,S,b)=>f>b[p]?S:p,0),h=i[u];let g=!1,m=h.length;for(;!g&&m>-1;){m=h.lastIndexOf(" ",m-1);const p=[h.slice(0,m),h.slice(m+1)],f=p.map(b=>mt(b,a,r));f[0]<=n.width&&(i=[...i.slice(0,u),...p,...i.slice(u+1)],s=[...s.slice(0,u),...f,...s.slice(u+1)],o+=1,g=!0)}g||(c=!1)}return[null,null]},Kt=(n,t,e,a,r)=>{let i,o;const s=wt(t.assetUrl),l=s.getFont();if(r.size){const u=n/l.unitsPerEm;return[i,o]=aa(e,a,n,u,s),[r.size,i,o]}const c=6;let d=c-_e;if(a.length>0){let u=a,h=0;for(;(!r.maxSize||d<=r.maxSize)&&u;)d+=_e,h=d/l.unitsPerEm,[u,o]=aa(e,a,d,h,s)}d>c&&(d-=_e),r.minSize&&d<r.minSize&&(d=r.minSize);const A=d/l.unitsPerEm;return[i,o]=aa(e,a,d,A,s),[d,i,o]},na=30;class Te extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Te.name}}const Rs=["‘","’","“","”",`
1503
- `];class Ne extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ne.name}}class Os{constructor(){this.cachedColors=new Map,this.cachedStrokeColors=new Map,this.filterUnsupportedCharacters=(t,e)=>{let a=t.replace(/(\r\n|\r|(\u2665|\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const r=[],i=e?wt(e.assetUrl):void 0;if(i){const o=a.split("").filter(l=>!Rs.includes(l)).join(""),s=o.split("").map(l=>i.getFont().charToGlyph(l));for(let l=0;l<s.length;l++)s[l].name===".notdef"&&r.push(String.fromCharCode(o.charCodeAt(l)))}for(let o=0;o<r.length;o++)a=a.replaceAll(r[o],"");return a},this.textAlign=t=>t.vertical?"center":t.textAlign||"center",this.getErrorsForText=(t,e,a,r)=>{let i;a.data&&a.data.maxLength&&e.length>a.data.maxLength&&(i||(i={}),i.hitCharacterLimit=!0);const o=r.getProfanities(),s=la.split(t.toLowerCase());for(const c of s)for(const d in o){const A=o[d].toLowerCase().replace(/\s/g,"");if(c===A){i||(i={}),i.blockedProfanity=!0;break}}return!a.data.allowNewlines&&(t.includes(`
1504
- `)||t.includes("\r"))&&(i||(i={}),i.illegalMultipleLines=!0),i}}async init(t,e,a){const r=t.option;if(!r)return null;if(a)await this.reload(t,e,a);else{const i=this.getDefaultImageFillVariant(t.data),o=i?.asset?.fileLink,s=o?await pa(o):void 0,l=s?{src:s.src,height:s.height,width:s.width,scale:t.data.imageFillScale||1}:void 0,c=this.getDefaultStrokeColorVariant(t.data),d=t.data.strokeEnabled&&c?.color?{browserValue:c.color,pmsValue:c.name}:void 0;let A=t.data.defaultText||"";const u=e.getWorkflowExperience().getBundle();if(u&&t.globalPropertyAspectConfigurations){const m=u.getGlobalPropertyConfiguration()?.aspects?.find(p=>p.type===U.Text&&t.globalPropertyAspectConfigurations?.map(f=>f.aspectName).includes(p.name));if(m){const f=u.getGlobalPropertyStateManager().getAspect(m.name);f&&(A=f)}}e.updateStorage(t.stepName,{text:A,inputText:t.data.defaultText||"",color:this.getDefaultColorVariant(t.data)?.color||this.getDefaultColor(t.data),fillImage:l,strokeColor:d}),e.updateMetadata(t.stepName,{text:A,color:this.getDefaultColorVariant(t.data)?.name||this.getDefaultColor(t.data),fillImage:i?.name,strokeColor:t.data.strokeEnabled?c?.color:void 0});const h=W.getDefaultVariant(r);if(h)return this.selectVariantCommand(t,h,{text:A},[],e,()=>{},()=>{},l,d)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map(i=>$(i.id,t.getAllLayoutData()))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const a=t.data.colorOption;if(a){const r=a.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i}))||[];return this.cachedColors.set(t.stepName,r),r}return[]}changeAlignment(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher();for(const o of a){const s=new ur(o.id,e);i(s)}}async changeFillColor(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher();e.variant?r.updateMetadata(t.stepName,{color:e.variant.name}):r.updateMetadata(t.stepName,{color:e.fill});const o=t.data.colorOption,s=o?this.createTextFillSpotColor(o,e.variant):void 0;o?r.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:o.colorProfile?.key}):r.updateStorage(t.stepName,{color:e.fill});for(const l of a){if(!e.fill)throw new Error("Fill not set on new color selection!");const c=new dr(l.id,e.fill,s);i(c)}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const a=e.variants?.map(r=>r.asset?.fileLink)?.filter(r=>!!r)||[];return Promise.all(a.map(async r=>{const i=await pa(r);return{src:r,width:i.width,height:i.height,scale:t.data.imageFillScale||1}}))}return Promise.resolve([])}async changeFillImage(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher(),o=t.option?.variants?.find(s=>s.asset?.fileLink===e.src);r.updateMetadata(t.stepName,{fillImage:o?.name}),r.updateStorage(t.stepName,{fillImage:e});for(const s of a){const l=new ta(s.id,e);i(l)}}availableStrokeColors(t){const e=this.cachedStrokeColors.get(t.stepName);if(e)return e;const a=t.data.strokeOption;if(a){const r=a.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i}))||[];return this.cachedStrokeColors.set(t.stepName,r),r}return[]}async changeStrokeColor(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher();e?.variant?r.updateMetadata(t.stepName,{strokeColor:e.variant.name}):r.updateMetadata(t.stepName,{strokeColor:e?.fill});const o=e?{browserValue:e.fill,pmsValue:e.pmsValue}:void 0;r.updateStorage(t.stepName,{strokeColor:o});for(const s of a){const l=new ea(s.id,o,t.data?.strokeThickness);i(l)}}getProcessedInput(t,e,a){const r=a?t:this.injectReplaceableText(t,e);return ke(r,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,a,r){const i=r.getStepStorage(a.stepName),o=Mt(t,r),s=this.getProcessedInput(o,a.data,i?.customiseAllText??!1),l={command:void 0,helperData:{},errorData:this.getErrorsForText(t,s,a,r)};if(l.errorData)return l;l.helperData.charactersRemaining=a.data.maxLength-s.length;const c=[],d=new Map,A=new Map;for(const u of e){if(!u.fontData)throw new L("Failed to resolve font data for text.");const[h,g]=Kt(u.fontSize,u.fontData,{left:u.x,top:u.y,width:u.width,height:u.height,rotation:u.rotation},[s],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});d.set(u.id,h),A.set(u.id,g);const m=a.data.curved?s:(g||[]).join(`
1505
- `);c.push(this.generateTextChangeCommandsForRegion(h,a.data,u.id,m))}return!a.data.curved&&e.length>0&&!Array.from(A.values()).every(h=>h)?(l.errorData||(l.errorData={}),l.errorData.doesNotFit=!0,l):(r.updateStorage(a.stepName,{text:t}),r.updateMetadata(a.stepName,{text:s}),(i?.defaultCleared||!a.data.deleteDefaultOnFocus)&&s.trim()!==""&&r.setMandatoryFulfilled(a.stepName,!0),l.command=new Q(c),l)}async selectVariant(t,e,a,r,i){const o=await this.selectVariantCommand(t,e,a.getStepStorage(t.stepName)||{},a.getRegionElements(t.stepName),a,r,i);o&&(o.command&&a.getCommandDispatcher()(o.command),o.followup&&await o.followup())}createTextFillSpotColor(t,e){const a=t.colorProfile;if(a){const r=(a.name||"").replace(/\s/g,"-"),i=r.lastIndexOf("/"),s=r.slice(i+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:s,namedColor:e.namedColor}}}async reload(t,e,a){const r=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(r?.selectedVariants){const c=r.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(A=>A.id===c);if(d){const A=await this.fontDataFromVariant(d),u=s.map(p=>({id:p.id,region:p.stepRegion})),h=r.storage?.color;let g=r.storage?.text;const m=e.getWorkflowExperience().getBundle();if(m&&t.globalPropertyAspectConfigurations){const f=m.getGlobalPropertyConfiguration()?.aspects?.find(S=>S.type===U.Text&&t.globalPropertyAspectConfigurations?.map(b=>b.aspectName).includes(S.name));if(f){const b=m.getGlobalPropertyStateManager().getAspect(f.name);b&&(g=b)}}if(await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateMetadata(t.stepName,{color:h,text:g}),e.updateStorage(t.stepName,{text:g,inputText:g});const p=s.map(S=>new Ca(S.id,A)),f=new Q(p);e.getCommandDispatcher()(f)}),s.length===0&&l){const p=W.getDefaultVariant(l);if(p){const f=await this.selectVariantCommand(t,p,{text:g},[],e,()=>{},()=>{});e.getCommandDispatcher()(f.command)}}else{const{command:p}=q.updateInputText(g||"",s,t,e);p&&e.getCommandDispatcher()(p)}}}}else{const c=e.getWorkflowExperience().getBundle();if(c&&t.globalPropertyAspectConfigurations){const A=c.getGlobalPropertyConfiguration()?.aspects?.find(u=>u.type===U.Text&&t.globalPropertyAspectConfigurations?.map(h=>h.aspectName).includes(u.name));if(A){const h=c.getGlobalPropertyStateManager().getAspect(A.name);if(h)if(s.length===0&&l){const g=W.getDefaultVariant(l);if(g){const m=await this.selectVariantCommand(t,g,{text:h},[],e,()=>{},()=>{});e.getCommandDispatcher()(m.command)}}else{const{command:g}=q.updateInputText(h,s,t,e);g&&e.getCommandDispatcher()(g)}}}}}getDefaultColorVariant(t){const e=t.colorOption;if(e)return W.getDefaultVariant(e)}getDefaultColor(t){const e=t.colorOption;return e?W.getDefaultVariant(e)?.color:void 0}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return W.getDefaultVariant(e)}getDefaultStrokeColorVariant(t){const e=t.strokeOption;if(e)return W.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new pt(t);const a=e.fileLink;if(!a)throw new Qt(e);const r=await xt(a);return{assetUrl:a,name:r.names.fullName.en}}async selectVariantCommand(t,e,a,r,i,o,s,l,c){const d=i.markUpdatePending(),A=await this.fontDataFromVariant(e);if(r.length>0){const u=r.map(m=>new Ca(m.id,A));if(l){const m=r.map(p=>new ta(p.id,l));u.push(...m)}if(c){const m=r.map(p=>new ea(p.id,c,t.data.strokeThickness));u.push(...m)}const h=await this.changeInputTextWithRegion(t,t.data.size||na,A,a.text||"",a,i,a?.customiseAllText??!1,o,s);return h&&u.push(h),{command:new Q(u),followup:async()=>{i.markUpdateCompleted(d),await i.setSelectionsAndElements(t.stepName,[e],r)}}}else{const u=await this.createTextboxRegions(t.stepName,e,t.data,A,a,i),h=await this.changeInputTextWithRegion(t,t.data.size||na,A,u[0]?.newElement.input||a.text||t.data.defaultText||"",a,i,a?.customiseAllText??!1,o,s),g=u.flatMap(p=>p.commands);if(l){const p=u.map(f=>new ta(f.regionElement.id,l));g.push(...p)}if(c){const p=r.map(f=>new ea(f.id,c,t.data.strokeThickness));g.push(...p)}return h&&g.push(h),{command:new Q(g),followup:async()=>{i.markUpdateCompleted(d)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,a,r,i,o){if(!a||!a.regions)throw new Error("Step data not supplied");const s=i.text||a.defaultText||"",l=Mt(s,o),c=this.getProcessedInput(l,a,!1),d=async u=>{const g=o.getLayouts().find(p=>p.panelId===u.panelId),m=M();try{if(!g)throw new Ne("Failed to find layout for region: "+u.panelId);const p=a.colorOption;let f;if(p&&p.variants){const et=p.variants.find(at=>at.id===p.defaultVariant?.id)||p.variants[0];f=this.createTextFillSpotColor(p,et),o.updateStorage(t,{colorProfileAssetKey:p.colorProfile?.key})}const S=await this.getDefaultColor(a),b=S||"#000000",P={stepRegion:u,stepName:t,align:this.textAlign(a),fill:i.color?i.color:b,fontSize:a.size||na,fontData:r,id:m,layer:u.layer,layerIndex:u.layerIndex,rotation:u.rotation,text:c,input:s,type:F.Textbox,vertical:a.vertical,x:u.left,y:u.top,height:u.height,width:u.width,immutable:u.immutable,verticalAlign:a.verticalAlign||"middle",curved:a.curved,paths:a.paths,fillSpotColorDefinition:f},C=[],E=new Map,x=new Map;if(!P.fontData)throw new L("Failed to resolve font data for text.");const[B,D]=Kt(P.fontSize,P.fontData,{left:P.x,top:P.y,width:P.width,height:P.height,rotation:P.rotation,panelId:""},[c],{size:a.size,minSize:a.minSize,maxSize:a.maxSize});E.set(P.id,B),x.set(P.id,D);const O=a.curved||a.vertical?c:(D||[]).join(`
1506
- `);C.push(this.generateTextChangeCommandsForRegion(B,a,P.id,O));const T=new z(P,g);return{regionElement:{id:m,region:u},commands:[T,...C],newElement:P,fontData:r}}catch(p){throw console.log(p),new Te("Error adding font to region")}},A=await Promise.all(a.regions.map(d)).catch(u=>{throw u instanceof Te?(pr.setLatestToast("Failed to load font.",pe.Error),u):u instanceof Ne?u:new Error(u)});return await o.setSelectionsAndElements(t,[e],A.map(u=>u.regionElement),async()=>{o.updateMetadata(t,{text:s}),o.updateStorage(t,{text:s})}),A}generateTextChangeCommandsForRegion(t,e,a,r){const i=[],o=new hr(a,r);if(i.push(o),!e.size){const l=new Ar(a,t);i.push(l)}return new Q(i)}async changeInputTextWithRegion(t,e,a,r,i,o,s,l,c,d){const A=(r||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),u=Mt(A,o),h=this.getProcessedInput(u,t.data,s),g=o.getRegionElements(t.stepName),m=new Map,p=new Map;for(const C of g)if(C.region){const[E,x]=Kt(e,a,C.region,[h],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});m.set(C.id,E),p.set(C.id,x)}const S=(()=>{if(t.data&&t.data.maxLength&&h.length>t.data.maxLength)return d&&d(!0),{info:"0"};const C=o.getProfanities(),E=la.split(h.toLowerCase());for(const x of E)for(const B in C){const D=C[B].toLowerCase().replace(/\s/g,"");if(x===D)return l(!0),{error:"Blocked profanity."}}return!t.data.vertical&&!t.data.allowNewlines&&(h.includes(`
1507
- `)||h.includes("\r"))?(l(!0),{error:"Cannot span multiple lines."}):!t.data.curved&&!Array.from(p.values()).every(B=>B)?(l(!0),{error:"Does not fit."}):(l(!1),{info:(t.data.maxLength-h.length).toString()})})();if(S.error){c(S.error);return}if(c(`${S.info} characters remaining`||""),d)return;o.updateStorage(t.stepName,{text:A}),o.updateMetadata(t.stepName,{text:this.injectReplaceableText(A,t.data)}),(i.defaultCleared||!t.data.deleteDefaultOnFocus)&&A.trim()!==""&&o.setMandatoryFulfilled(t.stepName,!0);const b=[];for(const C of g){const E=t.data.curved?h:(p.get(C.id)||[]).join(`
1508
- `);b.push(this.generateTextChangeCommandsForRegion(m.get(C.id)||1,t.data,C.id,E))}return new Q(b)}}const q=new Os;class $s{}const Us="data:application/octet-stream;base64,AAEAAAAPAIAAAwBwRkZUTYdHeHoAAElcAAAAHEdERUYAJwBUAAAe2AAAAB5HUE9TkNtcVAAAHygAACoyR1NVQrj/uP4AAB74AAAAME9TLzJoWmUcAAABeAAAAGBjbWFwtkIacAAAAxAAAAJWZ2FzcP//AAMAAB7QAAAACGdseWY27KOUAAAGCAAAFcRoZWFkFPal0gAAAPwAAAA2aGhlYQU0Ar0AAAE0AAAAJGhtdHiADw6qAAAB2AAAAThsb2Nh5CzfJAAABWgAAACebWF4cACVAEwAAAFYAAAAIG5hbWXeIPPyAAAbzAAAAiJwb3N0ABeZTwAAHfAAAADdAAEAAAABAAAZ9vREXw889QALA+gAAAAA2ZexNAAAAADZl7E0ADL/yQJ2ArwAAAAIAAIAAAAAAAAAAQAAArz/wwAAAqsAAAAAAnYAAQAAAAAAAAAAAAAAAAAAAE4AAQAAAE4ASQAFAAAAAAACAAAAAQABAAAAQAAAAAAAAAAEAbsBkAAFAAACigK7AAAAjAKKArsAAAHfADEBAgAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAABYWFhYAEAACgCtArz/wwAAAqkANgAAAAMAAAAAAmQCZAAAACAAAgIPADIAAAAAAU0AAAAAAAAAAAAAALQAAAD3ADUCfQA1AcoANQKrADUCDQA1AX4ANQHYADUBNQA1AcgANQHUADUB8AA1AeEANQHpADUBqQA1AdAANQHpADUCqgA1Af8ANQGaADUB3wA1AbgANQFtADUBbQA1AekANQG8ADUA1QA1AYcANQHBADUBUAA1AhsANQHBADUB4QA1AZYANQH0ADUBxQA1AcUAMgGJADUBwwA1Ad0ANQJ1ADUB9wA1AcoANQF6ADUB3AA1Af8ANQGaADUB3wA1AbgANQFtADUBbQA1AekANQG8ADUA1QA1AYcANQHBADUBUAA1AhsANQHBADUB4QA1AZYANQH0ADUBxQA1AcUAMgGJADUBwwA1Ad0ANQJ1ADUB9wA1AcoANQF6ADUAtAAAAAAAAAAAAAMAAAADAAAAHAABAAAAAAFQAAMAAQAAABwABAE0AAAALgAgAAQADgAAAAoADQAhACYAKgA5AFoAXgB6AKAArQDFAM8A1gDdAOUA7wD2AP0A/wF4//8AAAAAAAoADQAgACMAKgAwAEAAXgBhAKAArQDAAMcA0QDYAOAA5wDxAPgA/wF4//8AAf/5//f/5f/k/+H/3P/W/9P/0f+s/6AAAAAAAAAAAAAAAAAAAAAA/0v+twABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABYAIAAwADoARABOAF4AaAAAAAAAAAAXABcAFwAXABcAFwAZABsAGwAbABsAHwAfAB8AHwAkACUAJQAlACUAJQAlACsAKwArACsALwAyADIAMgAyADIAMgA0ADYANgA2ADYAOgA6ADoAOgA/AEAAQABAAEAAQABAAEYARgBGAEYASgAAAQYAAAEAAAAAAAAAAQIDAAAEAAAAAAAAAAAAAAAAAAAAAQAABQYABwgJCgAAAAsAAAAAAAwNDg8QERITFBUAAAAAAAAWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAAAAAxAAAyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKSwAAAAAAFxcZGyQlKzIyMjIyMjQ2NjY2Ojo6Oj9AQEBAQEZGRkYAAAAAAAAAAAAAAAAAAAAlAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAABMFxclAAAAAAAAAAAAAEovAAAAAAAAAAAAAAAXGxcbGx8fHx8lJQAlKysrAAAAAAAAAAAAAAAAAAAAACgAKAAoACgAKAAoADwAbgC0AQgBbgGQAcYB1AIGAkYCYAKSAtAC4gMoA2ADyAPgBBoEUAR4BI4EogTWBOoE9gUiBToFSAViBXoFqgXWBjAGWgaaBqwG2AbqBwYHIAc2B0wHXgd2B7AH5ggOCCQIOAhsCIAIjAi4CNAI3gj4CRAJQAlsCcYJ8AowCkIKbgqACpwKtgrMCuIK4griAAAABQAyAAAB3QK8AAMABgAJAAwADwAAEyERIRsCCwEREwMhAxMRMgGr/lUcubrGtMG5AXKttQK8/UQCqP7LATX+tgEs/acBGP7MAUn+0QJdAAACADUABQDCAmoAAwAHAAATESMRExUjNcGLi4sCaf5mAZr+KY2NAAAAAgA1AAACSAJkABsAHwAAJQcjNyMHIzcjNzM3IzczNzMHMzczBzMHIwczByc3IwcBthdrFkoXbBdeDl8KYA9fFWwVShVtFWoPagpqDscJSgqqqqqqqmxHbJqamppsR2xsR0cAAAEANf/JAZUCqgAwAAABFR4BByM0LgEjIgYVFBYXHgMVFA4BBxUjNS4BNTMUFjMyNjU0LgInJjU0Njc1ARwwPAF3CBQOExcsPCEwFgkZNyhnPkGDGRQTGBElHBprRzQCqkQNV0INGBIdFB8hGw4tMCkUJkU7EENDCmk8GiUgFBIeGA4LKXpKVxBEAAAABQA1/+8CdgJrAAwAGAAcACkAOAAAEzQ2MzIeARUUBiMiJjcVFBYzMjY1NCYiBiUDIxMDNTQ+ATMyFhQGIyImNxUUHgEzMjY1NC4BIyIGNk02JD0jTTc2TVEeFBUeHiodAWjhVeEtIz0kN01ONjZOUQ4YDRUeDhcOFR4B1j5XKEUoPldXPgEXISEYGCEhcf2dAmP+JgEoRChXfFdWPwEPGhAiGBAbDyIAAwA1AAAB2AJnACQAOQBIAAAlFwcnDgEjIiY1ND4CNyY1NDYzMhYVFA4IBxc3MyciBhUUHgQXPgU1NCYjAxY+ATcnDgUVFBYBmT8qQgdUMk1cDyETFDVTNzdPAwUJBw0HDgUMATUabPULGQQFCgUKAQENBAsEBBYNAQ8bEQRRAQ4ECwUEIbFNZEERMGJKHzMqEhFDQD9ZVjsLFxITDRAJDgULAUFBtRgSBw4LDwcOAQEQBg8LDwcPGf58AQsOB2IBDQUOCg8IGyQAAAAAAQA1ATwBSQJtABEAABMHNxcHFwcnFyM3Byc3JzcXJ+YXVSVnZyhTGE0WUShnZyVWGAJselJLJSVOVXp7Vk4nI0tReQACADUAAAGjAmQAFwAmAAA3NTQ+AzMyHgMdARQOAiMiLgI3FRQeATMyPQE0IyIOAjYZJzIvFxQtMicaIjc9Hh09OiR8CBsXOTkSGAsF4KQxTzEhDQwhMFAypDtaMhkYMlvjrBUkH1isVxEeGgABADUAAAEAAmEABQAAMxEjNTMRhE7KAd6D/Z8AAQA1AAMBkwJmACEAADc1Njc+AzU0JiMiByM+Ajc+AzMyFhUUBgcGBzMVOi5WFxkaCx0XMQJ2AQINDQ4qLCIQTlkjLkAargN3L1kYHCcoFyIhXhsgNxccJxIHbU04WDRHHYEAAAEANQAAAZ8CZAAtAAATNjc2MzIWFRQOAwcWFRQGIyImJyYnMxYXMjY1NC4DKwE1MzI1NCYjIgdDAjktP0RVCw0VCwlca0otVRYVBn4KLhobCg8UDQcsFT0RESQCAaxgMCdfQRcoGBcIBiVpTWwrKCRENgElHRAYCwcCbzsVHjMAAgA1//8BuwJjAAoADQAAITUjNRMzETMVIxUnMzUBDdfadDY20WJrcgGF/oN6a+XAAAAAAAEANf//AawCYwAgAAABFSMHNjMyHgIVFA4CIyIuASczFjMyNjU0JiMiBycTAX+uCxsnKUIlExYrSy8zUS8HfRYjGygkHy4SZSoCYoBSEic+QyEkSkIqL00xJi8hHy80HwFTAAACADUAAAG0AmIAFgAoAAABMhYVFAYjIiYnJjU0PwEzBw4BBzAyNgMyPgE1NC4EIyIGFRQeAQEaO19vTy9QGCksepBYAw4CCA0kEx8TBAgLDxQLHSUVHQGvbF9kgConOV1LVdqUBRYFAv7XFCYXChMSEAwHLyEaJxIAAAAAAQA1//8BdAJjAAYAABMhFQMjEyM2AT6sibS9AmJ3/hUB3wAAAwA1AAABmwJkABkAJAAuAAATNTQ2MhYVFA4BBxYVFA4BIi4BNTQ3LgMXFRQWMjY1NCYiBjcVFBYyNjQmIgZCVqBWFBAMPC1RaFEtPAkLEgpwHjAdHTAeCRskGxskGwG/AUJhYkIeMxINJGU5WjMzWjllJAkNHSbhARgqKhkaKirTARcfHy8fHwAAAAACADUAAAG0AmQAFgAkAAA/AT4BNyYOASMiJjU0NjMyFhcWFRQPARM1NC4BIyIGFRQWMzI2fVgDDQQBCA0EO15uTy9QGCoteSsVHhAcKCUfHiUBlAQWBgEBAWxfZIAqJzldTFXaAYkBGiYSLiIgMi4AAgA1/8wCdQJtADgASAAAAQcGBwYzMjY1NCYjIgYHBh4DFxY3FQYnLgQ3ND4CMzIWFRQGIyInBicuATU0NjMyFhc3BzY1NC4CJyYGHQEUFjc2AfscBAIBFhYmbFVhdgcBBhwtVThNX01cQGlGMBUBLExzQniZWjs3FB07NT1PQBwoBwgqCQIHEg0gKCAUIQG2ux0NGVo8Wm2Laxg2RTcpBAUfWxsCASlBVlsvQHpfOqF8XZBBNwEBWkRIcyAWKMkaIgcQGBEBAz8rAyYjAQIAAAIANQAAAcgCZQAHAAoAADcHIxMzEyMvAge8GG6bYJdvGhknK3JyAmT9nHJz1tYAAAMANQABAWQCaAAPABoAJQAANxEzMhcWFRQHFhUUBw4BIwMzMjc2NTQnJisBFxUzMjc2NTQnJiM2lEAiJC9DJhszNx0mEgkQEAgUJQExFAsVFAoWAgJlKShQUygka1cuIhMBfAYLIB4LBuNwCA4mIgwGAAAAAQA1AAABqQJnACUAACUzDgEjIi4CNTQ+AjMyHgMXIy4DIyIOARUUFjMyPgIBSWAQX0cxSiwWFStLMSM7KB4QA2AFDhQfER4pEi8qFCEUCulrfjNXbD47alk0HzJAPR0SISATNEwsSWcXJxkAAgA1AAABgwJlAA8AGAAAMxEzMh4DFxYVFA4CIwMRMzI1NCcmIzZ/EhcsICYOJBUtTzUiKF4TFzMCZAEMFi4hT29BbFcwAdr+r6dDLjkAAAABADUAAAE3AmUACwAAEyEVIxUzFSMVMxUhNgEBlpGSlv8AAmR4cHmKeQAAAAEANQAAATcCZQAJAAAzESEVIxUzFSMRNgEBmJOTAmR5b3r+/gAAAAABADUAAAG3AmYAIQAAARUmBw4CFRQeAjMyNzY3IzUzFgcGIyIuATU0NjMyFhcBQBQ3FygbEBkgESEWGQVr0wUTMH89WCpiX0haEAGbAUgCASNPOC1FKhUaHDlpZkOyVYlXiaZvWwAAAAEANQAAAYYCZQALAAAzIxEzFTM1MxEjNSOcZmaDZ2eDAmTm5v2c9QABADUAAACgAmUAAwAAMxEzETZpAmT9nAABADUAAAFRAmUAGgAAAREUBwYHBiMiLgMnJjUzFBYVFjMyNzY1EQFQDQ8fJi4IESsgIAUCcQEEGxUHBAJk/pZkLCscIwIRHkEsFxcCDAQzGxAhAZEAAAAAAQA1//8BiwJmAAoAABcRMxETMwMTIwMRNmdzbISTfnABAmb+7AEU/s/+zAEJ/vYAAQA1AAABGgJlAAUAADMRMxEzFTZpewJk/iaKAAEANQAAAeUCZQAMAAAzIxEzGwEzESMTAyMDlmCLTEuMYARZRVgCZP52AYr9nAHK/jYBygABADUAAAGMAmUACQAAGwEDMxEjAxMjEZ2NAWNikwJjAmT+lAFs/ZwBaf6XAmQAAAACADUAAAGsAmUADAAfAAATNDYzMhYVFA4BIyImNxQWMzI+BDU0LgIjIg4BNmRWUWs0VDRWZGgqKg8aEQ0IAwgSIhceJw4BLKGXmJpfjUaelUtjDxohKCcUHzo1IDVKAAACADUAAAFgAmYAEAAbAAATMzIeARcWFRQGBw4BKwEVIxMVMzI3NjU0JyYjNoEjMRoMLhcSFjEtKGRkJRoNGBkOHAJlCxMPO2cvWRkdGMAB3ZMJEi8uEQoAAwA1//8BvwJmABsALgA8AAAlFwYiLgInDgIjIi4BNTQ+ATMyFhUUBx4CAyIOBAc2MzIXFhc2NTQuAQMeAzsBMjcmJyYjIgG9AQINGRgcChMsFBM+VycmWD1Uah0GDQzAERwSDQcCARgVKCIbHQkbLGgGFRUTBgYWDhEOGSAPenkBAggSDRMTAlaGU1GIXK5/ZUkIBwEBZxIgHScLCBEoHzQeLTJOKP7/HCgQCQwiFSMAAAAAAgA1//8BjwJmAA0AGgAAJRcjJxUjETMXFhcWFRQnNjU0LgInKwEVMzIBDYF+cGpqOi4UW4QYCxARBQY1Lhb7++vqAmQBBQosgohEFyoVHg4IAZkAAQAyAAABjwJnACsAADczFBY3NjU0JicuAycmPgEzMhYXIy4DIyIGFRQWFx4BFRQOAiMiJjZ2JBIyJjwRICobAQE0TSs5WQp0AQMJEg0RHCdBQTEUJkQsXFbFKx8BBDgWIB4JFyg7ITlVKFRbCwwTCh0UFSIkJEc2JUE3IGkAAAABADUAAAFTAmUABwAAMxEjNSEVIxGLVQEdVQHseHj+FAAAAAABADUAAAGNAmUAGgAAEzMRFBceATI2NzY1ETMRFA4BBwYjIiYnLgE1NmsIBR8qHgUIagcQDjBUIk0ZGQwCZP6WLhsSGBYQFzUBa/6WM0MvFEEcJCZISwAAAQA1AAABpwJlAAYAADMDMxsBMwO2gGdQUWmAAmT+UwGt/ZwAAQA1AAACQAJkAAwAADMDMxsBMxsBMwMjCwGfaWk4PFA8OGhrWz4+AmP+cwGN/nEBj/2dAYz+dAABADUAAAHBAmUACwAAMxMDMxc3MwMTIycHNop6c0NCcnmJc1VRAUYBHq6u/t/+vdnZAAAAAQA1AAABlAJlAAkAADczAzMXNzMDFSOsAXdvQUFtd3HrAXn29v6H6wAAAAABADUAAAFDAmYACQAAAQMzFSE1EyM1IQFDiIj+85OTAQ0B5v6kimcBdYkAAAEANQFFAaYCagAGAAAbATMTIycHNnx3fYE4NwFFAST+3LOzAAIANQAAAcgCZQAHAAoAADcHIxMzEyMvAge8GG6bYJdvGhknK3JyAmT9nHJz1tYAAAMANQABAWQCaAAPABoAJQAANxEzMhcWFRQHFhUUBw4BIwMzMjc2NTQnJisBFxUzMjc2NTQnJiM2lEAiJC9DJhszNx0mEgkQEAgUJQExFAsVFAoWAgJlKShQUygka1cuIhMBfAYLIB4LBuNwCA4mIgwGAAAAAQA1AAABqQJnACUAACUzDgEjIi4CNTQ+AjMyHgMXIy4DIyIOARUUFjMyPgIBSWAQX0cxSiwWFStLMSM7KB4QA2AFDhQfER4pEi8qFCEUCulrfjNXbD47alk0HzJAPR0SISATNEwsSWcXJxkAAgA1AAABgwJlAA8AGAAAMxEzMh4DFxYVFA4CIwMRMzI1NCcmIzZ/EhcsICYOJBUtTzUiKF4TFzMCZAEMFi4hT29BbFcwAdr+r6dDLjkAAAABADUAAAE3AmUACwAAEyEVIxUzFSMVMxUhNgEBlpGSlv8AAmR4cHmKeQAAAAEANQAAATcCZQAJAAAzESEVIxUzFSMRNgEBmJOTAmR5b3r+/gAAAAABADUAAAG3AmYAIQAAARUmBw4CFRQeAjMyNzY3IzUzFgcGIyIuATU0NjMyFhcBQBQ3FygbEBkgESEWGQVr0wUTMH89WCpiX0haEAGbAUgCASNPOC1FKhUaHDlpZkOyVYlXiaZvWwAAAAEANQAAAYYCZQALAAAzIxEzFTM1MxEjNSOcZmaDZ2eDAmTm5v2c9QABADUAAACgAmUAAwAAMxEzETZpAmT9nAABADUAAAFRAmUAGgAAAREUBwYHBiMiLgMnJjUzFBYVFjMyNzY1EQFQDQ8fJi4IESsgIAUCcQEEGxUHBAJk/pZkLCscIwIRHkEsFxcCDAQzGxAhAZEAAAAAAQA1//8BiwJmAAoAABcRMxETMwMTIwMRNmdzbISTfnABAmb+7AEU/s/+zAEJ/vYAAQA1AAABGgJlAAUAADMRMxEzFTZpewJk/iaKAAEANQAAAeUCZQAMAAAzIxEzGwEzESMTAyMDlmCLTEuMYARZRVgCZP52AYr9nAHK/jYBygABADUAAAGMAmUACQAAGwEDMxEjAxMjEZ2NAWNikwJjAmT+lAFs/ZwBaf6XAmQAAAACADUAAAGsAmUADAAfAAATNDYzMhYVFA4BIyImNxQWMzI+BDU0LgIjIg4BNmRWUWs0VDRWZGgqKg8aEQ0IAwgSIhceJw4BLKGXmJpfjUaelUtjDxohKCcUHzo1IDVKAAACADUAAAFgAmYAEAAbAAATMzIeARcWFRQGBw4BKwEVIxMVMzI3NjU0JyYjNoEjMRoMLhcSFjEtKGRkJRoNGBkOHAJlCxMPO2cvWRkdGMAB3ZMJEi8uEQoAAwA1//8BvwJmABsALgA8AAAlFwYiLgInDgIjIi4BNTQ+ATMyFhUUBx4CAyIOBAc2MzIXFhc2NTQuAQMeAzsBMjcmJyYjIgG9AQINGRgcChMsFBM+VycmWD1Uah0GDQzAERwSDQcCARgVKCIbHQkbLGgGFRUTBgYWDhEOGSAPenkBAggSDRMTAlaGU1GIXK5/ZUkIBwEBZxIgHScLCBEoHzQeLTJOKP7/HCgQCQwiFSMAAAAAAgA1//8BjwJmAA0AGgAAJRcjJxUjETMXFhcWFRQnNjU0LgInKwEVMzIBDYF+cGpqOi4UW4QYCxARBQY1Lhb7++vqAmQBBQosgohEFyoVHg4IAZkAAQAyAAABjwJnACsAADczFBY3NjU0JicuAycmPgEzMhYXIy4DIyIGFRQWFx4BFRQOAiMiJjZ2JBIyJjwRICobAQE0TSs5WQp0AQMJEg0RHCdBQTEUJkQsXFbFKx8BBDgWIB4JFyg7ITlVKFRbCwwTCh0UFSIkJEc2JUE3IGkAAAABADUAAAFTAmUABwAAMxEjNSEVIxGLVQEdVQHseHj+FAAAAAABADUAAAGNAmUAGgAAEzMRFBceATI2NzY1ETMRFA4BBwYjIiYnLgE1NmsIBR8qHgUIagcQDjBUIk0ZGQwCZP6WLhsSGBYQFzUBa/6WM0MvFEEcJCZISwAAAQA1AAABpwJlAAYAADMDMxsBMwO2gGdQUWmAAmT+UwGt/ZwAAQA1AAACQAJkAAwAADMDMxsBMxsBMwMjCwGfaWk4PFA8OGhrWz4+AmP+cwGN/nEBj/2dAYz+dAABADUAAAHBAmUACwAAMxMDMxc3MwMTIycHNop6c0NCcnmJc1VRAUYBHq6u/t/+vdnZAAAAAQA1AAABlAJlAAkAADczAzMXNzMDFSOsAXdvQUFtd3HrAXn29v6H6wAAAAABADUAAAFDAmYACQAAAQMzFSE1EyM1IQFDiIj+85OTAQ0B5v6kimcBdYkAAAAAEADGAAEAAAAAAAEACAASAAEAAAAAAAIABwArAAEAAAAAAAMAFQBfAAEAAAAAAAQACACHAAEAAAAAAAUAIgDWAAEAAAAAAAYADwEZAAEAAAAAABAACAE7AAEAAAAAABEABwFUAAMAAQQJAAEAEAAAAAMAAQQJAAIADgAbAAMAAQQJAAMAKgAzAAMAAQQJAAQAEAB1AAMAAQQJAAUARACQAAMAAQQJAAYAHgD5AAMAAQQJABAAEAEpAAMAAQQJABEADgFEAFYAZQBnAGUAbQBpAHQAZQAAVmVnZW1pdGUAAFIAZQBnAHUAbABhAHIAAFJlZ3VsYXIAADEALgAwADAAMgA7AFYAZQBnAGUAbQBpAHQAZQBSAGUAZwB1AGwAYQByAAAxLjAwMjtWZWdlbWl0ZVJlZ3VsYXIAAFYAZQBnAGUAbQBpAHQAZQAAVmVnZW1pdGUAAFYAZQByAHMAaQBvAG4AIAAxAC4AMAAwADIAOwBGAG8AbgB0AHMAZQBsAGYAIABNAGEAawBlAHIAIAAzAC4AMwAuADAAAFZlcnNpb24gMS4wMDI7Rm9udHNlbGYgTWFrZXIgMy4zLjAAAFYAZQBnAGUAbQBpAHQAZQBSAGUAZwB1AGwAYQByAABWZWdlbWl0ZVJlZ3VsYXIAAFYAZQBnAGUAbQBpAHQAZQAAVmVnZW1pdGUAAFIAZQBnAHUAbABhAHIAAFJlZ3VsYXIAAAAAAgAAAAAAAP+DADIAAAAAAAAAAAAAAAAAAAAAAAAAAABOAAAAAQACAQIBAwADAAQABgAHAAgACQANABMAFAAVABYAFwAYABkAGgAbABwAIwAkACUAJgAnACgAKQAqACsALAAtAC4ALwAwADEAMgAzADQANQA2ADcAOAA5ADoAOwA8AD0AQQBEAEUARgBHAEgASQBKAEsATABNAE4ATwBQAFEAUgBTAFQAVQBWAFcAWABZAFoAWwBcAF0ArAEECWNvbnRyb2xMRgljb250cm9sQ1IKc29mdGh5cGhlbgAAAAAAAAH//wACAAEAAAAMAAAAFgAAAAIAAQABAE0AAQAEAAAAAgAAAAAAAQAAAAoALAAuAAJERkxUAA5sYXRuABgABAAAAAD//wAAAAQAAAAA//8AAAAAAAAAAQAAAAoAMAA+AAJERkxUAA5sYXRuABoABAAAAAD//wABAAAABAAAAAD//wABAAAAAWtlcm4ACAAAAAEAAAABAAQAAgAAAAEACAABKd4ABAAAAEYAlgEwAd4CjAM2A+AEegUsBWYGDAa+B3AIHgjQCYIKNAriC4gMAgx0DOYNZA3mDlQOyg88D54QEBCGEQARchHsEmIS1BOWFAwUghTwFWIV1BaiFxQXkhgEGMYZdBomGtQbfhwYHL4dYB3+HpgfPh/oIJYhPCHmIpQjRiPsJJolSCXuJpQnQifoKJIpRAAmAAn/8QAK//sADP/7AA3/+wAO//sAD//7ABD/+wAR//sAEv/7ABP/+wAU//sAFf/xABb/8QAZ//sAHf/2AB7/+wAf//sAIP/xACH/+wAi//sAI//7ACT/+wAl//EAJv/2ACf/8QAo//sAKf/2ACr/+wAr//sALP/sAC3/7AAu/+IAL//dADD/9gAx/+wAMv/7ADP/+wA0//YAKwAG//EACP/nAAn/4gAK/9MAC//iAAz/9gAN/+IADv/sAA//4gAQ/9gAEf/iABL/1QAT//EAFP/nABX/8QAW/9gAMf/TADL/pgAz//MANP/nADX/8QA2//EAN//7ADj/7gA5//YAOv/7ADv/2AA8//EAPf/2AD7/9gA///EAQP/sAEH/+wBC/+wAQ//xAET/7ABF/+wARv/2AEf/3QBI/90ASf/EAEr/zgBL//YAKwAG//YAB//2AAn/3QAL/+wADP/sAA3/8QAO//YAD//sABD/8QAR/+wAEv/iABP/5wAU/+wAFf/dABb/7AAX/78AMf/YADL/sAAz/+IANP/iADX/8QA2/+cAN//xADj/3QA5/+wAOv/2ADv/4gA8//EAPf/xAD7/8QA///YAQP/YAEH/9gBC/+cAQ//sAET/7ABF/+wARv/xAEf/zgBI/9MASf/OAEr/zgBL/+wAKgAG//YAB//iAAj/4gAK/+IADP/dAA3/ugAO/+IAD//iABD/5wAR/+IAEv/dABP/yQAU/90AFf+mABb/0wAx/5gAMv/YADP/4gA0/9MANf/xADb/7AA3/+wAOP/iADn/7AA6//EAO//dADz/5wA9/+wAPv/sAD//5wBA/9gAQf/sAEL/zgBD/+wARP/YAEX/tQBG/90AR/+hAEj/oQBJ/8QASv+DAEv/7AAqAAb/8QAH/90ACP/YAAn/oQAL/8kADP/iAA3/sAAO/+cAD//YABD/4gAR/90AEv/bABP/4gAU/+IAFf/TABb/5wAg/+QAMf/nADL/3AAz//QANP/rADX/9AA2//IAN//4ADj/8AA5//QAOv/1ADv/7AA8/+oAPf/7AD7/9wA///IAQP/tAEH/+wBC/+IAQ//2AET/4wBF/7YARv/vAEf/pgBK/6MAS//yACYAB//TAAj/8QAK/84ADP/dAA3/9gAO//EAD//dABD/pgAR/8kAEv+6ABP/7AAU/90AFf/OADH/xAAy/5IAM//sADT/3QA1/+cANv/xADf/9gA4/90AO/9WADz/5wA9//EAPv/sAD//5wBA/84AQf/dAEL/0wBD/+cARP/nAEX/5wBG/+cAR//dAEj/2ABJ/7oASv/JAEv/4gAsAAb/+wAH//sACP/xAAn/zgAK/+cAC//dAAz/9gAN/9gADv/tAA//7AAQ/+kAEf/rABL/3QAT/90AFP/hABX/3QAW/90AMf/nADL/vwAz/+cANP/nADX/8QA2//EAN//sADj/5wA5//YAOv/2ADv/4gA8//EAPf/2AD7/+wA///sAQP/2AEH/+wBC/+wAQ//7AET/7ABF/9MARv/7AEf/yQBI/84ASf+wAEr/xABL/+cADgAG//sACf/xAAv/7AAN//sADv/7AA8AAAAR//EAEv/0ABP/9gAU//EAFf/xABb/7AAx//YAQP/2ACkABv/7AAf/9gAI//sACf/iAAr/5wAL/+wADP/vAA3/3QAO//sAD//qABD/8QAR/+wAEv/nABP/8QAU/+cAFf/iABb/7AAx/+cAMv/vADP//AA0/+cANf/7ADb//gA4//EAOf/8ADr//AA7/+kAPP/6AD3//QA+//4AP//7AEL/6gBD//0ARP/2AEX/7ABG//EAR//YAEj/4gBJ/+wASv/LAEv//AAsAAb/+wAH//EACP/2AAn/0wAK/+IAC//JAAz/5wAN/90ADv/iAA//7AAQ/+cAEf/sABL/3QAT/9MAFP/iABX/zgAW/+cAMf/YADL/xAAz/+wANP/dADX/6AA2//EAN//xADj/4wA5//EAOv/2ADv/7AA8/+wAPf/sAD7/9gA//+wAQP/iAEH/8QBC/90AQ//nAET/5wBF/8QARv/mAEf/xABI/8kASf+1AEr/rQBL/+IALAAG//sAB//7AAj/9gAJ/9MACv/2AAv/ugAM/+kADf/dAA7/9gAP/+wAEP/2ABH/8AAS//EAE//2ABT/5wAV/9gAFv/sADH/vwAy/9UAM//eADT/3wA1//EANv/xADf/9gA4/+IAOf/xADr/9gA7/+wAPP/xAD3/9gA+//EAP//2AED/2ABB//EAQv/nAEP/9gBE/+cARf/TAEb/8QBH/9gASP/YAEn/xgBK/78AS//xACsABv/7AAf/9gAI/+wACf/TAAr/5wAL/90ADP/lAA3/zgAO/90AD//dABD/7AAR/+IAEv/iABP/2AAU/+IAFf/JABb/5wAx/90AMv/EADP/6wA0/+EANf/wADb/8AA4/9wAOf/dADr/7AA7/9gAPP/sAD3/5wA+/+wAP//iAED/0wBB/+IAQv/YAEP/4gBE/84ARf/JAEb/4gBH/8kASP/OAEn/vwBK/8kAS//TACwABv/7AAf/3wAI/+cACf+wAAr/4wAL/8kADP/dAA3/xwAO/+cAD//dABD/7AAR/+cAEv/iABP/yQAU/9cAFf+/ABb/4gAa/+kAMf/YADL/uwAz/+EANP/dADb/6wA3//MAOP/lADn/8QA6//IAO//eADz/5wA9/+4APv/zAD//8ABA/+IAQf/2AEL/6gBD//YARP/kAEX/zABG/+8AR/+0AEj/uwBJ/64ASv+vAEv/5QAsAAb/+wAH/90ACP/nAAn/4gAK/9MAC//nAAz/3QAN//YADv/eAA//3QAQ/7AAEf/OABL/sAAT//sAFP/dABX/0wAW/9MAMf/iADL/iAAz//YANP/OADX/9gA2//EAN//xADj/0wA5//YAOv/zADv/gAA8//EAPf/7AD7/+wA///YAQP/OAEH/7gBC/84AQ//2AET/2ABF//sARv/2AEf/5wBI/+cASf/TAEr/4gBL/+wALAAG//sAB//2AAj/8QAJ/9gACv/nAAv/3QAM/+IADf/dAA7/4gAP/+IAEP/nABH/5wAS/9gAE//YABT/3QAV/84AFv/sADH/5wAy/78AM//nADT/2AA1/+cANv/nADf/7AA4/90AOf/sADr/7AA7/+cAPP/sAD3/8QA+/+wAP//xAED/4gBB//EAQv/dAEP/5wBE/+IARf/YAEb/5wBH/78ASP/HAEn/sABK/7UAS//dACsABv/xAAf/8QAI/+IACf/dAAr/0wAL/+IADP/iAA3/3QAO/+cAD//dABD/zgAR/9MAEv/EABP/0wAU/84AFv/dADH/4gAy/6EAM//jADT/3QA1/+wANv/sADf/5wA4/90AOf/nADr/8QA7/78APP/xAD3/9gA+/+wAP//nAED/3QBB/+cAQv/nAEP/5wBE/+IARf/OAEb/3QBH/8QASP/JAEn/lwBK/7oAS//YACkABv/sAAf/0wAI/90ACf/OAAr/3QAM/90ADf/EAA7/5wAP/9gAEP/YABH/3QAS/9MAE//YABT/4gAV/90AMf/sADL/wAAz/+8ANP/kADX/6wA2//AAN//2ADj/5AA5//EAOv/uADv/1gA8//QAPf/2AD7/8QA///AAQP/dAEH/7ABD/+gARP/YAEX/1QBG/+wAR/+3AEj/wwBJ/7UASv+wAEv/5gAeAAf/zgAi/+4AI//5ACT/7wAy/9AAM//pADT/sQA1/+sANv/nADf/5gA4/7oAOf/vADr/9wA7/9AAPP/sAD3/6wA+/+YAP//sAED/uwBB/+kAQv+7AEP/5ABE/9QARf+6AEb/0ABH/34ASP+SAEn/zQBK/5sAS//nABwAF//RACT//wAy/9EAM//uADT/5wA1/+8ANv/3ADf/7gA4/+gAOf/3ADr/+wA7/9oAPP/vAD3/9wA+/+4AP//vAED/4QBB//cAQv/nAEP/7wBE/+4ARf/QAEb/9wBH/8EASP/MAEn/wwBK/7sAS//nABwAF//QABv/+QAy/8EAM//zADT/6wA1//sANv/zADf/+wA4/+8AOf/zADr//gA7/+EAPP/vAD3/9wA+//kAP//3AED/4gBB//kAQv/jAEP/8wBE/+YARf/VAEb/+QBH/84ASP/JAEn/twBK/8EAS//rAB8ABv/7ABL/3wAX/8kAJf/5ACv/7wAy/7oAM//zADT/6wA1/+8ANv/uADf/8wA4/+oAOf/vADr/7wA7/9QAPP/5AD3//gA+//EAP//vAED/4wBB//MAQv/mAEP/7gBE/+cARf/XAEb/6wBH/8kASP/JAEn/twBK/7cAS//nACAABv/7ACQAAgAl/+8AJ//5AC3//gAv//4AMv/oADP//QA0/+sANf/7ADb/+gA3//sAOP/jADn/9wA6//oAO//kADz//wA9//0APv/+AD8AAABA/+gAQf/7AEL/6ABD//sARP/sAEX/8QBG//sAR//qAEj/6wBJ/+cASv/qAEv/+QAbAAb/+wAl/+8AMv+5ADP/+wA0/+8ANf/7ADb/+wA3//0AOP/vADn/+wA6AAAAO/+7ADz//gA9//4APv/7AED/7ABB//4AQv/nAEP/+QBE//kARf/7AEb/+QBH//MASP/rAEn/4gBK/+8AS//7AB0ABv/2ABf/zgAl/+8AMv+3ADP/9wA0/+sANf/3ADb/8QA3//kAOP/uADn/8wA6//sAO//YADz/8wA9/+4APv/3AD//8wBA/+MAQf/3AEL/6QBD/+8ARP/nAEX/1ABG/+8AR//JAEj/zABJ/6YASv/JAEv/3AAcAAb/+wAX//MAJf/7ADL/6wAz//4ANP/uADX/+wA2//4AN//+ADj/8wA5//0AOv/+ADv/7gA8//4APf/+AD7/+wA///4AQP/uAEL/9wBD//4ARP/+AEX/+QBG//4AR//uAEj/9wBJ/+4ASv/zAEv//gAYAAb/+wAx//YAMv/rADP//wA0//MANf//ADYAAQA3//8AOP/zADv/6AA8//4APf/+AD4AAQBA/+4AQf//AEL/8wBD//4ARP/4AEX//QBH/+wASP/3AEn/7ABK//EASwABABwABv/2ABf/4QAy/8oAM//9ADT/+QA1//4ANv/7ADf//gA4//MAOf/+ADr//wA7/+EAPP/7AD3//gA+//4AP//+AED/7wBB//4AQv/zAEP//gBE//sARf/7AEb//gBH/+8ASP/5AEn/2gBK//oAS//+AB0ABv/nABf/5wAx/7AAMv/hADP/7gA0/7QANf/rADb/5wA3/+4AOP+sADn/6wA6//kAO/+3ADz/6gA9/+8APv/nAD//5wBA/6wAQf/uAEL/rgBD/+cARP+8AEX/3ABG/9oAR//cAEj/0QBJ/9oASv/RAEv/7wAeAAb/9gAX//cAI//9ADH/vwAy/+4AM//5ADT/2gA1//4ANv/3ADf/+wA4/9oAOf/3ADr/+wA7/+cAPP/7AD3/+QA+//cAP//5AED/1ABB//sAQv/cAEP/9wBE/+8ARf/JAEb/6wBH/8QASP++AEn/5wBK/8EAS//+ABwAF//7ADH/7AAy/+QAM//+ADT/7gA1//4ANgAAADf//QA4//cAOf/7ADr//gA7/+4APP/+AD3//gA+//0AP//7AED/7wBB//4AQv/uAEP//gBE//cARf/7AEb/+QBH/+gASP/vAEn/6wBK/+gAS//+AB4ABv/7ABf/8wAa//4AHf/3ACX/9wAq//4AMf/2ADL/5AAz//0ANP/zADX/+wA2//4AN//+ADj/+QA7/+4APf/+AD7/+wA///4AQP/2AEH/+gBC/+4AQ//7AET/+QBF//sARv/+AEf/8wBI/+8ASf/zAEr/6wBL//4AHQAG//EAJP/3ADH/7AAy/7sAM//sADT/4wA1/+8ANv/vADf/9wA4/+QAOf/qADr/9wA7/98APP/vAD3/9wA+/+sAP//uAED/4wBB/+4AQv/mAEP/7wBE/+IARf/VAEb/7gBH/8MASP/GAEn/uwBK/7oAS//fABwABv/sACT//gAy/54AM//rADT/6gA1//EANv/rADf/9wA4/+MAOf/oADr/9wA7/64APP/sAD3/8QA+/+wAP//sAED/4QBB//MAQv/oAEP/5ABE/9gARf/kAEb/7gBH/9EASP/QAEn/uwBK/8QAS//zADAAF//3ABj//wAZ/+kAGv//ABv//QAc//4AHf/pAB7/+wAf//8AIP/iACH//gAi//8AI//+ACT//wAl/+IAJ//uACj//gAp/+cAKv/hACv/+QAs/8MALf/QAC7/5AAv/8wAMP//ADL/4QAz//4ANP/jADX/9wA3//kAOP/fADn/9wA7/+IAPP/5AD3/+gA+//EAP//6AED/2gBB/+8AQv/aAET/7wBF/9cARv/qAEf/xgBI/7sASf/qAEr/tABL//sAHQAG/+cAF//oACT/+gAy/+IAM//xADT/zAA1/+8ANv/sADf/+gA4/8wAOf/3ADr/8wA7/8kAPP/uAD3/7wA+/+wAP//rAED/yQBB//cAQv/MAEP/+ABE/9QARf/KAEb/2gBH/8EASP/EAEn/4gBK/7cAS//vAB0ABv/xABv/+QAl/+4AMv+8ADP/7wA0/9wANf/zADb/6AA3//cAOP/hADn/5gA6//MAO//aADz/6QA9//MAPv/pAD//6wBA/+MAQf/3AEL/2gBD/+kARP/rAEX/1ABG/+kAR//JAEj/zABJ/7QASv+7AEv/5wAbAAb/9gAy/6YAM//9ADT/0wA1//oANv/+ADf//QA4/9UAOf/3ADr//wA7/7kAPP/6AD3//gA+//sAP//7AED/0ABB//oAQv/XAEP/+QBE/+IARf/zAEb/9wBH/+8ASP/vAEn/6gBK/+cAS//6ABwABv/7ACQAAgAy/9UAM//7ADT/7wA1//cANv/9ADf//wA4/+4AOf/7ADr//wA7/+sAPP/+AD3//gA+//0AP//6AED/7gBB//sAQv/sAEP/+wBE/+8ARf/7AEb//QBH/+8ASP/qAEn/3wBK//gAS//+ABwABv/nABf/lQAy/4IAM//3ADT/wQA1/+kANv/nADf/+gA4/8QAOf/oADr/6wA7/5UAPP/uAD3/+wA+//cAP//vAED/wQBB/+8AQv/DAEP/5wBE/84ARf/uAEb/7gBH/+kASP/pAEn/zgBK/+4AS//7ADMABv/sABf/owAY//kAGf/XABr//gAb//4AHP/5AB3/0AAe//gAIP+tACH/8wAi//4AJP/+ACX/0AAm//kAJ//MACj//gAp/9oAKv/+ACv//gAs/+MALf/zAC7/3AAv//cAMP/7ADL/jwAz/+oANP/CADX/7wA2/+oAN//3ADj/xgA5/+sAOv/6ADv/qgA8/+sAPf/7AD7/7wA//+8AQP++AEH/7gBC/8MAQ//qAET/1QBF/+sARv/pAEf/6ABI/+cASf/iAEr/2gBL/+4AHAAG/+cAF//hADL/1AAz/+sANP+wADX/6wA2/+QAN//jADj/qgA5/+cAOv/jADv/ugA8/+cAPf/vAD7/2gA//+kAQP+uAEH/7wBC/64AQ//kAET/uwBF/9oARv/aAEf/zABI/84ASf/TAEr/zQBL/+sAHwAG/+IAF/+lACP//gAk//sAL//uADL/hwAz/+8ANP+sADX/+AA2/9wAN//6ADj/uQA5/+4AOv/vADv/hAA8/+gAPf/pAD7/5wA//+YAQP+wAEH/6QBC/7oAQ//vAET/zgBF/+gARv/oAEf/2gBI/+YASf/QAEr/4gBL/+kAHAAG//sAF//+ADL/5wAz//sANP/kADX/+wA2//8AN//7ADj/4QA5//4AOv//ADv/6wA8//sAPf/+AD7//gA///sAQP/hAEH/+wBC/9oAQ//+AET/7wBF//sARv/6AEf/6QBI//kASf/rAEr/6QBL//sAMAAG/+wAB//YAAj/3QAJ/9MACv+/AAv/yQAM/+IADf/YAA7/7AAP/9MAEP/JABH/5wAS/+IAE//OABT/4gAV/+wAFv/nACD/WwAh/+wAIv/xACP/8QAk//YAJf/xADL/oQAz/+wANP/nADX/7AA2//sAN//2ADj/9gA5//sAO/+PADz/7AA9//YAPv/sAD//8QBA/+IAQf/nAEL/7ABD/+IARP/JAEX/zgBG/+cAR/+/AEj/xABJ/5IASv+/AEv/4gArAAb/9gAI/8QACf+cAAr/zAAL/5QADP+6AA3/xAAO/+oAD//BABD/zgAR/78AEv+7ABP/2AAU/78AFf+mABcAAgAk/+cAMf+mADL/2AAz/+cANP+7ADX/5gA2//MAN//zADj/sQA5/+oAOv/rADz/6AA9/+gAPv/mAD//5wBA/7oAQf/4AEL/twBD/+gARP/OAEX/sQBG/88AR/+EAEj/lwBJ/9AASv+NAEv/9wAsAAb/9gAH/+oACP/nAAn/xAAK/+gAC//TAAz/3QAN/9gADv/lAA//5wAQ/+IAEf/aABL/3AAT/9MAFP/bABX/xAAk//EAMf/YADL/zQAz/+wANP/kADX/9wA2//MAN//9ADj/4wA5//cAOv/3ADv/5gA8//4APf/9AD7/7gA//+4AQP/kAEH/+QBC/+YAQ//vAET/6QBF/9oARv/vAEf/zgBI/88ASf/QAEr/uQBL//kAKwAG//YAB//qAAj/7AAJ/9gACv/uAAv/4gAM/+IADf/dAA7/9AAP/+IAEP/eABH/5gAS/+IAE//TABT/3QAV/90AJP/2ADH/7AAy/74AM//uADT/3wA1//oANv/xADj/5wA5/+8AOv/5ADv/2AA8/+0APf/9AD7/8wA///EAQP/rAEH/+ABC/+QAQ//3AET/5gBF/9AARv/zAEf/xgBI/80ASf++AEr/twBL/+gAKgAH//EACP/xAAn/0wAK/+YAC//YAAz/5wAN/9gADv/oAA//5wAQ/+IAEf/iABP/2AAU/90AFf/dACT/+wAx/+wAMv+7ADP/9wA0/+QANf/rADb/5wA3//EAOP/kADn/+QA6//YAO//aADz/9wA9//4APv/uAD//8QBA/+cAQf/vAEL/4wBD/+sARP/cAEX/0ABG/+sAR//CAEj/xABJ/7QASv+6AEv/6AAmAAf/9gAI//EACf/sAAr/9gAM/+cADv/6AA//8QAQ//EAEf/vABL/4QAT//EAFP/iABX/5wAy/+kAM//9ADT/5wA1//sANv/9ADf//gA4/+sAOf/+ADoAAQA7/+gAPP/9AD3/9wA+//0AP//9AED/6wBBAAEAQv/pAEP/+QBE/+wARgACAEf/6QBI/+8ASf/nAEr/6wBL//sAKQAH//sACP/xAAn/5wAK/+4AC//2AAz/4gAN//sADv/1AA//8QAQ/90AEf/kABL/4gAT/+wAFP/YABX/3QAx//YAMv+5ADP/+AA0/+MANf/3ADb/+AA3//kAOP/iADn/+gA6//0AO//OADz//QA9//4APv/5AD///ABA/+YAQv/jAEP/9wBE/+YARf/vAEb//gBH/+cASP/vAEn/0QBK/+YAS//9ACgAB//2AAj/4gAJ/90ACv/sAAv/4gAM/+gADf/iAA7/9QAP/+gAEP/dABH/4AAS/+YAE//OABT/4gAV/90AJP/7ADH/9gAy/8EAM//vADT/3wA2//QAN//4ADj/4wA5/+kAOv/6ADv/0QA8/+YAPf/zAD7/6QA///EAQP/qAEL/3ABD/+gARP/fAEb/+ABH/7sASP+7AEn/rwBK/68AS//jACcACP/xAAn/7AAK//gADP/2AA7/9wAP//YAEP/xABH/5wAS/+cAE//xABT/7AAV/+UAMf/2ADL/6AAz//kANP/qADX/+wA2//oAN//7ADj/6wA5//cAOv//ADv/4wA8//sAPf/+AD7/+wA///oAQP/sAEH/+gBC/+MAQ//5AET/7wBF/+oARv/7AEf/4wBI/+wASf/jAEr/6gBL//4AJgAH//sACP/7AAn/5wAK//oADP/2AA7/9gAP//YAEP/xABH/8QAS//IAE//xABT/5wAV//EAMv/nADP/+wA0//EANf/9ADb//gA3//4AOP/uADn/+wA6//4AO//oAD0AAAA+//sAP//+AED/7wBB//4AQv/qAEP//wBE//EARf/3AEb/+wBH/+YASP/3AEn/2gBK/+QAS//7ACkAB//2AAj/9gAJ/90ACv/yAAz/8QAO//EAD//wABD/6gAR/+wAEv/mABP/9AAU/+wAFf/rABf/zgAx//YAMv/OADP/7wA0/+oANf/5ADb//gA3//0AOP/oADn/+QA6//0AO//YADz//gA9//8APv/6AD//+QBA/+4AQf/5AEL/4wBD//gARP/qAEX/+QBG//oAR//pAEj/6QBJ/9UASv/rAEv/+gAqAAf/sgAI/8kACf+wAAr/ugAL/7UADP+1AA3/3QAO/+QAD/+6ABD/sgAR/7UAEv+xABP/4gAU/6sAFf+mADH/lwAy/9oAM//jADT/qwA1/+IANv/iADf/4wA4/5oAOf/XADr/7gA7/7QAPP/kAD3/6wA+/+4AP//mAED/rQBB/+8AQv+qAEP/6gBE/74ARf/XAEb/2gBH/9AASP/SAEn/1QBK/80AS//qACsAB//nAAj/8QAJ/6YACv/sAAv/nAAM/90ADf+6AA7/9gAP/+IAEP/sABH/3QAS/9oAE//sABT/3QAV/8QAJP/+ADH/pgAy/+sAM//vADT/ygA1//0ANv/zADf/+wA4/9MAOf/vADr/+wA7/9gAPP/3AD3/9wA+//EAP//7AED/1QBB//cAQv/PAEP/8wBE/+YARf+7AEb/5wBH/7UASP/JAEn/2gBK/6UAS//zACkAB//2AAn/7AAK//kAC//sAAz/9gAO//oAD//2ABD/7AAR/+cAEv/vABP/9gAU//EAFf/sABcAAQAx/+YAMv/pADP/+QA0/+oANf/zADb/+wA3//oAOP/nADn/9wA6//4AO//uADz/+QA9//oAPv/7AD//+QBA/+8AQf/3AEL/6QBD//oARP/sAEX/8wBG//gAR//pAEj/6QBJ/+MASv/nAEv//QAqAAf/9gAI//sACf/sAAr/9wAL/+wADP/7AA7/+gAP//EAEP/2ABH/7AAS//EAE//2ABT/9gAV/+QAFwABADH/8QAy/+kAM//3ADT/6QA1//kANv/5ADf/+QA4/+8AOf/6ADr//gA7/+8APP/7AD3/+gA+//oAP//4AED/7wBB//sAQv/rAEP//QBE/+8ARf/3AEb/+gBH/+4ASP/rAEn/4QBK/+wAS//5ACsAB//xAAj/4gAJ/9gACv/sAAv/2AAM//YADf/iAA7/8QAP/90AEP/iABH/0wAS/+IAE//JABT/4gAV/94AJP/7ADH/3QAy/7QAM//pADT/4QA1/+wANv/vADf/6gA4/+IAOf/qADr/+gA7/9oAPP/pAD3/6wA+/+wAP//pAED/4QBB/+sAQv/cAEP/6wBE/+IARf/JAEb/7gBH/7wASP/BAEn/pgBK/7UAS//kACwAB//iAAj/5wAJ/+IACv/OAAv/2AAM/+cADf/nAA7/8AAP/90AEP+6ABH/xAAS/9cAE//XABT/2AAV/9gAG//3ACT/+wAx/+IAMv+gADP/6QA0/+MANf/mADb/7wA3/+sAOP/aADn/6AA6//YAO/+xADz/6wA9/+4APv/oAD//7wBA/9oAQf/oAEL/1wBD/+MARP/aAEX/2ABG/+cAR//PAEj/yQBJ/7kASv/BAEv/6AApAAf/8QAI/+wACf/OAAr/6gAL/84ADP/nAA3/2AAO//YAD//fABD/4gAR/9gAEv/lABP/5wAU/+IAFf/YADH/4gAy/+cAM//3ADT/2gA1//gANv/5ADf/+wA4/9wAOf/3ADr//gA7/+MAPP/3AD3//QA+//cAP//3AED/1QBC/9UAQ//9AET/6QBF/+EARv/pAEf/ugBI/8QASf/aAEr/wgBL//sAKwAH/8kACP/YAAn/xAAK/9MAC/+/AAz/yQAN/9gADv/nAA//xAAQ/7oAEf+1ABL/wQAT/9gAFP+6ABX/vwAk//sAMf+/ADL/2gAz/+gANP/KADX/6QA2/+kAN//oADj/xgA5/+QAOv/nADv/uQA8/+wAPf/uAD7/6QA//+cAQP/GAEH/7ABC/8kAQ//mAET/2ABF/84ARv/VAEf/wQBI/7wASf/GAEr/tABL/+8AKwAH//EACP/2AAn/yQAK/+oAC//TAAz/3QAN/+cADv/sAA//4gAQ/+IAEf/YABL/3wAT/90AFP/dABX/2AAk//sAMf/nADL/xgAz//MANP/iADX/7wA2/+4AN//3ADj/4wA5/+kAOv/vADv/1wA8/+4APf/zAD7/6gA//+0AQP/kAEH/9wBC/98AQ//qAET/5wBF/9AARv/vAEf/yQBI/9AASf/PAEr/xABL/+8AKQAH/+cACP/sAAn/5wAK/+kAC//dAAz/2AAO/+wAD//XABD/qwAR/8kAEv/AABP/9gAU/9MAFf/OADH/2AAy/7AAM//5ADT/2gA1//0ANv/6ADf//gA4/98AOf/3ADr//QA7/8YAPP/7AD3//gA+//gAP//4AED/1QBB//0AQv/VAEP/+ABE/+MARf/zAEb/+QBH/+4ASP/zAEn/4gBK/+cAS//zACkACP/2AAn/5wAK//QAC//sAAz/+wAN//4ADv/2AA//5QAQ/+wAEf/nABL/8wAT//EAFP/nABX/3QAx/+QAMv/KADP/+QA0/+wANf/6ADb/+gA3//sAOP/vADn/+gA6AAAAO//hADz//wA9//0APv/5AD///gBA/+wAQf/7AEL/7ABD//sARP/vAEX/9wBG//sAR//zAEj/6gBJ/+EASv/jAEv/+wArAAf/zgAI/84ACf/YAAr/ygAL/9gADP/JAA3/+wAO/9kAD//JABD/ogAR/7oAEv+5ABP/5wAU/8QAFf+9ACT/+wAx/7oAMv+FADP/+wA0/7sANf/qADb/6wA3/+wAOP++ADn/5gA6/+8AO/+iADz/6AA9/+oAPv/sAD//7wBA/8MAQf/mAEL/uwBD/+YARP/KAEX/6QBG/+8AR//jAEj/3wBJ/9MASv/hAEv/6wApAAf/zgAI/84ACf/TAAv/2AAM/84ADv/eAA//xAAQ/7AAEf/TABL/sQAT/+wAFP/FABX/yQAk//sAMf/JADL/lQAz//MANP/BADX/+QA2//MAN//3ADj/xgA5//sAOv/3ADv/pQA8/+8APf/+AD7/7gA//+oAQP/DAEH/7gBC/8QAQ//vAET/0ABF/+4ARv/uAEf/6QBI/+QASf/aAEr/5gBL//cAKgAH/8QACP/OAAn/pgAL/7oADP+rAA3/3QAO/+cAD/+5ABD/twAR/8QAEv+zABP/0wAU/7AAFf+cACT/+wAx/6EAMv/aADP/4wA0/7cANf/4ADb/4wA3//0AOP+3ADn/7gA6/+8AO/+7ADz/7gA9//EAPv/jAD//6ABA/7oAQf/zAEL/uQBD/+sARP/OAEX/3wBG/+EAR//aAEj/2ABJ/9gASv/MAEv/7gAsAAf/yQAI/84ACf/JAAr/wgAL/8kADP/JAA3//gAO/8kAD/+6ABD/jQAR/7oAEv+gABP/4gAU/7UAFf+6AB7/8QAk//sAMf+1ADL/lwAz/+8ANP+7ADX/5gA2/+4AN//uADj/uQA5/+gAOv/3ADv/hAA8/+8APf/sAD7/7AA//+oAQP+6AEH/7ABC/7kAQ//pAET/ygBF/+8ARv/vAEf/6ABI/+kASf/fAEr/5ABL//EAJgAH//YACf/iAAr/7AAL/+cADP/iAA3//wAO//UAD//nABD/7AAR/+IAEv/gABP/7AAU/90AFf/TADH/4gAy/+sAM//+ADT/6AA1//4ANgAEADf//wA4/9wAOf/6ADv/5gA8//8APf//AD///QBA/+MAQf//AEMAAABE/+8ARf/4AEb/+wBH//cASP/rAEn/6QBK/+kAS//9AAIAAQAGAEsAAAAAAAAAAQAAAADUGBYRAAAAANmXsTQAAAAA2ZexNA==",nt=n=>vi("http://www.w3.org/2000/svg",n),Ls=(n,t)=>{const e=nt("rect");return e.setAttribute("height",`${n}`),e.setAttribute("width",`${t}`),e},Vs=(n,t,e,a)=>{const r=Ce("filter");r.setAttribute("id",a),r.setAttribute("height","200%"),r.setAttribute("width","200%"),r.setAttribute("x","-50%"),r.setAttribute("y","-50%");const i=Ce("feOffset");r.appendChild(i),i.setAttribute("result","offOut"),i.setAttribute("in","SourceAlpha"),i.setAttribute("dx",`${n}`),i.setAttribute("dy",`${t}`);const o=Ce("feGaussianBlur");r.appendChild(o),o.setAttribute("result","blurOut"),o.setAttribute("in","offOut"),o.setAttribute("stdDeviation",`${e}`);const s=Ce("feBlend");return r.appendChild(s),s.setAttribute("in","SourceGraphic"),s.setAttribute("in2","blurOut"),s.setAttribute("mode","normal"),r},zs=n=>{let t=n;return t=t.replace(/feoffset/gi,"feOffset"),t=t.replace(/fegaussianblur/gi,"feGaussianBlur"),t=t.replace(/feblend/gi,"feBlend"),t=t.replace(/lineargradient/gi,"linearGradient"),t=t.replace(/stddeviation/gi,"stdDeviation"),t};function qs(n,t,e,a,r,i){const o=r,s=i,l={x:t[0],y:t[1],width:t[2]-t[0],height:t[3]-t[1]};if(l.width<=0)return;const c=Gs(l.height,l.width,e*o,a*s),d=(a-c*l.width)/2-c*l.x,A=(e-c*l.height)/2-c*l.y;n.setAttribute("transform",`translate(${d} ${A}) scale(${c} ${c})`)}function Gs(n,t,e,a){const r=e/n,i=a/t;return r>1&&i>1?Math.min(r,i):r>1&&i<1?i:r<1&&i>1?r:Math.min(r,i)}const un={m:["x","y"],z:[],l:["x","y"],h:["x"],v:["y"],c:["x1","y1","x2","y2","x","y"],s:["x2","y2","x","y"],q:["x1","y1","x","y"],t:["x","y"],a:["rx","ry","xRotation","largeArc","sweep","x","y"]};class Ws{constructor(t){const e=Array.from(t.querySelectorAll("path"));this.paths=e.map(a=>{const r=a.getAttribute("d")||"",i=this.parsePath(r);return{pathElement:a,pathData:i}})}transform(t){for(const e of this.paths)e.pathData=this.runTransformer(e.pathData,t);this.update()}encodePath(t){let e="";const r=i=>{const o=[],s=i.relative?i.type:i.type.toUpperCase();let l=e!==s;const c=un[i.type];l&&(o.push(s),e=s);for(const d of c){const A=i[d];let u;switch(typeof A){case"boolean":u=A|0;break;case"number":u=(A*100|0)/100;break;default:throw new bt("Failed to encode path.")}l||o.push(" "),o.push(u),l=!1}return o.join("")};return t.map(r).join("")}parsePath(t){const e=/([mzlhvcsqta])([^mzlhvcsqta]*)/gi,a=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi,r=[];let i;for(e.lastIndex=0;i=e.exec(t);){const o=i[1].toLowerCase(),s=(i[2].match(a)||[]).map(parseFloat),l=o===i[1],c=un[o];if(s.length<c.length)throw new bt(`Path type "${o}" given ${s.length} arguments, expected ${c.length}.`);if(c.length>0){if(s.length%c.length!==0)throw new bt(`Path type "${o}" given ${s.length} arguments, not divisible by ${c.length}`);for(let d=0;d<s.length/c.length;d++){const A={type:o,relative:l};for(let u=0;u<c.length;u++)A[c[u]]=s[d*c.length+u];r.push(A)}}else r.push({type:o,relative:l})}return r}runTransformer(t,e){const a=[["x1","y1"],["x2","y2"],["x","y"]],r=i=>{for(let o=0;o<a.length;o++){const[s,l]=a[o];if(s in i&&l in i){const c=[i[s],i[l]],d=e(c);if(d.length<2)throw new bt("Transformer must return at least 2 points.");i[s]=d[0],i[l]=d[1]}}return i};return this.transformPath(t,r)}transformPath(t,e){const a=[];for(let r=0;r<t.length;r++){const i=JSON.parse(JSON.stringify(t[r])),o=e(i);Array.isArray(o)?a.push(...o):o&&a.push(o)}return a}update(){for(const{pathElement:t,pathData:e}of this.paths){const a=this.encodePath(e);t.setAttribute("d",a)}}}class js extends $s{constructor(){super(...arguments),this.moduleName="Vegemite"}svgPreview(t,e){return this.svgElement(t,e)}svgPrint(t,e){return this.svgElement(t,e)}svgElement(t,e){const a=as(Us),i=t!==""?(b=>b.charAt(0).toUpperCase()+b.substr(1).toLowerCase())(t):"",o=a.getPath(i,0,72,72),s=o.toSVG(2),l=o.getBoundingBox(),c=l.x2-l.x1,d=o.toPathData(3),A=()=>{const b=nt("g");b.classList.add("module-text-group");const P=nt("defs");b.appendChild(P),P.appendChild(Vs(0,2,2,"shadow"));const C=nt("path");C.setAttribute("d",d),C.setAttribute("stroke","black"),C.setAttribute("stroke-width","3"),P.appendChild(C);const E=nt("g");E.classList.add("module-layer0"),b.appendChild(E),E.setAttribute("filter","url(#shadow)"),E.innerHTML=C.outerHTML;const x=nt("g");x.classList.add("module-layer1"),b.appendChild(x),x.setAttribute("stroke-width","3"),x.setAttribute("stroke","rgb(45,41,38)"),x.setAttribute("fill","rgb(45,41,38)"),x.setAttribute("transform","translate(0.5,0)"),x.innerHTML=s;const B=nt("g");B.classList.add("module-layer2"),b.appendChild(B),B.setAttribute("fill","rgb(255,209,0)"),B.setAttribute("transform","translate(1,-0.1)"),B.innerHTML=s;const D=nt("g");return D.classList.add("module-layer3"),b.appendChild(D),D.setAttribute("fill","white"),D.innerHTML=s,new Ws(b).transform(([T,et])=>[T,et+(c/2-T)**2/(c*6)]),b},u=nt("g");u.classList.add("module-root");const h=nt("defs");u.appendChild(h);const g=nt("g");g.classList.add("module-bounds"),u.appendChild(g);const m=Ls(e.height,e.width);m.setAttribute("opacity","0"),g.appendChild(m);const p=nt("g");p.classList.add("module-text-enclosure"),u.appendChild(p);const f=A();p.appendChild(f);const S=ci(d);return qs(p,S,e.height,e.width,.35,.65),zs(u.outerHTML)}}async function fr(n){if(n==="Vegemite")return new js;throw new L(`Failed to resolve Module, Module ${n} not found`)}const ge=w.gql`
1501
+ `,m={};m[this.shapeFillId]={browserValue:g};const f=M();return{id:f,region:u,command:new z({stepRegion:u,stepName:t.stepName,colors:m,id:f,svg:p,type:x.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,excludeFromExport:t.data.excludeFromPrint},h)}},c=t.data.regions.map(l),d=c.filter(u=>!!u).map(u=>u?.command),A=c.filter(u=>!!u).map(u=>({id:u.id,region:u.region}));return{command:new Q(d),followup:async()=>{await r.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],A,async()=>{r.updateStorage(t.stepName,{colour:s()})})}}}}}const kt=new Qs;class Rs{constructor(){this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(t){t({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(t)}removeToastCallback(t){this.toastCallbacks=this.toastCallbacks.filter(e=>e!==t)}setLatestToast(t,e){this.latestToast=t,this.toastType=e,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach(t=>t({toastMessage:this.latestToast,toastType:this.toastType}))}}const fr=new Rs,na=(n,t,e,a,r)=>{if(t.some(d=>d==null))throw new Error(`Failed to autosize lines: ${t.join(", ")}`);let i=t.map(d=>d.split(`
1502
+ `)).flat(),o=i.length,s=i.map(d=>mt(d,a,r));const l=r.getApproximateHeight()*a;let c=!0;for(;c;){if(l+(o-1)*e>n.height)return[null,null];const A=Math.max(...s);if(A<=n.width)return[i,A];const u=s.reduce((m,f,v,b)=>f>b[m]?v:m,0),h=i[u];let g=!1,p=h.length;for(;!g&&p>-1;){p=h.lastIndexOf(" ",p-1);const m=[h.slice(0,p),h.slice(p+1)],f=m.map(b=>mt(b,a,r));f[0]<=n.width&&(i=[...i.slice(0,u),...m,...i.slice(u+1)],s=[...s.slice(0,u),...f,...s.slice(u+1)],o+=1,g=!0)}g||(c=!1)}return[null,null]},Kt=(n,t,e,a,r)=>{let i,o;const s=wt(t.assetUrl),l=s.getFont();if(r.size){const u=n/l.unitsPerEm;return[i,o]=na(e,a,n,u,s),[r.size,i,o]}const c=6;let d=c-Xe;if(a.length>0){let u=a,h=0;for(;(!r.maxSize||d<=r.maxSize)&&u;)d+=Xe,h=d/l.unitsPerEm,[u,o]=na(e,a,d,h,s)}d>c&&(d-=Xe),r.minSize&&d<r.minSize&&(d=r.minSize);const A=d/l.unitsPerEm;return[i,o]=na(e,a,d,A,s),[d,i,o]},ra=30;class Te extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Te.name}}const Os=["‘","’","“","”",`
1503
+ `];class Ne extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ne.name}}class $s{constructor(){this.cachedColors=new Map,this.cachedStrokeColors=new Map,this.filterUnsupportedCharacters=(t,e)=>{let a=t.replace(/(\r\n|\r|(\u2665|\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const r=[],i=e?wt(e.assetUrl):void 0;if(i){const o=a.split("").filter(l=>!Os.includes(l)).join(""),s=o.split("").map(l=>i.getFont().charToGlyph(l));for(let l=0;l<s.length;l++)s[l].name===".notdef"&&r.push(String.fromCharCode(o.charCodeAt(l)))}for(let o=0;o<r.length;o++)a=a.replaceAll(r[o],"");return a},this.textAlign=t=>t.vertical?"center":t.textAlign||"center",this.getErrorsForText=(t,e,a,r)=>{let i;a.data&&a.data.maxLength&&e.length>a.data.maxLength&&(i||(i={}),i.hitCharacterLimit=!0);const o=r.getProfanities(),s=ca.split(t.toLowerCase());for(const c of s)for(const d in o){const A=o[d].toLowerCase().replace(/\s/g,"");if(c===A){i||(i={}),i.blockedProfanity=!0;break}}return!a.data.allowNewlines&&(t.includes(`
1504
+ `)||t.includes("\r"))&&(i||(i={}),i.illegalMultipleLines=!0),i}}async init(t,e,a){const r=t.option;if(!r)return null;if(a)await this.reload(t,e,a);else{const i=this.getDefaultImageFillVariant(t.data),o=i?.asset?.fileLink,s=o?await fa(o):void 0,l=s?{src:s.src,height:s.height,width:s.width,scale:t.data.imageFillScale||1}:void 0,c=this.getDefaultStrokeColorVariant(t.data),d=t.data.strokeEnabled&&c?.color?{browserValue:c.color,pmsValue:c.name}:void 0;let A=t.data.defaultText||"";const u=e.getWorkflowExperience().getBundle();if(u&&t.globalPropertyAspectConfigurations){const p=u.getGlobalPropertyConfiguration()?.aspects?.find(m=>m.type===$.Text&&t.globalPropertyAspectConfigurations?.map(f=>f.aspectName).includes(m.name));if(p){const f=u.getGlobalPropertyStateManager().getAspect(p.name);f&&(A=f)}}e.updateStorage(t.stepName,{text:A,inputText:t.data.defaultText||"",color:this.getDefaultColorVariant(t.data)?.color||this.getDefaultColor(t.data),fillImage:l,strokeColor:d}),e.updateMetadata(t.stepName,{text:A,color:this.getDefaultColorVariant(t.data)?.name||this.getDefaultColor(t.data),fillImage:i?.name,strokeColor:t.data.strokeEnabled?c?.color:void 0});const h=j.getDefaultVariant(r);if(h)return this.selectVariantCommand(t,h,{text:A},[],e,()=>{},()=>{},l,d)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map(i=>O(i.id,t.getAllLayoutData()))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const a=t.data.colorOption;if(a){const r=a.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i}))||[];return this.cachedColors.set(t.stepName,r),r}return[]}changeAlignment(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher();for(const o of a){const s=new hr(o.id,e);i(s)}}async changeFillColor(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher();e.variant?r.updateMetadata(t.stepName,{color:e.variant.name}):r.updateMetadata(t.stepName,{color:e.fill});const o=t.data.colorOption,s=o?this.createTextFillSpotColor(o,e.variant):void 0;o?r.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:o.colorProfile?.key}):r.updateStorage(t.stepName,{color:e.fill});for(const l of a){if(!e.fill)throw new Error("Fill not set on new color selection!");const c=new Ar(l.id,e.fill,s);i(c)}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const a=e.variants?.map(r=>r.asset?.fileLink)?.filter(r=>!!r)||[];return Promise.all(a.map(async r=>{const i=await fa(r);return{src:r,width:i.width,height:i.height,scale:t.data.imageFillScale||1}}))}return Promise.resolve([])}async changeFillImage(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher(),o=t.option?.variants?.find(s=>s.asset?.fileLink===e.src);r.updateMetadata(t.stepName,{fillImage:o?.name}),r.updateStorage(t.stepName,{fillImage:e});for(const s of a){const l=new ea(s.id,e);i(l)}}availableStrokeColors(t){const e=this.cachedStrokeColors.get(t.stepName);if(e)return e;const a=t.data.strokeOption;if(a){const r=a.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i}))||[];return this.cachedStrokeColors.set(t.stepName,r),r}return[]}async changeStrokeColor(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher();e?.variant?r.updateMetadata(t.stepName,{strokeColor:e.variant.name}):r.updateMetadata(t.stepName,{strokeColor:e?.fill});const o=e?{browserValue:e.fill,pmsValue:e.pmsValue}:void 0;r.updateStorage(t.stepName,{strokeColor:o});for(const s of a){const l=new aa(s.id,o,t.data?.strokeThickness);i(l)}}getProcessedInput(t,e,a){const r=a?t:this.injectReplaceableText(t,e);return ke(r,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,a,r){const i=r.getStepStorage(a.stepName),o=Mt(t,r),s=this.getProcessedInput(o,a.data,i?.customiseAllText??!1),l={command:void 0,helperData:{},errorData:this.getErrorsForText(t,s,a,r)};if(l.errorData)return l;l.helperData.charactersRemaining=a.data.maxLength-s.length;const c=[],d=new Map,A=new Map;for(const u of e){if(!u.fontData)throw new U("Failed to resolve font data for text.");const[h,g]=Kt(u.fontSize,u.fontData,{left:u.x,top:u.y,width:u.width,height:u.height,rotation:u.rotation},[s],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});d.set(u.id,h),A.set(u.id,g);const p=a.data.curved?s:(g||[]).join(`
1505
+ `);c.push(this.generateTextChangeCommandsForRegion(h,a.data,u.id,p))}return!a.data.curved&&e.length>0&&!Array.from(A.values()).every(h=>h)?(l.errorData||(l.errorData={}),l.errorData.doesNotFit=!0,l):(r.updateStorage(a.stepName,{text:t}),r.updateMetadata(a.stepName,{text:s}),(i?.defaultCleared||!a.data.deleteDefaultOnFocus)&&s.trim()!==""&&r.setMandatoryFulfilled(a.stepName,!0),l.command=new Q(c),l)}async selectVariant(t,e,a,r,i){const o=await this.selectVariantCommand(t,e,a.getStepStorage(t.stepName)||{},a.getRegionElements(t.stepName),a,r,i);o&&(o.command&&a.getCommandDispatcher()(o.command),o.followup&&await o.followup())}createTextFillSpotColor(t,e){const a=t.colorProfile;if(a){const r=(a.name||"").replace(/\s/g,"-"),i=r.lastIndexOf("/"),s=r.slice(i+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:s,namedColor:e.namedColor}}}async reload(t,e,a){const r=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(r?.selectedVariants){const c=r.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(A=>A.id===c);if(d){const A=await this.fontDataFromVariant(d),u=s.map(m=>({id:m.id,region:m.stepRegion})),h=r.storage?.color;let g=r.storage?.text;const p=e.getWorkflowExperience().getBundle();if(p&&t.globalPropertyAspectConfigurations){const f=p.getGlobalPropertyConfiguration()?.aspects?.find(v=>v.type===$.Text&&t.globalPropertyAspectConfigurations?.map(b=>b.aspectName).includes(v.name));if(f){const b=p.getGlobalPropertyStateManager().getAspect(f.name);b&&(g=b)}}if(await e.setSelectionsAndElements(t.stepName,[d],u,async()=>{e.updateMetadata(t.stepName,{color:h,text:g}),e.updateStorage(t.stepName,{text:g,inputText:g});const m=s.map(v=>new wa(v.id,A)),f=new Q(m);e.getCommandDispatcher()(f)}),s.length===0&&l){const m=j.getDefaultVariant(l);if(m){const f=await this.selectVariantCommand(t,m,{text:g},[],e,()=>{},()=>{});e.getCommandDispatcher()(f.command)}}else{const{command:m}=G.updateInputText(g||"",s,t,e);m&&e.getCommandDispatcher()(m)}}}}else{const c=e.getWorkflowExperience().getBundle();if(c&&t.globalPropertyAspectConfigurations){const A=c.getGlobalPropertyConfiguration()?.aspects?.find(u=>u.type===$.Text&&t.globalPropertyAspectConfigurations?.map(h=>h.aspectName).includes(u.name));if(A){const h=c.getGlobalPropertyStateManager().getAspect(A.name);if(h)if(s.length===0&&l){const g=j.getDefaultVariant(l);if(g){const p=await this.selectVariantCommand(t,g,{text:h},[],e,()=>{},()=>{});e.getCommandDispatcher()(p.command)}}else{const{command:g}=G.updateInputText(h,s,t,e);g&&e.getCommandDispatcher()(g)}}}}}getDefaultColorVariant(t){const e=t.colorOption;if(e)return j.getDefaultVariant(e)}getDefaultColor(t){const e=t.colorOption;return e?j.getDefaultVariant(e)?.color:void 0}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return j.getDefaultVariant(e)}getDefaultStrokeColorVariant(t){const e=t.strokeOption;if(e)return j.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new pt(t);const a=e.fileLink;if(!a)throw new Qt(e);const r=await Dt(a);return{assetUrl:a,name:r.names.fullName.en}}async selectVariantCommand(t,e,a,r,i,o,s,l,c){const d=i.markUpdatePending(),A=await this.fontDataFromVariant(e);if(r.length>0){const u=r.map(p=>new wa(p.id,A));if(l){const p=r.map(m=>new ea(m.id,l));u.push(...p)}if(c){const p=r.map(m=>new aa(m.id,c,t.data.strokeThickness));u.push(...p)}const h=await this.changeInputTextWithRegion(t,t.data.size||ra,A,a.text||"",a,i,a?.customiseAllText??!1,o,s);return h&&u.push(h),{command:new Q(u),followup:async()=>{i.markUpdateCompleted(d),await i.setSelectionsAndElements(t.stepName,[e],r)}}}else{const u=await this.createTextboxRegions(t.stepName,e,t.data,A,a,i),h=await this.changeInputTextWithRegion(t,t.data.size||ra,A,u[0]?.newElement.input||a.text||t.data.defaultText||"",a,i,a?.customiseAllText??!1,o,s),g=u.flatMap(m=>m.commands);if(l){const m=u.map(f=>new ea(f.regionElement.id,l));g.push(...m)}if(c){const m=r.map(f=>new aa(f.id,c,t.data.strokeThickness));g.push(...m)}return h&&g.push(h),{command:new Q(g),followup:async()=>{i.markUpdateCompleted(d)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,a,r,i,o){if(!a||!a.regions)throw new Error("Step data not supplied");const s=i.text||a.defaultText||"",l=Mt(s,o),c=this.getProcessedInput(l,a,!1),d=async u=>{const g=o.getLayouts().find(m=>m.panelId===u.panelId),p=M();try{if(!g)throw new Ne("Failed to find layout for region: "+u.panelId);const m=a.colorOption;let f;if(m&&m.variants){const Y=m.variants.find(X=>X.id===m.defaultVariant?.id)||m.variants[0];f=this.createTextFillSpotColor(m,Y),o.updateStorage(t,{colorProfileAssetKey:m.colorProfile?.key})}const v=await this.getDefaultColor(a),b=v||"#000000",D={stepRegion:u,stepName:t,align:this.textAlign(a),fill:i.color?i.color:b,fontSize:a.size||ra,fontData:r,id:p,layer:u.layer,layerIndex:u.layerIndex,rotation:u.rotation,text:c,input:s,type:x.Textbox,vertical:a.vertical,x:u.left,y:u.top,height:u.height,width:u.width,immutable:u.immutable,verticalAlign:a.verticalAlign||"middle",curved:a.curved,paths:a.paths,fillSpotColorDefinition:f},w=[],S=new Map,P=new Map;if(!D.fontData)throw new U("Failed to resolve font data for text.");const[F,B]=Kt(D.fontSize,D.fontData,{left:D.x,top:D.y,width:D.width,height:D.height,rotation:D.rotation,panelId:""},[c],{size:a.size,minSize:a.minSize,maxSize:a.maxSize});S.set(D.id,F),P.set(D.id,B);const T=a.curved||a.vertical?c:(B||[]).join(`
1506
+ `);w.push(this.generateTextChangeCommandsForRegion(F,a,D.id,T));const V=new z(D,g);return{regionElement:{id:p,region:u},commands:[V,...w],newElement:D,fontData:r}}catch(m){throw console.log(m),new Te("Error adding font to region")}},A=await Promise.all(a.regions.map(d)).catch(u=>{throw u instanceof Te?(fr.setLatestToast("Failed to load font.",pe.Error),u):u instanceof Ne?u:new Error(u)});return await o.setSelectionsAndElements(t,[e],A.map(u=>u.regionElement),async()=>{o.updateMetadata(t,{text:s}),o.updateStorage(t,{text:s})}),A}generateTextChangeCommandsForRegion(t,e,a,r){const i=[],o=new gr(a,r);if(i.push(o),!e.size){const l=new ur(a,t);i.push(l)}return new Q(i)}async changeInputTextWithRegion(t,e,a,r,i,o,s,l,c,d){const A=(r||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),u=Mt(A,o),h=this.getProcessedInput(u,t.data,s),g=o.getRegionElements(t.stepName),p=new Map,m=new Map;for(const w of g)if(w.region){const[S,P]=Kt(e,a,w.region,[h],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});p.set(w.id,S),m.set(w.id,P)}const v=(()=>{if(t.data&&t.data.maxLength&&h.length>t.data.maxLength)return d&&d(!0),{info:"0"};const w=o.getProfanities(),S=ca.split(h.toLowerCase());for(const P of S)for(const F in w){const B=w[F].toLowerCase().replace(/\s/g,"");if(P===B)return l(!0),{error:"Blocked profanity."}}return!t.data.vertical&&!t.data.allowNewlines&&(h.includes(`
1507
+ `)||h.includes("\r"))?(l(!0),{error:"Cannot span multiple lines."}):!t.data.curved&&!Array.from(m.values()).every(F=>F)?(l(!0),{error:"Does not fit."}):(l(!1),{info:(t.data.maxLength-h.length).toString()})})();if(v.error){c(v.error);return}if(c(`${v.info} characters remaining`||""),d)return;o.updateStorage(t.stepName,{text:A}),o.updateMetadata(t.stepName,{text:this.injectReplaceableText(A,t.data)}),(i.defaultCleared||!t.data.deleteDefaultOnFocus)&&A.trim()!==""&&o.setMandatoryFulfilled(t.stepName,!0);const b=[];for(const w of g){const S=t.data.curved?h:(m.get(w.id)||[]).join(`
1508
+ `);b.push(this.generateTextChangeCommandsForRegion(p.get(w.id)||1,t.data,w.id,S))}return new Q(b)}}const G=new $s;class Us{}const Ls="data:application/octet-stream;base64,AAEAAAAPAIAAAwBwRkZUTYdHeHoAAElcAAAAHEdERUYAJwBUAAAe2AAAAB5HUE9TkNtcVAAAHygAACoyR1NVQrj/uP4AAB74AAAAME9TLzJoWmUcAAABeAAAAGBjbWFwtkIacAAAAxAAAAJWZ2FzcP//AAMAAB7QAAAACGdseWY27KOUAAAGCAAAFcRoZWFkFPal0gAAAPwAAAA2aGhlYQU0Ar0AAAE0AAAAJGhtdHiADw6qAAAB2AAAAThsb2Nh5CzfJAAABWgAAACebWF4cACVAEwAAAFYAAAAIG5hbWXeIPPyAAAbzAAAAiJwb3N0ABeZTwAAHfAAAADdAAEAAAABAAAZ9vREXw889QALA+gAAAAA2ZexNAAAAADZl7E0ADL/yQJ2ArwAAAAIAAIAAAAAAAAAAQAAArz/wwAAAqsAAAAAAnYAAQAAAAAAAAAAAAAAAAAAAE4AAQAAAE4ASQAFAAAAAAACAAAAAQABAAAAQAAAAAAAAAAEAbsBkAAFAAACigK7AAAAjAKKArsAAAHfADEBAgAAAAAAAAAAAAAAAAAAAAcAAAAAAAAAAAAAAABYWFhYAEAACgCtArz/wwAAAqkANgAAAAMAAAAAAmQCZAAAACAAAgIPADIAAAAAAU0AAAAAAAAAAAAAALQAAAD3ADUCfQA1AcoANQKrADUCDQA1AX4ANQHYADUBNQA1AcgANQHUADUB8AA1AeEANQHpADUBqQA1AdAANQHpADUCqgA1Af8ANQGaADUB3wA1AbgANQFtADUBbQA1AekANQG8ADUA1QA1AYcANQHBADUBUAA1AhsANQHBADUB4QA1AZYANQH0ADUBxQA1AcUAMgGJADUBwwA1Ad0ANQJ1ADUB9wA1AcoANQF6ADUB3AA1Af8ANQGaADUB3wA1AbgANQFtADUBbQA1AekANQG8ADUA1QA1AYcANQHBADUBUAA1AhsANQHBADUB4QA1AZYANQH0ADUBxQA1AcUAMgGJADUBwwA1Ad0ANQJ1ADUB9wA1AcoANQF6ADUAtAAAAAAAAAAAAAMAAAADAAAAHAABAAAAAAFQAAMAAQAAABwABAE0AAAALgAgAAQADgAAAAoADQAhACYAKgA5AFoAXgB6AKAArQDFAM8A1gDdAOUA7wD2AP0A/wF4//8AAAAAAAoADQAgACMAKgAwAEAAXgBhAKAArQDAAMcA0QDYAOAA5wDxAPgA/wF4//8AAf/5//f/5f/k/+H/3P/W/9P/0f+s/6AAAAAAAAAAAAAAAAAAAAAA/0v+twABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABYAIAAwADoARABOAF4AaAAAAAAAAAAXABcAFwAXABcAFwAZABsAGwAbABsAHwAfAB8AHwAkACUAJQAlACUAJQAlACsAKwArACsALwAyADIAMgAyADIAMgA0ADYANgA2ADYAOgA6ADoAOgA/AEAAQABAAEAAQABAAEYARgBGAEYASgAAAQYAAAEAAAAAAAAAAQIDAAAEAAAAAAAAAAAAAAAAAAAAAQAABQYABwgJCgAAAAsAAAAAAAwNDg8QERITFBUAAAAAAAAWFxgZGhscHR4fICEiIyQlJicoKSorLC0uLzAAAAAxAAAyMzQ1Njc4OTo7PD0+P0BBQkNERUZHSElKSwAAAAAAFxcZGyQlKzIyMjIyMjQ2NjY2Ojo6Oj9AQEBAQEZGRkYAAAAAAAAAAAAAAAAAAAAlAAAAAAAAAAAAAAAAAAAAQAAAAAAAAAAAAABMFxclAAAAAAAAAAAAAEovAAAAAAAAAAAAAAAXGxcbGx8fHx8lJQAlKysrAAAAAAAAAAAAAAAAAAAAACgAKAAoACgAKAAoADwAbgC0AQgBbgGQAcYB1AIGAkYCYAKSAtAC4gMoA2ADyAPgBBoEUAR4BI4EogTWBOoE9gUiBToFSAViBXoFqgXWBjAGWgaaBqwG2AbqBwYHIAc2B0wHXgd2B7AH5ggOCCQIOAhsCIAIjAi4CNAI3gj4CRAJQAlsCcYJ8AowCkIKbgqACpwKtgrMCuIK4griAAAABQAyAAAB3QK8AAMABgAJAAwADwAAEyERIRsCCwEREwMhAxMRMgGr/lUcubrGtMG5AXKttQK8/UQCqP7LATX+tgEs/acBGP7MAUn+0QJdAAACADUABQDCAmoAAwAHAAATESMRExUjNcGLi4sCaf5mAZr+KY2NAAAAAgA1AAACSAJkABsAHwAAJQcjNyMHIzcjNzM3IzczNzMHMzczBzMHIwczByc3IwcBthdrFkoXbBdeDl8KYA9fFWwVShVtFWoPagpqDscJSgqqqqqqqmxHbJqamppsR2xsR0cAAAEANf/JAZUCqgAwAAABFR4BByM0LgEjIgYVFBYXHgMVFA4BBxUjNS4BNTMUFjMyNjU0LgInJjU0Njc1ARwwPAF3CBQOExcsPCEwFgkZNyhnPkGDGRQTGBElHBprRzQCqkQNV0INGBIdFB8hGw4tMCkUJkU7EENDCmk8GiUgFBIeGA4LKXpKVxBEAAAABQA1/+8CdgJrAAwAGAAcACkAOAAAEzQ2MzIeARUUBiMiJjcVFBYzMjY1NCYiBiUDIxMDNTQ+ATMyFhQGIyImNxUUHgEzMjY1NC4BIyIGNk02JD0jTTc2TVEeFBUeHiodAWjhVeEtIz0kN01ONjZOUQ4YDRUeDhcOFR4B1j5XKEUoPldXPgEXISEYGCEhcf2dAmP+JgEoRChXfFdWPwEPGhAiGBAbDyIAAwA1AAAB2AJnACQAOQBIAAAlFwcnDgEjIiY1ND4CNyY1NDYzMhYVFA4IBxc3MyciBhUUHgQXPgU1NCYjAxY+ATcnDgUVFBYBmT8qQgdUMk1cDyETFDVTNzdPAwUJBw0HDgUMATUabPULGQQFCgUKAQENBAsEBBYNAQ8bEQRRAQ4ECwUEIbFNZEERMGJKHzMqEhFDQD9ZVjsLFxITDRAJDgULAUFBtRgSBw4LDwcOAQEQBg8LDwcPGf58AQsOB2IBDQUOCg8IGyQAAAAAAQA1ATwBSQJtABEAABMHNxcHFwcnFyM3Byc3JzcXJ+YXVSVnZyhTGE0WUShnZyVWGAJselJLJSVOVXp7Vk4nI0tReQACADUAAAGjAmQAFwAmAAA3NTQ+AzMyHgMdARQOAiMiLgI3FRQeATMyPQE0IyIOAjYZJzIvFxQtMicaIjc9Hh09OiR8CBsXOTkSGAsF4KQxTzEhDQwhMFAypDtaMhkYMlvjrBUkH1isVxEeGgABADUAAAEAAmEABQAAMxEjNTMRhE7KAd6D/Z8AAQA1AAMBkwJmACEAADc1Njc+AzU0JiMiByM+Ajc+AzMyFhUUBgcGBzMVOi5WFxkaCx0XMQJ2AQINDQ4qLCIQTlkjLkAargN3L1kYHCcoFyIhXhsgNxccJxIHbU04WDRHHYEAAAEANQAAAZ8CZAAtAAATNjc2MzIWFRQOAwcWFRQGIyImJyYnMxYXMjY1NC4DKwE1MzI1NCYjIgdDAjktP0RVCw0VCwlca0otVRYVBn4KLhobCg8UDQcsFT0RESQCAaxgMCdfQRcoGBcIBiVpTWwrKCRENgElHRAYCwcCbzsVHjMAAgA1//8BuwJjAAoADQAAITUjNRMzETMVIxUnMzUBDdfadDY20WJrcgGF/oN6a+XAAAAAAAEANf//AawCYwAgAAABFSMHNjMyHgIVFA4CIyIuASczFjMyNjU0JiMiBycTAX+uCxsnKUIlExYrSy8zUS8HfRYjGygkHy4SZSoCYoBSEic+QyEkSkIqL00xJi8hHy80HwFTAAACADUAAAG0AmIAFgAoAAABMhYVFAYjIiYnJjU0PwEzBw4BBzAyNgMyPgE1NC4EIyIGFRQeAQEaO19vTy9QGCksepBYAw4CCA0kEx8TBAgLDxQLHSUVHQGvbF9kgConOV1LVdqUBRYFAv7XFCYXChMSEAwHLyEaJxIAAAAAAQA1//8BdAJjAAYAABMhFQMjEyM2AT6sibS9AmJ3/hUB3wAAAwA1AAABmwJkABkAJAAuAAATNTQ2MhYVFA4BBxYVFA4BIi4BNTQ3LgMXFRQWMjY1NCYiBjcVFBYyNjQmIgZCVqBWFBAMPC1RaFEtPAkLEgpwHjAdHTAeCRskGxskGwG/AUJhYkIeMxINJGU5WjMzWjllJAkNHSbhARgqKhkaKirTARcfHy8fHwAAAAACADUAAAG0AmQAFgAkAAA/AT4BNyYOASMiJjU0NjMyFhcWFRQPARM1NC4BIyIGFRQWMzI2fVgDDQQBCA0EO15uTy9QGCoteSsVHhAcKCUfHiUBlAQWBgEBAWxfZIAqJzldTFXaAYkBGiYSLiIgMi4AAgA1/8wCdQJtADgASAAAAQcGBwYzMjY1NCYjIgYHBh4DFxY3FQYnLgQ3ND4CMzIWFRQGIyInBicuATU0NjMyFhc3BzY1NC4CJyYGHQEUFjc2AfscBAIBFhYmbFVhdgcBBhwtVThNX01cQGlGMBUBLExzQniZWjs3FB07NT1PQBwoBwgqCQIHEg0gKCAUIQG2ux0NGVo8Wm2Laxg2RTcpBAUfWxsCASlBVlsvQHpfOqF8XZBBNwEBWkRIcyAWKMkaIgcQGBEBAz8rAyYjAQIAAAIANQAAAcgCZQAHAAoAADcHIxMzEyMvAge8GG6bYJdvGhknK3JyAmT9nHJz1tYAAAMANQABAWQCaAAPABoAJQAANxEzMhcWFRQHFhUUBw4BIwMzMjc2NTQnJisBFxUzMjc2NTQnJiM2lEAiJC9DJhszNx0mEgkQEAgUJQExFAsVFAoWAgJlKShQUygka1cuIhMBfAYLIB4LBuNwCA4mIgwGAAAAAQA1AAABqQJnACUAACUzDgEjIi4CNTQ+AjMyHgMXIy4DIyIOARUUFjMyPgIBSWAQX0cxSiwWFStLMSM7KB4QA2AFDhQfER4pEi8qFCEUCulrfjNXbD47alk0HzJAPR0SISATNEwsSWcXJxkAAgA1AAABgwJlAA8AGAAAMxEzMh4DFxYVFA4CIwMRMzI1NCcmIzZ/EhcsICYOJBUtTzUiKF4TFzMCZAEMFi4hT29BbFcwAdr+r6dDLjkAAAABADUAAAE3AmUACwAAEyEVIxUzFSMVMxUhNgEBlpGSlv8AAmR4cHmKeQAAAAEANQAAATcCZQAJAAAzESEVIxUzFSMRNgEBmJOTAmR5b3r+/gAAAAABADUAAAG3AmYAIQAAARUmBw4CFRQeAjMyNzY3IzUzFgcGIyIuATU0NjMyFhcBQBQ3FygbEBkgESEWGQVr0wUTMH89WCpiX0haEAGbAUgCASNPOC1FKhUaHDlpZkOyVYlXiaZvWwAAAAEANQAAAYYCZQALAAAzIxEzFTM1MxEjNSOcZmaDZ2eDAmTm5v2c9QABADUAAACgAmUAAwAAMxEzETZpAmT9nAABADUAAAFRAmUAGgAAAREUBwYHBiMiLgMnJjUzFBYVFjMyNzY1EQFQDQ8fJi4IESsgIAUCcQEEGxUHBAJk/pZkLCscIwIRHkEsFxcCDAQzGxAhAZEAAAAAAQA1//8BiwJmAAoAABcRMxETMwMTIwMRNmdzbISTfnABAmb+7AEU/s/+zAEJ/vYAAQA1AAABGgJlAAUAADMRMxEzFTZpewJk/iaKAAEANQAAAeUCZQAMAAAzIxEzGwEzESMTAyMDlmCLTEuMYARZRVgCZP52AYr9nAHK/jYBygABADUAAAGMAmUACQAAGwEDMxEjAxMjEZ2NAWNikwJjAmT+lAFs/ZwBaf6XAmQAAAACADUAAAGsAmUADAAfAAATNDYzMhYVFA4BIyImNxQWMzI+BDU0LgIjIg4BNmRWUWs0VDRWZGgqKg8aEQ0IAwgSIhceJw4BLKGXmJpfjUaelUtjDxohKCcUHzo1IDVKAAACADUAAAFgAmYAEAAbAAATMzIeARcWFRQGBw4BKwEVIxMVMzI3NjU0JyYjNoEjMRoMLhcSFjEtKGRkJRoNGBkOHAJlCxMPO2cvWRkdGMAB3ZMJEi8uEQoAAwA1//8BvwJmABsALgA8AAAlFwYiLgInDgIjIi4BNTQ+ATMyFhUUBx4CAyIOBAc2MzIXFhc2NTQuAQMeAzsBMjcmJyYjIgG9AQINGRgcChMsFBM+VycmWD1Uah0GDQzAERwSDQcCARgVKCIbHQkbLGgGFRUTBgYWDhEOGSAPenkBAggSDRMTAlaGU1GIXK5/ZUkIBwEBZxIgHScLCBEoHzQeLTJOKP7/HCgQCQwiFSMAAAAAAgA1//8BjwJmAA0AGgAAJRcjJxUjETMXFhcWFRQnNjU0LgInKwEVMzIBDYF+cGpqOi4UW4QYCxARBQY1Lhb7++vqAmQBBQosgohEFyoVHg4IAZkAAQAyAAABjwJnACsAADczFBY3NjU0JicuAycmPgEzMhYXIy4DIyIGFRQWFx4BFRQOAiMiJjZ2JBIyJjwRICobAQE0TSs5WQp0AQMJEg0RHCdBQTEUJkQsXFbFKx8BBDgWIB4JFyg7ITlVKFRbCwwTCh0UFSIkJEc2JUE3IGkAAAABADUAAAFTAmUABwAAMxEjNSEVIxGLVQEdVQHseHj+FAAAAAABADUAAAGNAmUAGgAAEzMRFBceATI2NzY1ETMRFA4BBwYjIiYnLgE1NmsIBR8qHgUIagcQDjBUIk0ZGQwCZP6WLhsSGBYQFzUBa/6WM0MvFEEcJCZISwAAAQA1AAABpwJlAAYAADMDMxsBMwO2gGdQUWmAAmT+UwGt/ZwAAQA1AAACQAJkAAwAADMDMxsBMxsBMwMjCwGfaWk4PFA8OGhrWz4+AmP+cwGN/nEBj/2dAYz+dAABADUAAAHBAmUACwAAMxMDMxc3MwMTIycHNop6c0NCcnmJc1VRAUYBHq6u/t/+vdnZAAAAAQA1AAABlAJlAAkAADczAzMXNzMDFSOsAXdvQUFtd3HrAXn29v6H6wAAAAABADUAAAFDAmYACQAAAQMzFSE1EyM1IQFDiIj+85OTAQ0B5v6kimcBdYkAAAEANQFFAaYCagAGAAAbATMTIycHNnx3fYE4NwFFAST+3LOzAAIANQAAAcgCZQAHAAoAADcHIxMzEyMvAge8GG6bYJdvGhknK3JyAmT9nHJz1tYAAAMANQABAWQCaAAPABoAJQAANxEzMhcWFRQHFhUUBw4BIwMzMjc2NTQnJisBFxUzMjc2NTQnJiM2lEAiJC9DJhszNx0mEgkQEAgUJQExFAsVFAoWAgJlKShQUygka1cuIhMBfAYLIB4LBuNwCA4mIgwGAAAAAQA1AAABqQJnACUAACUzDgEjIi4CNTQ+AjMyHgMXIy4DIyIOARUUFjMyPgIBSWAQX0cxSiwWFStLMSM7KB4QA2AFDhQfER4pEi8qFCEUCulrfjNXbD47alk0HzJAPR0SISATNEwsSWcXJxkAAgA1AAABgwJlAA8AGAAAMxEzMh4DFxYVFA4CIwMRMzI1NCcmIzZ/EhcsICYOJBUtTzUiKF4TFzMCZAEMFi4hT29BbFcwAdr+r6dDLjkAAAABADUAAAE3AmUACwAAEyEVIxUzFSMVMxUhNgEBlpGSlv8AAmR4cHmKeQAAAAEANQAAATcCZQAJAAAzESEVIxUzFSMRNgEBmJOTAmR5b3r+/gAAAAABADUAAAG3AmYAIQAAARUmBw4CFRQeAjMyNzY3IzUzFgcGIyIuATU0NjMyFhcBQBQ3FygbEBkgESEWGQVr0wUTMH89WCpiX0haEAGbAUgCASNPOC1FKhUaHDlpZkOyVYlXiaZvWwAAAAEANQAAAYYCZQALAAAzIxEzFTM1MxEjNSOcZmaDZ2eDAmTm5v2c9QABADUAAACgAmUAAwAAMxEzETZpAmT9nAABADUAAAFRAmUAGgAAAREUBwYHBiMiLgMnJjUzFBYVFjMyNzY1EQFQDQ8fJi4IESsgIAUCcQEEGxUHBAJk/pZkLCscIwIRHkEsFxcCDAQzGxAhAZEAAAAAAQA1//8BiwJmAAoAABcRMxETMwMTIwMRNmdzbISTfnABAmb+7AEU/s/+zAEJ/vYAAQA1AAABGgJlAAUAADMRMxEzFTZpewJk/iaKAAEANQAAAeUCZQAMAAAzIxEzGwEzESMTAyMDlmCLTEuMYARZRVgCZP52AYr9nAHK/jYBygABADUAAAGMAmUACQAAGwEDMxEjAxMjEZ2NAWNikwJjAmT+lAFs/ZwBaf6XAmQAAAACADUAAAGsAmUADAAfAAATNDYzMhYVFA4BIyImNxQWMzI+BDU0LgIjIg4BNmRWUWs0VDRWZGgqKg8aEQ0IAwgSIhceJw4BLKGXmJpfjUaelUtjDxohKCcUHzo1IDVKAAACADUAAAFgAmYAEAAbAAATMzIeARcWFRQGBw4BKwEVIxMVMzI3NjU0JyYjNoEjMRoMLhcSFjEtKGRkJRoNGBkOHAJlCxMPO2cvWRkdGMAB3ZMJEi8uEQoAAwA1//8BvwJmABsALgA8AAAlFwYiLgInDgIjIi4BNTQ+ATMyFhUUBx4CAyIOBAc2MzIXFhc2NTQuAQMeAzsBMjcmJyYjIgG9AQINGRgcChMsFBM+VycmWD1Uah0GDQzAERwSDQcCARgVKCIbHQkbLGgGFRUTBgYWDhEOGSAPenkBAggSDRMTAlaGU1GIXK5/ZUkIBwEBZxIgHScLCBEoHzQeLTJOKP7/HCgQCQwiFSMAAAAAAgA1//8BjwJmAA0AGgAAJRcjJxUjETMXFhcWFRQnNjU0LgInKwEVMzIBDYF+cGpqOi4UW4QYCxARBQY1Lhb7++vqAmQBBQosgohEFyoVHg4IAZkAAQAyAAABjwJnACsAADczFBY3NjU0JicuAycmPgEzMhYXIy4DIyIGFRQWFx4BFRQOAiMiJjZ2JBIyJjwRICobAQE0TSs5WQp0AQMJEg0RHCdBQTEUJkQsXFbFKx8BBDgWIB4JFyg7ITlVKFRbCwwTCh0UFSIkJEc2JUE3IGkAAAABADUAAAFTAmUABwAAMxEjNSEVIxGLVQEdVQHseHj+FAAAAAABADUAAAGNAmUAGgAAEzMRFBceATI2NzY1ETMRFA4BBwYjIiYnLgE1NmsIBR8qHgUIagcQDjBUIk0ZGQwCZP6WLhsSGBYQFzUBa/6WM0MvFEEcJCZISwAAAQA1AAABpwJlAAYAADMDMxsBMwO2gGdQUWmAAmT+UwGt/ZwAAQA1AAACQAJkAAwAADMDMxsBMxsBMwMjCwGfaWk4PFA8OGhrWz4+AmP+cwGN/nEBj/2dAYz+dAABADUAAAHBAmUACwAAMxMDMxc3MwMTIycHNop6c0NCcnmJc1VRAUYBHq6u/t/+vdnZAAAAAQA1AAABlAJlAAkAADczAzMXNzMDFSOsAXdvQUFtd3HrAXn29v6H6wAAAAABADUAAAFDAmYACQAAAQMzFSE1EyM1IQFDiIj+85OTAQ0B5v6kimcBdYkAAAAAEADGAAEAAAAAAAEACAASAAEAAAAAAAIABwArAAEAAAAAAAMAFQBfAAEAAAAAAAQACACHAAEAAAAAAAUAIgDWAAEAAAAAAAYADwEZAAEAAAAAABAACAE7AAEAAAAAABEABwFUAAMAAQQJAAEAEAAAAAMAAQQJAAIADgAbAAMAAQQJAAMAKgAzAAMAAQQJAAQAEAB1AAMAAQQJAAUARACQAAMAAQQJAAYAHgD5AAMAAQQJABAAEAEpAAMAAQQJABEADgFEAFYAZQBnAGUAbQBpAHQAZQAAVmVnZW1pdGUAAFIAZQBnAHUAbABhAHIAAFJlZ3VsYXIAADEALgAwADAAMgA7AFYAZQBnAGUAbQBpAHQAZQBSAGUAZwB1AGwAYQByAAAxLjAwMjtWZWdlbWl0ZVJlZ3VsYXIAAFYAZQBnAGUAbQBpAHQAZQAAVmVnZW1pdGUAAFYAZQByAHMAaQBvAG4AIAAxAC4AMAAwADIAOwBGAG8AbgB0AHMAZQBsAGYAIABNAGEAawBlAHIAIAAzAC4AMwAuADAAAFZlcnNpb24gMS4wMDI7Rm9udHNlbGYgTWFrZXIgMy4zLjAAAFYAZQBnAGUAbQBpAHQAZQBSAGUAZwB1AGwAYQByAABWZWdlbWl0ZVJlZ3VsYXIAAFYAZQBnAGUAbQBpAHQAZQAAVmVnZW1pdGUAAFIAZQBnAHUAbABhAHIAAFJlZ3VsYXIAAAAAAgAAAAAAAP+DADIAAAAAAAAAAAAAAAAAAAAAAAAAAABOAAAAAQACAQIBAwADAAQABgAHAAgACQANABMAFAAVABYAFwAYABkAGgAbABwAIwAkACUAJgAnACgAKQAqACsALAAtAC4ALwAwADEAMgAzADQANQA2ADcAOAA5ADoAOwA8AD0AQQBEAEUARgBHAEgASQBKAEsATABNAE4ATwBQAFEAUgBTAFQAVQBWAFcAWABZAFoAWwBcAF0ArAEECWNvbnRyb2xMRgljb250cm9sQ1IKc29mdGh5cGhlbgAAAAAAAAH//wACAAEAAAAMAAAAFgAAAAIAAQABAE0AAQAEAAAAAgAAAAAAAQAAAAoALAAuAAJERkxUAA5sYXRuABgABAAAAAD//wAAAAQAAAAA//8AAAAAAAAAAQAAAAoAMAA+AAJERkxUAA5sYXRuABoABAAAAAD//wABAAAABAAAAAD//wABAAAAAWtlcm4ACAAAAAEAAAABAAQAAgAAAAEACAABKd4ABAAAAEYAlgEwAd4CjAM2A+AEegUsBWYGDAa+B3AIHgjQCYIKNAriC4gMAgx0DOYNZA3mDlQOyg88D54QEBCGEQARchHsEmIS1BOWFAwUghTwFWIV1BaiFxQXkhgEGMYZdBomGtQbfhwYHL4dYB3+HpgfPh/oIJYhPCHmIpQjRiPsJJolSCXuJpQnQifoKJIpRAAmAAn/8QAK//sADP/7AA3/+wAO//sAD//7ABD/+wAR//sAEv/7ABP/+wAU//sAFf/xABb/8QAZ//sAHf/2AB7/+wAf//sAIP/xACH/+wAi//sAI//7ACT/+wAl//EAJv/2ACf/8QAo//sAKf/2ACr/+wAr//sALP/sAC3/7AAu/+IAL//dADD/9gAx/+wAMv/7ADP/+wA0//YAKwAG//EACP/nAAn/4gAK/9MAC//iAAz/9gAN/+IADv/sAA//4gAQ/9gAEf/iABL/1QAT//EAFP/nABX/8QAW/9gAMf/TADL/pgAz//MANP/nADX/8QA2//EAN//7ADj/7gA5//YAOv/7ADv/2AA8//EAPf/2AD7/9gA///EAQP/sAEH/+wBC/+wAQ//xAET/7ABF/+wARv/2AEf/3QBI/90ASf/EAEr/zgBL//YAKwAG//YAB//2AAn/3QAL/+wADP/sAA3/8QAO//YAD//sABD/8QAR/+wAEv/iABP/5wAU/+wAFf/dABb/7AAX/78AMf/YADL/sAAz/+IANP/iADX/8QA2/+cAN//xADj/3QA5/+wAOv/2ADv/4gA8//EAPf/xAD7/8QA///YAQP/YAEH/9gBC/+cAQ//sAET/7ABF/+wARv/xAEf/zgBI/9MASf/OAEr/zgBL/+wAKgAG//YAB//iAAj/4gAK/+IADP/dAA3/ugAO/+IAD//iABD/5wAR/+IAEv/dABP/yQAU/90AFf+mABb/0wAx/5gAMv/YADP/4gA0/9MANf/xADb/7AA3/+wAOP/iADn/7AA6//EAO//dADz/5wA9/+wAPv/sAD//5wBA/9gAQf/sAEL/zgBD/+wARP/YAEX/tQBG/90AR/+hAEj/oQBJ/8QASv+DAEv/7AAqAAb/8QAH/90ACP/YAAn/oQAL/8kADP/iAA3/sAAO/+cAD//YABD/4gAR/90AEv/bABP/4gAU/+IAFf/TABb/5wAg/+QAMf/nADL/3AAz//QANP/rADX/9AA2//IAN//4ADj/8AA5//QAOv/1ADv/7AA8/+oAPf/7AD7/9wA///IAQP/tAEH/+wBC/+IAQ//2AET/4wBF/7YARv/vAEf/pgBK/6MAS//yACYAB//TAAj/8QAK/84ADP/dAA3/9gAO//EAD//dABD/pgAR/8kAEv+6ABP/7AAU/90AFf/OADH/xAAy/5IAM//sADT/3QA1/+cANv/xADf/9gA4/90AO/9WADz/5wA9//EAPv/sAD//5wBA/84AQf/dAEL/0wBD/+cARP/nAEX/5wBG/+cAR//dAEj/2ABJ/7oASv/JAEv/4gAsAAb/+wAH//sACP/xAAn/zgAK/+cAC//dAAz/9gAN/9gADv/tAA//7AAQ/+kAEf/rABL/3QAT/90AFP/hABX/3QAW/90AMf/nADL/vwAz/+cANP/nADX/8QA2//EAN//sADj/5wA5//YAOv/2ADv/4gA8//EAPf/2AD7/+wA///sAQP/2AEH/+wBC/+wAQ//7AET/7ABF/9MARv/7AEf/yQBI/84ASf+wAEr/xABL/+cADgAG//sACf/xAAv/7AAN//sADv/7AA8AAAAR//EAEv/0ABP/9gAU//EAFf/xABb/7AAx//YAQP/2ACkABv/7AAf/9gAI//sACf/iAAr/5wAL/+wADP/vAA3/3QAO//sAD//qABD/8QAR/+wAEv/nABP/8QAU/+cAFf/iABb/7AAx/+cAMv/vADP//AA0/+cANf/7ADb//gA4//EAOf/8ADr//AA7/+kAPP/6AD3//QA+//4AP//7AEL/6gBD//0ARP/2AEX/7ABG//EAR//YAEj/4gBJ/+wASv/LAEv//AAsAAb/+wAH//EACP/2AAn/0wAK/+IAC//JAAz/5wAN/90ADv/iAA//7AAQ/+cAEf/sABL/3QAT/9MAFP/iABX/zgAW/+cAMf/YADL/xAAz/+wANP/dADX/6AA2//EAN//xADj/4wA5//EAOv/2ADv/7AA8/+wAPf/sAD7/9gA//+wAQP/iAEH/8QBC/90AQ//nAET/5wBF/8QARv/mAEf/xABI/8kASf+1AEr/rQBL/+IALAAG//sAB//7AAj/9gAJ/9MACv/2AAv/ugAM/+kADf/dAA7/9gAP/+wAEP/2ABH/8AAS//EAE//2ABT/5wAV/9gAFv/sADH/vwAy/9UAM//eADT/3wA1//EANv/xADf/9gA4/+IAOf/xADr/9gA7/+wAPP/xAD3/9gA+//EAP//2AED/2ABB//EAQv/nAEP/9gBE/+cARf/TAEb/8QBH/9gASP/YAEn/xgBK/78AS//xACsABv/7AAf/9gAI/+wACf/TAAr/5wAL/90ADP/lAA3/zgAO/90AD//dABD/7AAR/+IAEv/iABP/2AAU/+IAFf/JABb/5wAx/90AMv/EADP/6wA0/+EANf/wADb/8AA4/9wAOf/dADr/7AA7/9gAPP/sAD3/5wA+/+wAP//iAED/0wBB/+IAQv/YAEP/4gBE/84ARf/JAEb/4gBH/8kASP/OAEn/vwBK/8kAS//TACwABv/7AAf/3wAI/+cACf+wAAr/4wAL/8kADP/dAA3/xwAO/+cAD//dABD/7AAR/+cAEv/iABP/yQAU/9cAFf+/ABb/4gAa/+kAMf/YADL/uwAz/+EANP/dADb/6wA3//MAOP/lADn/8QA6//IAO//eADz/5wA9/+4APv/zAD//8ABA/+IAQf/2AEL/6gBD//YARP/kAEX/zABG/+8AR/+0AEj/uwBJ/64ASv+vAEv/5QAsAAb/+wAH/90ACP/nAAn/4gAK/9MAC//nAAz/3QAN//YADv/eAA//3QAQ/7AAEf/OABL/sAAT//sAFP/dABX/0wAW/9MAMf/iADL/iAAz//YANP/OADX/9gA2//EAN//xADj/0wA5//YAOv/zADv/gAA8//EAPf/7AD7/+wA///YAQP/OAEH/7gBC/84AQ//2AET/2ABF//sARv/2AEf/5wBI/+cASf/TAEr/4gBL/+wALAAG//sAB//2AAj/8QAJ/9gACv/nAAv/3QAM/+IADf/dAA7/4gAP/+IAEP/nABH/5wAS/9gAE//YABT/3QAV/84AFv/sADH/5wAy/78AM//nADT/2AA1/+cANv/nADf/7AA4/90AOf/sADr/7AA7/+cAPP/sAD3/8QA+/+wAP//xAED/4gBB//EAQv/dAEP/5wBE/+IARf/YAEb/5wBH/78ASP/HAEn/sABK/7UAS//dACsABv/xAAf/8QAI/+IACf/dAAr/0wAL/+IADP/iAA3/3QAO/+cAD//dABD/zgAR/9MAEv/EABP/0wAU/84AFv/dADH/4gAy/6EAM//jADT/3QA1/+wANv/sADf/5wA4/90AOf/nADr/8QA7/78APP/xAD3/9gA+/+wAP//nAED/3QBB/+cAQv/nAEP/5wBE/+IARf/OAEb/3QBH/8QASP/JAEn/lwBK/7oAS//YACkABv/sAAf/0wAI/90ACf/OAAr/3QAM/90ADf/EAA7/5wAP/9gAEP/YABH/3QAS/9MAE//YABT/4gAV/90AMf/sADL/wAAz/+8ANP/kADX/6wA2//AAN//2ADj/5AA5//EAOv/uADv/1gA8//QAPf/2AD7/8QA///AAQP/dAEH/7ABD/+gARP/YAEX/1QBG/+wAR/+3AEj/wwBJ/7UASv+wAEv/5gAeAAf/zgAi/+4AI//5ACT/7wAy/9AAM//pADT/sQA1/+sANv/nADf/5gA4/7oAOf/vADr/9wA7/9AAPP/sAD3/6wA+/+YAP//sAED/uwBB/+kAQv+7AEP/5ABE/9QARf+6AEb/0ABH/34ASP+SAEn/zQBK/5sAS//nABwAF//RACT//wAy/9EAM//uADT/5wA1/+8ANv/3ADf/7gA4/+gAOf/3ADr/+wA7/9oAPP/vAD3/9wA+/+4AP//vAED/4QBB//cAQv/nAEP/7wBE/+4ARf/QAEb/9wBH/8EASP/MAEn/wwBK/7sAS//nABwAF//QABv/+QAy/8EAM//zADT/6wA1//sANv/zADf/+wA4/+8AOf/zADr//gA7/+EAPP/vAD3/9wA+//kAP//3AED/4gBB//kAQv/jAEP/8wBE/+YARf/VAEb/+QBH/84ASP/JAEn/twBK/8EAS//rAB8ABv/7ABL/3wAX/8kAJf/5ACv/7wAy/7oAM//zADT/6wA1/+8ANv/uADf/8wA4/+oAOf/vADr/7wA7/9QAPP/5AD3//gA+//EAP//vAED/4wBB//MAQv/mAEP/7gBE/+cARf/XAEb/6wBH/8kASP/JAEn/twBK/7cAS//nACAABv/7ACQAAgAl/+8AJ//5AC3//gAv//4AMv/oADP//QA0/+sANf/7ADb/+gA3//sAOP/jADn/9wA6//oAO//kADz//wA9//0APv/+AD8AAABA/+gAQf/7AEL/6ABD//sARP/sAEX/8QBG//sAR//qAEj/6wBJ/+cASv/qAEv/+QAbAAb/+wAl/+8AMv+5ADP/+wA0/+8ANf/7ADb/+wA3//0AOP/vADn/+wA6AAAAO/+7ADz//gA9//4APv/7AED/7ABB//4AQv/nAEP/+QBE//kARf/7AEb/+QBH//MASP/rAEn/4gBK/+8AS//7AB0ABv/2ABf/zgAl/+8AMv+3ADP/9wA0/+sANf/3ADb/8QA3//kAOP/uADn/8wA6//sAO//YADz/8wA9/+4APv/3AD//8wBA/+MAQf/3AEL/6QBD/+8ARP/nAEX/1ABG/+8AR//JAEj/zABJ/6YASv/JAEv/3AAcAAb/+wAX//MAJf/7ADL/6wAz//4ANP/uADX/+wA2//4AN//+ADj/8wA5//0AOv/+ADv/7gA8//4APf/+AD7/+wA///4AQP/uAEL/9wBD//4ARP/+AEX/+QBG//4AR//uAEj/9wBJ/+4ASv/zAEv//gAYAAb/+wAx//YAMv/rADP//wA0//MANf//ADYAAQA3//8AOP/zADv/6AA8//4APf/+AD4AAQBA/+4AQf//AEL/8wBD//4ARP/4AEX//QBH/+wASP/3AEn/7ABK//EASwABABwABv/2ABf/4QAy/8oAM//9ADT/+QA1//4ANv/7ADf//gA4//MAOf/+ADr//wA7/+EAPP/7AD3//gA+//4AP//+AED/7wBB//4AQv/zAEP//gBE//sARf/7AEb//gBH/+8ASP/5AEn/2gBK//oAS//+AB0ABv/nABf/5wAx/7AAMv/hADP/7gA0/7QANf/rADb/5wA3/+4AOP+sADn/6wA6//kAO/+3ADz/6gA9/+8APv/nAD//5wBA/6wAQf/uAEL/rgBD/+cARP+8AEX/3ABG/9oAR//cAEj/0QBJ/9oASv/RAEv/7wAeAAb/9gAX//cAI//9ADH/vwAy/+4AM//5ADT/2gA1//4ANv/3ADf/+wA4/9oAOf/3ADr/+wA7/+cAPP/7AD3/+QA+//cAP//5AED/1ABB//sAQv/cAEP/9wBE/+8ARf/JAEb/6wBH/8QASP++AEn/5wBK/8EAS//+ABwAF//7ADH/7AAy/+QAM//+ADT/7gA1//4ANgAAADf//QA4//cAOf/7ADr//gA7/+4APP/+AD3//gA+//0AP//7AED/7wBB//4AQv/uAEP//gBE//cARf/7AEb/+QBH/+gASP/vAEn/6wBK/+gAS//+AB4ABv/7ABf/8wAa//4AHf/3ACX/9wAq//4AMf/2ADL/5AAz//0ANP/zADX/+wA2//4AN//+ADj/+QA7/+4APf/+AD7/+wA///4AQP/2AEH/+gBC/+4AQ//7AET/+QBF//sARv/+AEf/8wBI/+8ASf/zAEr/6wBL//4AHQAG//EAJP/3ADH/7AAy/7sAM//sADT/4wA1/+8ANv/vADf/9wA4/+QAOf/qADr/9wA7/98APP/vAD3/9wA+/+sAP//uAED/4wBB/+4AQv/mAEP/7wBE/+IARf/VAEb/7gBH/8MASP/GAEn/uwBK/7oAS//fABwABv/sACT//gAy/54AM//rADT/6gA1//EANv/rADf/9wA4/+MAOf/oADr/9wA7/64APP/sAD3/8QA+/+wAP//sAED/4QBB//MAQv/oAEP/5ABE/9gARf/kAEb/7gBH/9EASP/QAEn/uwBK/8QAS//zADAAF//3ABj//wAZ/+kAGv//ABv//QAc//4AHf/pAB7/+wAf//8AIP/iACH//gAi//8AI//+ACT//wAl/+IAJ//uACj//gAp/+cAKv/hACv/+QAs/8MALf/QAC7/5AAv/8wAMP//ADL/4QAz//4ANP/jADX/9wA3//kAOP/fADn/9wA7/+IAPP/5AD3/+gA+//EAP//6AED/2gBB/+8AQv/aAET/7wBF/9cARv/qAEf/xgBI/7sASf/qAEr/tABL//sAHQAG/+cAF//oACT/+gAy/+IAM//xADT/zAA1/+8ANv/sADf/+gA4/8wAOf/3ADr/8wA7/8kAPP/uAD3/7wA+/+wAP//rAED/yQBB//cAQv/MAEP/+ABE/9QARf/KAEb/2gBH/8EASP/EAEn/4gBK/7cAS//vAB0ABv/xABv/+QAl/+4AMv+8ADP/7wA0/9wANf/zADb/6AA3//cAOP/hADn/5gA6//MAO//aADz/6QA9//MAPv/pAD//6wBA/+MAQf/3AEL/2gBD/+kARP/rAEX/1ABG/+kAR//JAEj/zABJ/7QASv+7AEv/5wAbAAb/9gAy/6YAM//9ADT/0wA1//oANv/+ADf//QA4/9UAOf/3ADr//wA7/7kAPP/6AD3//gA+//sAP//7AED/0ABB//oAQv/XAEP/+QBE/+IARf/zAEb/9wBH/+8ASP/vAEn/6gBK/+cAS//6ABwABv/7ACQAAgAy/9UAM//7ADT/7wA1//cANv/9ADf//wA4/+4AOf/7ADr//wA7/+sAPP/+AD3//gA+//0AP//6AED/7gBB//sAQv/sAEP/+wBE/+8ARf/7AEb//QBH/+8ASP/qAEn/3wBK//gAS//+ABwABv/nABf/lQAy/4IAM//3ADT/wQA1/+kANv/nADf/+gA4/8QAOf/oADr/6wA7/5UAPP/uAD3/+wA+//cAP//vAED/wQBB/+8AQv/DAEP/5wBE/84ARf/uAEb/7gBH/+kASP/pAEn/zgBK/+4AS//7ADMABv/sABf/owAY//kAGf/XABr//gAb//4AHP/5AB3/0AAe//gAIP+tACH/8wAi//4AJP/+ACX/0AAm//kAJ//MACj//gAp/9oAKv/+ACv//gAs/+MALf/zAC7/3AAv//cAMP/7ADL/jwAz/+oANP/CADX/7wA2/+oAN//3ADj/xgA5/+sAOv/6ADv/qgA8/+sAPf/7AD7/7wA//+8AQP++AEH/7gBC/8MAQ//qAET/1QBF/+sARv/pAEf/6ABI/+cASf/iAEr/2gBL/+4AHAAG/+cAF//hADL/1AAz/+sANP+wADX/6wA2/+QAN//jADj/qgA5/+cAOv/jADv/ugA8/+cAPf/vAD7/2gA//+kAQP+uAEH/7wBC/64AQ//kAET/uwBF/9oARv/aAEf/zABI/84ASf/TAEr/zQBL/+sAHwAG/+IAF/+lACP//gAk//sAL//uADL/hwAz/+8ANP+sADX/+AA2/9wAN//6ADj/uQA5/+4AOv/vADv/hAA8/+gAPf/pAD7/5wA//+YAQP+wAEH/6QBC/7oAQ//vAET/zgBF/+gARv/oAEf/2gBI/+YASf/QAEr/4gBL/+kAHAAG//sAF//+ADL/5wAz//sANP/kADX/+wA2//8AN//7ADj/4QA5//4AOv//ADv/6wA8//sAPf/+AD7//gA///sAQP/hAEH/+wBC/9oAQ//+AET/7wBF//sARv/6AEf/6QBI//kASf/rAEr/6QBL//sAMAAG/+wAB//YAAj/3QAJ/9MACv+/AAv/yQAM/+IADf/YAA7/7AAP/9MAEP/JABH/5wAS/+IAE//OABT/4gAV/+wAFv/nACD/WwAh/+wAIv/xACP/8QAk//YAJf/xADL/oQAz/+wANP/nADX/7AA2//sAN//2ADj/9gA5//sAO/+PADz/7AA9//YAPv/sAD//8QBA/+IAQf/nAEL/7ABD/+IARP/JAEX/zgBG/+cAR/+/AEj/xABJ/5IASv+/AEv/4gArAAb/9gAI/8QACf+cAAr/zAAL/5QADP+6AA3/xAAO/+oAD//BABD/zgAR/78AEv+7ABP/2AAU/78AFf+mABcAAgAk/+cAMf+mADL/2AAz/+cANP+7ADX/5gA2//MAN//zADj/sQA5/+oAOv/rADz/6AA9/+gAPv/mAD//5wBA/7oAQf/4AEL/twBD/+gARP/OAEX/sQBG/88AR/+EAEj/lwBJ/9AASv+NAEv/9wAsAAb/9gAH/+oACP/nAAn/xAAK/+gAC//TAAz/3QAN/9gADv/lAA//5wAQ/+IAEf/aABL/3AAT/9MAFP/bABX/xAAk//EAMf/YADL/zQAz/+wANP/kADX/9wA2//MAN//9ADj/4wA5//cAOv/3ADv/5gA8//4APf/9AD7/7gA//+4AQP/kAEH/+QBC/+YAQ//vAET/6QBF/9oARv/vAEf/zgBI/88ASf/QAEr/uQBL//kAKwAG//YAB//qAAj/7AAJ/9gACv/uAAv/4gAM/+IADf/dAA7/9AAP/+IAEP/eABH/5gAS/+IAE//TABT/3QAV/90AJP/2ADH/7AAy/74AM//uADT/3wA1//oANv/xADj/5wA5/+8AOv/5ADv/2AA8/+0APf/9AD7/8wA///EAQP/rAEH/+ABC/+QAQ//3AET/5gBF/9AARv/zAEf/xgBI/80ASf++AEr/twBL/+gAKgAH//EACP/xAAn/0wAK/+YAC//YAAz/5wAN/9gADv/oAA//5wAQ/+IAEf/iABP/2AAU/90AFf/dACT/+wAx/+wAMv+7ADP/9wA0/+QANf/rADb/5wA3//EAOP/kADn/+QA6//YAO//aADz/9wA9//4APv/uAD//8QBA/+cAQf/vAEL/4wBD/+sARP/cAEX/0ABG/+sAR//CAEj/xABJ/7QASv+6AEv/6AAmAAf/9gAI//EACf/sAAr/9gAM/+cADv/6AA//8QAQ//EAEf/vABL/4QAT//EAFP/iABX/5wAy/+kAM//9ADT/5wA1//sANv/9ADf//gA4/+sAOf/+ADoAAQA7/+gAPP/9AD3/9wA+//0AP//9AED/6wBBAAEAQv/pAEP/+QBE/+wARgACAEf/6QBI/+8ASf/nAEr/6wBL//sAKQAH//sACP/xAAn/5wAK/+4AC//2AAz/4gAN//sADv/1AA//8QAQ/90AEf/kABL/4gAT/+wAFP/YABX/3QAx//YAMv+5ADP/+AA0/+MANf/3ADb/+AA3//kAOP/iADn/+gA6//0AO//OADz//QA9//4APv/5AD///ABA/+YAQv/jAEP/9wBE/+YARf/vAEb//gBH/+cASP/vAEn/0QBK/+YAS//9ACgAB//2AAj/4gAJ/90ACv/sAAv/4gAM/+gADf/iAA7/9QAP/+gAEP/dABH/4AAS/+YAE//OABT/4gAV/90AJP/7ADH/9gAy/8EAM//vADT/3wA2//QAN//4ADj/4wA5/+kAOv/6ADv/0QA8/+YAPf/zAD7/6QA///EAQP/qAEL/3ABD/+gARP/fAEb/+ABH/7sASP+7AEn/rwBK/68AS//jACcACP/xAAn/7AAK//gADP/2AA7/9wAP//YAEP/xABH/5wAS/+cAE//xABT/7AAV/+UAMf/2ADL/6AAz//kANP/qADX/+wA2//oAN//7ADj/6wA5//cAOv//ADv/4wA8//sAPf/+AD7/+wA///oAQP/sAEH/+gBC/+MAQ//5AET/7wBF/+oARv/7AEf/4wBI/+wASf/jAEr/6gBL//4AJgAH//sACP/7AAn/5wAK//oADP/2AA7/9gAP//YAEP/xABH/8QAS//IAE//xABT/5wAV//EAMv/nADP/+wA0//EANf/9ADb//gA3//4AOP/uADn/+wA6//4AO//oAD0AAAA+//sAP//+AED/7wBB//4AQv/qAEP//wBE//EARf/3AEb/+wBH/+YASP/3AEn/2gBK/+QAS//7ACkAB//2AAj/9gAJ/90ACv/yAAz/8QAO//EAD//wABD/6gAR/+wAEv/mABP/9AAU/+wAFf/rABf/zgAx//YAMv/OADP/7wA0/+oANf/5ADb//gA3//0AOP/oADn/+QA6//0AO//YADz//gA9//8APv/6AD//+QBA/+4AQf/5AEL/4wBD//gARP/qAEX/+QBG//oAR//pAEj/6QBJ/9UASv/rAEv/+gAqAAf/sgAI/8kACf+wAAr/ugAL/7UADP+1AA3/3QAO/+QAD/+6ABD/sgAR/7UAEv+xABP/4gAU/6sAFf+mADH/lwAy/9oAM//jADT/qwA1/+IANv/iADf/4wA4/5oAOf/XADr/7gA7/7QAPP/kAD3/6wA+/+4AP//mAED/rQBB/+8AQv+qAEP/6gBE/74ARf/XAEb/2gBH/9AASP/SAEn/1QBK/80AS//qACsAB//nAAj/8QAJ/6YACv/sAAv/nAAM/90ADf+6AA7/9gAP/+IAEP/sABH/3QAS/9oAE//sABT/3QAV/8QAJP/+ADH/pgAy/+sAM//vADT/ygA1//0ANv/zADf/+wA4/9MAOf/vADr/+wA7/9gAPP/3AD3/9wA+//EAP//7AED/1QBB//cAQv/PAEP/8wBE/+YARf+7AEb/5wBH/7UASP/JAEn/2gBK/6UAS//zACkAB//2AAn/7AAK//kAC//sAAz/9gAO//oAD//2ABD/7AAR/+cAEv/vABP/9gAU//EAFf/sABcAAQAx/+YAMv/pADP/+QA0/+oANf/zADb/+wA3//oAOP/nADn/9wA6//4AO//uADz/+QA9//oAPv/7AD//+QBA/+8AQf/3AEL/6QBD//oARP/sAEX/8wBG//gAR//pAEj/6QBJ/+MASv/nAEv//QAqAAf/9gAI//sACf/sAAr/9wAL/+wADP/7AA7/+gAP//EAEP/2ABH/7AAS//EAE//2ABT/9gAV/+QAFwABADH/8QAy/+kAM//3ADT/6QA1//kANv/5ADf/+QA4/+8AOf/6ADr//gA7/+8APP/7AD3/+gA+//oAP//4AED/7wBB//sAQv/rAEP//QBE/+8ARf/3AEb/+gBH/+4ASP/rAEn/4QBK/+wAS//5ACsAB//xAAj/4gAJ/9gACv/sAAv/2AAM//YADf/iAA7/8QAP/90AEP/iABH/0wAS/+IAE//JABT/4gAV/94AJP/7ADH/3QAy/7QAM//pADT/4QA1/+wANv/vADf/6gA4/+IAOf/qADr/+gA7/9oAPP/pAD3/6wA+/+wAP//pAED/4QBB/+sAQv/cAEP/6wBE/+IARf/JAEb/7gBH/7wASP/BAEn/pgBK/7UAS//kACwAB//iAAj/5wAJ/+IACv/OAAv/2AAM/+cADf/nAA7/8AAP/90AEP+6ABH/xAAS/9cAE//XABT/2AAV/9gAG//3ACT/+wAx/+IAMv+gADP/6QA0/+MANf/mADb/7wA3/+sAOP/aADn/6AA6//YAO/+xADz/6wA9/+4APv/oAD//7wBA/9oAQf/oAEL/1wBD/+MARP/aAEX/2ABG/+cAR//PAEj/yQBJ/7kASv/BAEv/6AApAAf/8QAI/+wACf/OAAr/6gAL/84ADP/nAA3/2AAO//YAD//fABD/4gAR/9gAEv/lABP/5wAU/+IAFf/YADH/4gAy/+cAM//3ADT/2gA1//gANv/5ADf/+wA4/9wAOf/3ADr//gA7/+MAPP/3AD3//QA+//cAP//3AED/1QBC/9UAQ//9AET/6QBF/+EARv/pAEf/ugBI/8QASf/aAEr/wgBL//sAKwAH/8kACP/YAAn/xAAK/9MAC/+/AAz/yQAN/9gADv/nAA//xAAQ/7oAEf+1ABL/wQAT/9gAFP+6ABX/vwAk//sAMf+/ADL/2gAz/+gANP/KADX/6QA2/+kAN//oADj/xgA5/+QAOv/nADv/uQA8/+wAPf/uAD7/6QA//+cAQP/GAEH/7ABC/8kAQ//mAET/2ABF/84ARv/VAEf/wQBI/7wASf/GAEr/tABL/+8AKwAH//EACP/2AAn/yQAK/+oAC//TAAz/3QAN/+cADv/sAA//4gAQ/+IAEf/YABL/3wAT/90AFP/dABX/2AAk//sAMf/nADL/xgAz//MANP/iADX/7wA2/+4AN//3ADj/4wA5/+kAOv/vADv/1wA8/+4APf/zAD7/6gA//+0AQP/kAEH/9wBC/98AQ//qAET/5wBF/9AARv/vAEf/yQBI/9AASf/PAEr/xABL/+8AKQAH/+cACP/sAAn/5wAK/+kAC//dAAz/2AAO/+wAD//XABD/qwAR/8kAEv/AABP/9gAU/9MAFf/OADH/2AAy/7AAM//5ADT/2gA1//0ANv/6ADf//gA4/98AOf/3ADr//QA7/8YAPP/7AD3//gA+//gAP//4AED/1QBB//0AQv/VAEP/+ABE/+MARf/zAEb/+QBH/+4ASP/zAEn/4gBK/+cAS//zACkACP/2AAn/5wAK//QAC//sAAz/+wAN//4ADv/2AA//5QAQ/+wAEf/nABL/8wAT//EAFP/nABX/3QAx/+QAMv/KADP/+QA0/+wANf/6ADb/+gA3//sAOP/vADn/+gA6AAAAO//hADz//wA9//0APv/5AD///gBA/+wAQf/7AEL/7ABD//sARP/vAEX/9wBG//sAR//zAEj/6gBJ/+EASv/jAEv/+wArAAf/zgAI/84ACf/YAAr/ygAL/9gADP/JAA3/+wAO/9kAD//JABD/ogAR/7oAEv+5ABP/5wAU/8QAFf+9ACT/+wAx/7oAMv+FADP/+wA0/7sANf/qADb/6wA3/+wAOP++ADn/5gA6/+8AO/+iADz/6AA9/+oAPv/sAD//7wBA/8MAQf/mAEL/uwBD/+YARP/KAEX/6QBG/+8AR//jAEj/3wBJ/9MASv/hAEv/6wApAAf/zgAI/84ACf/TAAv/2AAM/84ADv/eAA//xAAQ/7AAEf/TABL/sQAT/+wAFP/FABX/yQAk//sAMf/JADL/lQAz//MANP/BADX/+QA2//MAN//3ADj/xgA5//sAOv/3ADv/pQA8/+8APf/+AD7/7gA//+oAQP/DAEH/7gBC/8QAQ//vAET/0ABF/+4ARv/uAEf/6QBI/+QASf/aAEr/5gBL//cAKgAH/8QACP/OAAn/pgAL/7oADP+rAA3/3QAO/+cAD/+5ABD/twAR/8QAEv+zABP/0wAU/7AAFf+cACT/+wAx/6EAMv/aADP/4wA0/7cANf/4ADb/4wA3//0AOP+3ADn/7gA6/+8AO/+7ADz/7gA9//EAPv/jAD//6ABA/7oAQf/zAEL/uQBD/+sARP/OAEX/3wBG/+EAR//aAEj/2ABJ/9gASv/MAEv/7gAsAAf/yQAI/84ACf/JAAr/wgAL/8kADP/JAA3//gAO/8kAD/+6ABD/jQAR/7oAEv+gABP/4gAU/7UAFf+6AB7/8QAk//sAMf+1ADL/lwAz/+8ANP+7ADX/5gA2/+4AN//uADj/uQA5/+gAOv/3ADv/hAA8/+8APf/sAD7/7AA//+oAQP+6AEH/7ABC/7kAQ//pAET/ygBF/+8ARv/vAEf/6ABI/+kASf/fAEr/5ABL//EAJgAH//YACf/iAAr/7AAL/+cADP/iAA3//wAO//UAD//nABD/7AAR/+IAEv/gABP/7AAU/90AFf/TADH/4gAy/+sAM//+ADT/6AA1//4ANgAEADf//wA4/9wAOf/6ADv/5gA8//8APf//AD///QBA/+MAQf//AEMAAABE/+8ARf/4AEb/+wBH//cASP/rAEn/6QBK/+kAS//9AAIAAQAGAEsAAAAAAAAAAQAAAADUGBYRAAAAANmXsTQAAAAA2ZexNA==",nt=n=>Ei("http://www.w3.org/2000/svg",n),Vs=(n,t)=>{const e=nt("rect");return e.setAttribute("height",`${n}`),e.setAttribute("width",`${t}`),e},zs=(n,t,e,a)=>{const r=Ce("filter");r.setAttribute("id",a),r.setAttribute("height","200%"),r.setAttribute("width","200%"),r.setAttribute("x","-50%"),r.setAttribute("y","-50%");const i=Ce("feOffset");r.appendChild(i),i.setAttribute("result","offOut"),i.setAttribute("in","SourceAlpha"),i.setAttribute("dx",`${n}`),i.setAttribute("dy",`${t}`);const o=Ce("feGaussianBlur");r.appendChild(o),o.setAttribute("result","blurOut"),o.setAttribute("in","offOut"),o.setAttribute("stdDeviation",`${e}`);const s=Ce("feBlend");return r.appendChild(s),s.setAttribute("in","SourceGraphic"),s.setAttribute("in2","blurOut"),s.setAttribute("mode","normal"),r},qs=n=>{let t=n;return t=t.replace(/feoffset/gi,"feOffset"),t=t.replace(/fegaussianblur/gi,"feGaussianBlur"),t=t.replace(/feblend/gi,"feBlend"),t=t.replace(/lineargradient/gi,"linearGradient"),t=t.replace(/stddeviation/gi,"stdDeviation"),t};function Gs(n,t,e,a,r,i){const o=r,s=i,l={x:t[0],y:t[1],width:t[2]-t[0],height:t[3]-t[1]};if(l.width<=0)return;const c=Ws(l.height,l.width,e*o,a*s),d=(a-c*l.width)/2-c*l.x,A=(e-c*l.height)/2-c*l.y;n.setAttribute("transform",`translate(${d} ${A}) scale(${c} ${c})`)}function Ws(n,t,e,a){const r=e/n,i=a/t;return r>1&&i>1?Math.min(r,i):r>1&&i<1?i:r<1&&i>1?r:Math.min(r,i)}const hn={m:["x","y"],z:[],l:["x","y"],h:["x"],v:["y"],c:["x1","y1","x2","y2","x","y"],s:["x2","y2","x","y"],q:["x1","y1","x","y"],t:["x","y"],a:["rx","ry","xRotation","largeArc","sweep","x","y"]};class js{constructor(t){const e=Array.from(t.querySelectorAll("path"));this.paths=e.map(a=>{const r=a.getAttribute("d")||"",i=this.parsePath(r);return{pathElement:a,pathData:i}})}transform(t){for(const e of this.paths)e.pathData=this.runTransformer(e.pathData,t);this.update()}encodePath(t){let e="";const r=i=>{const o=[],s=i.relative?i.type:i.type.toUpperCase();let l=e!==s;const c=hn[i.type];l&&(o.push(s),e=s);for(const d of c){const A=i[d];let u;switch(typeof A){case"boolean":u=A|0;break;case"number":u=(A*100|0)/100;break;default:throw new bt("Failed to encode path.")}l||o.push(" "),o.push(u),l=!1}return o.join("")};return t.map(r).join("")}parsePath(t){const e=/([mzlhvcsqta])([^mzlhvcsqta]*)/gi,a=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/gi,r=[];let i;for(e.lastIndex=0;i=e.exec(t);){const o=i[1].toLowerCase(),s=(i[2].match(a)||[]).map(parseFloat),l=o===i[1],c=hn[o];if(s.length<c.length)throw new bt(`Path type "${o}" given ${s.length} arguments, expected ${c.length}.`);if(c.length>0){if(s.length%c.length!==0)throw new bt(`Path type "${o}" given ${s.length} arguments, not divisible by ${c.length}`);for(let d=0;d<s.length/c.length;d++){const A={type:o,relative:l};for(let u=0;u<c.length;u++)A[c[u]]=s[d*c.length+u];r.push(A)}}else r.push({type:o,relative:l})}return r}runTransformer(t,e){const a=[["x1","y1"],["x2","y2"],["x","y"]],r=i=>{for(let o=0;o<a.length;o++){const[s,l]=a[o];if(s in i&&l in i){const c=[i[s],i[l]],d=e(c);if(d.length<2)throw new bt("Transformer must return at least 2 points.");i[s]=d[0],i[l]=d[1]}}return i};return this.transformPath(t,r)}transformPath(t,e){const a=[];for(let r=0;r<t.length;r++){const i=JSON.parse(JSON.stringify(t[r])),o=e(i);Array.isArray(o)?a.push(...o):o&&a.push(o)}return a}update(){for(const{pathElement:t,pathData:e}of this.paths){const a=this.encodePath(e);t.setAttribute("d",a)}}}class Hs extends Us{constructor(){super(...arguments),this.moduleName="Vegemite"}svgPreview(t,e){return this.svgElement(t,e)}svgPrint(t,e){return this.svgElement(t,e)}svgElement(t,e){const a=ns(Ls),i=t!==""?(b=>b.charAt(0).toUpperCase()+b.substr(1).toLowerCase())(t):"",o=a.getPath(i,0,72,72),s=o.toSVG(2),l=o.getBoundingBox(),c=l.x2-l.x1,d=o.toPathData(3),A=()=>{const b=nt("g");b.classList.add("module-text-group");const D=nt("defs");b.appendChild(D),D.appendChild(zs(0,2,2,"shadow"));const w=nt("path");w.setAttribute("d",d),w.setAttribute("stroke","black"),w.setAttribute("stroke-width","3"),D.appendChild(w);const S=nt("g");S.classList.add("module-layer0"),b.appendChild(S),S.setAttribute("filter","url(#shadow)"),S.innerHTML=w.outerHTML;const P=nt("g");P.classList.add("module-layer1"),b.appendChild(P),P.setAttribute("stroke-width","3"),P.setAttribute("stroke","rgb(45,41,38)"),P.setAttribute("fill","rgb(45,41,38)"),P.setAttribute("transform","translate(0.5,0)"),P.innerHTML=s;const F=nt("g");F.classList.add("module-layer2"),b.appendChild(F),F.setAttribute("fill","rgb(255,209,0)"),F.setAttribute("transform","translate(1,-0.1)"),F.innerHTML=s;const B=nt("g");return B.classList.add("module-layer3"),b.appendChild(B),B.setAttribute("fill","white"),B.innerHTML=s,new js(b).transform(([V,Y])=>[V,Y+(c/2-V)**2/(c*6)]),b},u=nt("g");u.classList.add("module-root");const h=nt("defs");u.appendChild(h);const g=nt("g");g.classList.add("module-bounds"),u.appendChild(g);const p=Vs(e.height,e.width);p.setAttribute("opacity","0"),g.appendChild(p);const m=nt("g");m.classList.add("module-text-enclosure"),u.appendChild(m);const f=A();m.appendChild(f);const v=di(d);return Gs(m,v,e.height,e.width,.35,.65),qs(u.outerHTML)}}async function Cr(n){if(n==="Vegemite")return new Hs;throw new U(`Failed to resolve Module, Module ${n} not found`)}const ge=C.gql`
1509
1509
  fragment GlobalPropertyStateAspectFields on GlobalPropertyStateAspect {
1510
1510
  name
1511
1511
  value
@@ -1527,7 +1527,7 @@
1527
1527
  }
1528
1528
  }
1529
1529
  }
1530
- `,Hs=w.gql`
1530
+ `,Ys=C.gql`
1531
1531
  ${ge}
1532
1532
  mutation CreateGlobalPropertyState($bundleId: String!) {
1533
1533
  globalPropertyStateCreate(bundleId: $bundleId) {
@@ -1537,7 +1537,7 @@
1537
1537
  }
1538
1538
  }
1539
1539
  }
1540
- `,Ys=w.gql`
1540
+ `,Js=C.gql`
1541
1541
  ${ge}
1542
1542
  mutation UpdateGlobalPropertyState($id: String!, $aspects: [GlobalPropertyStateAspectInput]!) {
1543
1543
  globalPropertyStateUpdate(id: $id, aspects: $aspects) {
@@ -1547,7 +1547,7 @@
1547
1547
  }
1548
1548
  }
1549
1549
  }
1550
- `,Js=w.gql`
1550
+ `,Ks=C.gql`
1551
1551
  ${ge}
1552
1552
  query GetGlobalPropertyState($bundleId: String!) {
1553
1553
  globalPropertyState(bundleId: $bundleId) {
@@ -1557,7 +1557,7 @@
1557
1557
  }
1558
1558
  }
1559
1559
  }
1560
- `,Ks=async n=>(await y.getShadowGraphqlClient().query({query:Js,fetchPolicy:"cache-first",errorPolicy:"all",variables:{bundleId:n}})).data.globalPropertyState,_s=n=>w.gql`
1560
+ `,_s=async n=>(await y.getShadowGraphqlClient().query({query:Ks,fetchPolicy:"cache-first",errorPolicy:"all",variables:{bundleId:n}})).data.globalPropertyState,Xs=n=>C.gql`
1561
1561
  ${qe}
1562
1562
  fragment ProductFields on Product {
1563
1563
  id
@@ -1602,8 +1602,8 @@
1602
1602
  name
1603
1603
  }
1604
1604
  }
1605
- `,Ga=n=>w.gql`
1606
- ${_s(n)}
1605
+ `,Wa=n=>C.gql`
1606
+ ${Xs(n)}
1607
1607
  fragment ProductCollectionProductFields on ProductCollectionProduct {
1608
1608
  id
1609
1609
  productId
@@ -1612,8 +1612,8 @@
1612
1612
  ...ProductFields
1613
1613
  }
1614
1614
  }
1615
- `,me=(n,t=!1)=>w.gql`
1616
- ${n?Ga(t):""}
1615
+ `,me=(n,t=!1)=>C.gql`
1616
+ ${n?Wa(t):""}
1617
1617
  fragment ProductCollectionFields on ProductCollection {
1618
1618
  id
1619
1619
  name
@@ -1682,7 +1682,7 @@
1682
1682
  }
1683
1683
  }
1684
1684
  }
1685
- `,Xs=n=>w.gql`
1685
+ `,Zs=n=>C.gql`
1686
1686
  ${ge}
1687
1687
  ${me(n)}
1688
1688
  query GetBundle($id: String!) {
@@ -1726,7 +1726,7 @@
1726
1726
  quoteId
1727
1727
  }
1728
1728
  }
1729
- `,hn=w.gql`
1729
+ `,gn=C.gql`
1730
1730
  query GetBundleStakeholders($id: String!) {
1731
1731
  bundles(ids: [$id]) {
1732
1732
  id
@@ -1771,7 +1771,7 @@
1771
1771
  }
1772
1772
  }
1773
1773
  }
1774
- `,Zs=w.gql`
1774
+ `,tl=C.gql`
1775
1775
  query GetBundlesForCustomer($id: String!) {
1776
1776
  customers(ids: [$id]) {
1777
1777
  bundleStakeholders {
@@ -1800,8 +1800,8 @@
1800
1800
  }
1801
1801
  }
1802
1802
  }
1803
- `,tl=w.gql`
1804
- ${Ga(!1)}
1803
+ `,el=C.gql`
1804
+ ${Wa(!1)}
1805
1805
  query GetProductCollectionProducts($id: String!, $productIds: [String!]) {
1806
1806
  productCollections(ids: [$id], productIds: $productIds) {
1807
1807
  id
@@ -1810,7 +1810,7 @@
1810
1810
  }
1811
1811
  }
1812
1812
  }
1813
- `,el=w.gql`
1813
+ `,al=C.gql`
1814
1814
  query GetProductCollectionForFilteredProducts(
1815
1815
  $id: String!
1816
1816
  $filters: ProductCollectionProductFilterInput
@@ -1833,8 +1833,8 @@
1833
1833
  }
1834
1834
  }
1835
1835
  }
1836
- `,al=w.gql`
1837
- ${Ga(!0)}
1836
+ `,nl=C.gql`
1837
+ ${Wa(!0)}
1838
1838
  query GetProductCollectionForProductsFeed(
1839
1839
  $id: String!
1840
1840
  $limit: Int
@@ -1865,7 +1865,7 @@
1865
1865
  }
1866
1866
  }
1867
1867
  }
1868
- `,nl=n=>w.gql`
1868
+ `,rl=n=>C.gql`
1869
1869
  ${me(n)}
1870
1870
  mutation CreateBundle(
1871
1871
  $collectionId: String
@@ -1894,7 +1894,7 @@
1894
1894
  }
1895
1895
  }
1896
1896
  }
1897
- `,rl=n=>w.gql`
1897
+ `,il=n=>C.gql`
1898
1898
  ${ge}
1899
1899
  ${me(n)}
1900
1900
  mutation DuplicateBundle(
@@ -1936,7 +1936,7 @@
1936
1936
  }
1937
1937
  }
1938
1938
  }
1939
- `,il=w.gql`
1939
+ `,ol=C.gql`
1940
1940
  mutation UpdateBundle(
1941
1941
  $id: String!
1942
1942
  $name: String
@@ -1956,19 +1956,19 @@
1956
1956
  id
1957
1957
  }
1958
1958
  }
1959
- `,ol=w.gql`
1959
+ `,sl=C.gql`
1960
1960
  mutation BundleAddTransaction($id: String!, $transactionId: String!) {
1961
1961
  bundleAddTransaction(id: $id, transactionId: $transactionId) {
1962
1962
  id
1963
1963
  }
1964
1964
  }
1965
- `,sl=w.gql`
1965
+ `,ll=C.gql`
1966
1966
  mutation BundleAddTransactions($id: String!, $transactionIds: [String!]!, $transactionOwnerIds: [String!]) {
1967
1967
  bundleAddTransactions(id: $id, transactionIds: $transactionIds, transactionOwnerIds: $transactionOwnerIds) {
1968
1968
  id
1969
1969
  }
1970
1970
  }
1971
- `,ll=w.gql`
1971
+ `,cl=C.gql`
1972
1972
  mutation BundleRemoveTransaction(
1973
1973
  $id: String!
1974
1974
  $transactionId: String!
@@ -1983,7 +1983,7 @@
1983
1983
  id
1984
1984
  }
1985
1985
  }
1986
- `,cl=w.gql`
1986
+ `,dl=C.gql`
1987
1987
  mutation BundleRemoveTransactions(
1988
1988
  $id: String!
1989
1989
  $transactionIds: [String!]!
@@ -1998,7 +1998,7 @@
1998
1998
  id
1999
1999
  }
2000
2000
  }
2001
- `,dl=w.gql`
2001
+ `,Al=C.gql`
2002
2002
  mutation BundleAddStakeholder($id: String!, $details: CustomerDetailsInput!, $type: String!) {
2003
2003
  bundleAddStakeholder(id: $id, details: $details, type: $type) {
2004
2004
  id
@@ -2018,13 +2018,13 @@
2018
2018
  }
2019
2019
  }
2020
2020
  }
2021
- `,Al=w.gql`
2021
+ `,ul=C.gql`
2022
2022
  mutation BundleAddStakeholder($id: String!, $emailAddress: String!) {
2023
2023
  bundleRemoveStakeholder(id: $id, emailAddress: $emailAddress) {
2024
2024
  id
2025
2025
  }
2026
2026
  }
2027
- `,ul=w.gql`
2027
+ `,hl=C.gql`
2028
2028
  mutation BundleUpdateStakeholders($id: String!, $input: [BundleStakeholderInput!]!) {
2029
2029
  bundleUpdateStakeholders(id: $id, input: $input) {
2030
2030
  id
@@ -2044,13 +2044,13 @@
2044
2044
  }
2045
2045
  }
2046
2046
  }
2047
- `,hl=w.gql`
2047
+ `,gl=C.gql`
2048
2048
  mutation BundleUpdateTransactionOrder($id: String!, $transactionIds: [String!]!) {
2049
2049
  bundleUpdateTransactionOrder(id: $id, transactionIds: $transactionIds) {
2050
2050
  id
2051
2051
  }
2052
2052
  }
2053
- `,gl=n=>w.gql`
2053
+ `,ml=n=>C.gql`
2054
2054
  ${me(n)}
2055
2055
  mutation BundleAssignProductCollection($id: String!, $productCollectionId: String!) {
2056
2056
  bundleAssignProductCollection(id: $id, collectionId: $productCollectionId) {
@@ -2060,13 +2060,13 @@
2060
2060
  }
2061
2061
  }
2062
2062
  }
2063
- `,ml=w.gql`
2063
+ `,pl=C.gql`
2064
2064
  mutation AssignGlobalPropertyConfiguration($bundleId: String!, $globalPropertyConfigurationId: String!) {
2065
2065
  bundleUpdate(id: $bundleId, globalPropertyConfigurationId: $globalPropertyConfigurationId) {
2066
2066
  id
2067
2067
  }
2068
2068
  }
2069
- `,pl=n=>w.gql`
2069
+ `,fl=n=>C.gql`
2070
2070
  query CustomerBundlesFeed($id: String!, $limit: Int!, $offset: Int!, $template: Boolean, $templateStatus: BundleTemplateStatus, $ordered: Boolean) {
2071
2071
  customerBundlesFeed(id: $id, limit: $limit, offset: $offset, template: $template, templateStatus: $templateStatus, ordered: $ordered) {
2072
2072
  items {
@@ -2102,27 +2102,27 @@
2102
2102
  total
2103
2103
  }
2104
2104
  }
2105
- `,fl=w.gql`
2105
+ `,Cl=C.gql`
2106
2106
  mutation FinalizeUpdateBundle($bundleId: String!) {
2107
2107
  bundleFinalizeUpdate(bundleId: $bundleId)
2108
2108
  }
2109
- `,Cl=w.gql`
2109
+ `,wl=C.gql`
2110
2110
  mutation ApproveBundle($id: String!, $note: String, $stakeholderId: String) {
2111
2111
  bundleApprove(id: $id, note: $note, stakeholderId: $stakeholderId)
2112
2112
  }
2113
- `,wl=w.gql`
2113
+ `,yl=C.gql`
2114
2114
  mutation RejectBundle($id: String!, $note: String, $stakeholderId: String) {
2115
2115
  bundleReject(id: $id, note: $note, stakeholderId: $stakeholderId)
2116
2116
  }
2117
- `,yl=w.gql`
2117
+ `,Sl=C.gql`
2118
2118
  mutation ApproveTransaction($id: String!, $note: String) {
2119
2119
  transactionApprove(id: $id, note: $note)
2120
2120
  }
2121
- `,Sl=w.gql`
2121
+ `,vl=C.gql`
2122
2122
  mutation RejectTransaction($id: String!, $note: String) {
2123
2123
  transactionReject(id: $id, note: $note)
2124
2124
  }
2125
- `,vl=w.gql`
2125
+ `,El=C.gql`
2126
2126
  mutation CreateRecipient(
2127
2127
  $firstName: String
2128
2128
  $lastName: String
@@ -2164,7 +2164,7 @@
2164
2164
  id
2165
2165
  }
2166
2166
  }
2167
- `,El=w.gql`
2167
+ `,bl=C.gql`
2168
2168
  mutation UpdateRecipient(
2169
2169
  $id: String!
2170
2170
  $firstName: String
@@ -2208,13 +2208,17 @@
2208
2208
  id
2209
2209
  }
2210
2210
  }
2211
- `,bl=w.gql`
2211
+ `,Bl=C.gql`
2212
2212
  mutation AtttachRecipient($id: String!, $recipientId: String!) {
2213
2213
  transactionAttachRecipient(id: $id, recipientId: $recipientId) {
2214
2214
  id
2215
2215
  }
2216
2216
  }
2217
- `;var pe=(n=>(n.Error="Error",n.Warning="Warning",n.Info="Info",n))(pe||{});const Bl=1e3;class gn extends ka{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},Bl)})}}class Il{constructor(t,e,a,r,i,o,s,l,c,d,A,u,h,g=!1,m,p=!1,f=!1,S=!1){this.workflowStatePromiseQueue=new Ma(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.renderLayouts=()=>{if(!this.previewService)return;const b=this.getCommandContext().getAllLayouts(),P=this.getLayoutPreviewService()?.getAll();if(P)for(const[,C]of P)C.render(b)},this.experience=t,this.client=e,this.updateTransaction=s,this.graphQlClient=l,this.commandContext=o,this.reloadedState=h,this.transaction=c,this.readOnly=g,this.singleVariantsRenderable=f,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=a,this.stepSpecificServices={},this.profanityFilter=r,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=d,this.previewService=A,this.modelContainer=m,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},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.currentAdjustingStepId="",this.renderableContextService=u,this.renderableContextService?.setWorkflowManager(this),this.isReloadedTransaction=p,this.workflow.steps.forEach(b=>{this.stepTags[b.stepName]=b.tags??[]}),S&&(this.workflowStatePromiseQueue.enabled=!1),this.initializationPromise=this.initializeDefaultWorkflowState(a),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(b=>{throw console.error(b),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.getCommandContext().registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()}))}getTemplatingContext(){const t=this.transaction.recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const r=a.uniqueIdentifier??a.title??"";a.type===Xt.FirstName?e[r]=t?.firstName:a.type===Xt.LastName?e[r]=t?.lastName:a.type===Xt.Custom&&(a.customFieldIndex===1?e[r]=t?.customField1:a.customFieldIndex===2?e[r]=t?.customField2:a.customFieldIndex===3?e[r]=t?.customField3:a.customFieldIndex===4?e[r]=t?.customField4:a.customFieldIndex===5&&(e[r]=t?.customField5))}),e}async updateRecipient(t,e,a,r,i,o,s,l,c,d,A,u,h,g,m,p,f){if(this.transaction.recipient?.id)this.transaction.recipient={id:this.transaction.recipient.id,firstName:t??this.transaction.recipient.firstName,lastName:e??this.transaction.recipient.lastName,address:a??this.transaction.recipient.address,suburb:r??this.transaction.recipient.suburb,state:i??this.transaction.recipient.state,email:o??this.transaction.recipient.email,postalCode:s??this.transaction.recipient.postalCode,country:l??this.transaction.recipient.country,mobile:c??this.transaction.recipient.mobile,company:d??this.transaction.recipient.company,apartment:A??this.transaction.recipient.apartment,customField1:u??this.transaction.recipient.customField1,customField2:h??this.transaction.recipient.customField2,customField3:g??this.transaction.recipient.customField3,customField4:m??this.transaction.recipient.customField4,customField5:p??this.transaction.recipient.customField5,conversionConfigurationId:f||this.transaction.recipient.conversionConfigurationId},await this.graphQlClient().mutate({mutation:El,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:r||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:o||this.transaction.recipient.email,postalCode:s||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company,apartment:A||this.transaction.recipient.apartment,customField1:u||this.transaction.recipient.customField1,customField2:h||this.transaction.recipient.customField2,customField3:g||this.transaction.recipient.customField3,customField4:m||this.transaction.recipient.customField4,customField5:p||this.transaction.recipient.customField5,conversionConfigurationId:f||this.transaction.recipient.conversionConfigurationId}});else{const S=await this.graphQlClient().mutate({mutation:vl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:r,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:A,customField1:u,customField2:h,customField3:g,customField4:m,customField5:p,conversionConfigurationId:f}});this.transaction.recipient={id:S?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:r,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:A,customField1:u,customField2:h,customField3:g,customField4:m,customField5:p,conversionConfigurationId:f},await this.graphQlClient().mutate({mutation:bl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id,recipientId:S.data?.recipientCreate?.id},context:{transactionOwnerId:this.transaction.transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(S=>S(this.transaction.recipient))}async fetchConversionConfiguration(){const t=this.transaction.recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=await this.graphQlClient().query({query:po,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}});e.data.conversionConfiguration&&(this.recipientConversionConfiguration=e.data.conversionConfiguration)}}async initializeDefaultWorkflowState(t){const e=()=>{const s=this.workflow.finalizeStepConfig;if(!s)return;const l=s.lookAtAnimation,c=s.modelAnimation;l&&this.previewService?.executeCameraAnimation(l),c&&this.modelContainer?.executeAnimation(c)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(s=>{this.storage[s.stepName]=s.storage||{}}),await this.fetchConversionConfiguration(),this.allScenes=await Ro(t);const r=Et(this.allScenes,this.stepSelections).map(s=>s.silentSteps).flat(),{stepElements:i,commands:o}=await this.stepElementsForIntroducedSilentSteps(r,!!this.reloadedState);this.commandContext.apply(new Q(o),!0),this.stepElements={...this.stepElements,...i},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}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}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.transaction.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}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}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))}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.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=M();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())}getMandatoryUnfulfilledSteps(){return Et(this.allScenes,this.stepSelections).flatMap(i=>i.renderableSteps).filter(i=>i.mandatory).filter(i=>!this.mandatorySteps[i.stepName]).map(i=>i.stepName)}setStepError(t,e,a){let r=!1;if(!this.validationErrors.steps.has(t)&&a)r=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const i=this.validationErrors.steps.get(t);a&&a!==i.get(e)?(r=!0,i.set(e,a)):a||(r=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}r&&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.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const a=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(a),Et(this.allScenes,this.stepSelections).filter(o=>o).map(o=>o.renderableSteps).flat().filter(o=>o.type===v.Model||o.type===v.Material).forEach(o=>{if(!o.option?.id){console.error(`Failed to read option id from step: ${o.stepName}`);return}const s=this.stepSelections[o.stepName]?.selectedVariants||[];if(s.length===0)return;const l=s[0];if(o.type===v.Model){if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");const c=l.asset?.fileLink;if(!c){console.error(`Failed to read model url from variant: ${l.id} for step: ${o.stepName}`);return}const d=o.data;this.modelContainer.applyModelVariant(o.stepName,{model:c,contextService:this.getLayoutPreviewService()},d.replaceProductModel||!1)}else{const c=l.material;if(!c){console.error(`Failed to read material from variant: ${l.id} for step: ${o.stepName}`);return}o.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,o.option.id,c)})}}),await a.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(!xe(a,this.storage)){this.storage=a;const r=new dn(this.constructSerializableWorkflow());this.commandContext.apply(r,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const r={stepName:a.stepName};r.storage=this.storage[a.stepName],r.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(i=>({id:i.id,priceModifier:i.priceModifier})),t.push(r)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new gn(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new gn(async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new L("Attempted to serialize state before it was initialized.");const e=It(t.transaction),a=this.dehydrateState(e);return JSON.stringify(a)}dehydrateState(t){for(const e of Object.values(t.layouts).map(a=>a.elements).flat())e.type==="illustration"&&(delete e.cachedObjectURL,e.src&&delete e.svg),e.type==="frame"&&delete e.pattern?.svg;return this.deleteFieldNameFromObjectRecursive(t,"__typename"),t}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}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,r)=>Object.keys(a).reduce((i,o)=>{const s=[...a[o]||[]];return r.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),i[o]=s,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce((t,e)=>(Bt(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])}getInvalidModelVariants(){return this.workflow.steps.reduce((t,e)=>(e.type===v.Model&&!Bt(e,this.stepSelections)&&t.push(e.stepName),t),[])}async stepElementsForIntroducedSilentSteps(t,e){const a=this.product;if(!a)return Promise.resolve({stepElements:{},commands:[]});const r=async(c,d,A)=>{if(c.type===v.SilentIllustration){const u=await new An(c,d).trigger();return{step:c,results:u}}else if(c.type===v.ProductOverlay){const u=await new An(c,d,A).trigger();return{step:c,results:u}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||s.push(r(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.transaction.id);this.transaction.transactionShareActions=t}async updateTransactionStakeholders(){const t=await y.getShadowGraphqlClient().query({query:So,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.transaction.currentStakeholder=void 0,this.transaction.stakeholders=void 0):(this.transaction.stakeholders=t.data.transactions[0].stakeholders,this.transaction.currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:yl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async rejectTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:Sl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async reset(){this.commandContext.getAllLayouts().forEach(e=>e.layoutState.elements.forEach(a=>{this.getCommandDispatcher()(new yt(a.id))})),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,r){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((C,E)=>C+E.selectedVariants.map(x=>x.priceModifier||0).reduce((x,B)=>x+B,0),0),this.workflow.steps.forEach(C=>{Bt(C,this.stepSelections)||(this.stepInitialised[C.stepName]=!1,delete this.stepMetadata[C.stepName],delete this.stepSelections[C.stepName],delete this.storage[C.stepName])});const o=this.allScenes,s=Et(o,i),l=Et(o,this.stepSelections),c=s.map(C=>C.silentSteps).flat(),A=l.map(C=>C.silentSteps).flat().filter(C=>!c.some(E=>E.stepName===C.stepName));c.forEach(C=>{Bt(C,this.stepSelections)||(this.stepInitialised[C.stepName]=!1)});const u=this.getInvalidCanvasRegions(),{stepElements:h,commands:g}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...h,[t]:a},this.removeElements(u);const m=this.workflow.steps.find(C=>C.stepName===t);m?.type===v.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(E=>E.id));const p=u.map(C=>new yt(C.id)),f=new dn(this.constructSerializableWorkflow()),S=[...g,...p,f];S.length>0&&this.commandContext.apply(new Q(S),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const b=this.getInvalidModelVariants(),P=this.modelContainer;if(P){const C=b.map(E=>P.applyModelVariant(E,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(C)}await this.onSelectionChange(),r&&await r()}async ensureStepsAreLoaded(){const e=Et(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],r=e.flat();for(const l of r)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case v.DigitalContent:a.push($a.init(l,this,this.reloadedState));break;case v.Frame:a.push(ht.init(l,this,this.reloadedState));break;case v.Illustration:a.push(Jt.init(l,this,this.reloadedState));break;case v.Material:a.push(Ua.init(l,this,this.reloadedState));break;case v.Model:a.push(La.init(l,this,this.reloadedState));break;case v.Module:this.stepSpecificServices[l.stepName]={module:await fr(l.data.module)},a.push(Va.init(l,this,this.reloadedState));break;case v.Picture:a.push(za.init(l,this,this.reloadedState));break;case v.Question:a.push(qa.init(l,this,this.reloadedState));break;case v.Shape:a.push(kt.init(l,this,this.reloadedState));break;case v.Text:a.push(q.init(l,this,this.reloadedState));break}const i=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=i.filter(l=>!!l&&!!l.command).map(l=>l.command),s=i.filter(l=>!!l&&!!l.followup).map(l=>l.followup);o&&o.length>0&&this.commandContext.apply(new Q(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 Uo(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class rt{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}}const Zt=class Zt{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){Zt.updateState.set(`${this.step.stepName}-${this.manager.getTransaction().id}`,t)}getUpdateState(){return!!Zt.updateState.get(`${this.step.stepName}-${this.manager.getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new rt(a)}getAvailableVariants(){return(this.step.option?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.step.option?.variants||[]).map(e=>new rt(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(),r=this.step.data.modelAnimation,i=this.step.data.lookAtAnimation;e?i&&e.executeCameraAnimation(i):console.warn("No preview service available, cannot execute camera animations."),a?r&&a.executeAnimation(r,t):console.warn("No model container available, cannot execute model animations.")}};Zt.updateState=new Map;let X=Zt;class Cr extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Jt.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=$(t[0].id,this.manager.getAllLayoutData()).colors,i=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=i?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=i.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 r=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?r.set(c,{browserValue:e,pmsValue:a}):r.set(c,e)}}):a?r.set(t,{browserValue:e,pmsValue:a}):r.set(t,e),Jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),r)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?Jt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}}class wr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ua.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class yr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return La.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Sr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return za.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class vr extends X{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 qa.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class Er extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return kt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return kt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return kt.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()}`),kt.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}}class br extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(t){q.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:pe.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(r=>r.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?q.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return q.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return q.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);q.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,r=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:r,defaultCleared:!1}),this.setText(r)}setText(t){const e={input:t,helperData:{}},a=q.findLayoutElements(this.manager,this.step),r=q.filterUnsupportedCharacters(t,a[0]?.fontData),i=Mt(r,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&i>this.step.data.maxLength;o||(e.input=r);const s=a.length<=0,l=s?{inputText:r,text:r}:{inputText:r};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=q.getProcessedInput(r,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:A,errorData:u,helperData:h}=q.updateInputText(r,a,this.step,this.manager);A&&this.manager.getCommandDispatcher()(A),e.helperData=h,e.errorData=u,!o&&!u&&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=q.findLayoutElements(this.manager,this.step);return q.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=Mt(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.")}getAvailableStrokeColors(){return this.step.data.strokeEnabled?q.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 q.changeStrokeColor(this.step,t,e,this.manager)}}class Br extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Ir extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return $a.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Pr extends X{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=Mt(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){Va.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(r=>r.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class Se{static get(t,e){switch(e.type){case v.DigitalContent:return new Ir(t,e,t.getStepTags(e.stepName));case v.Information:return new Br(t,e,t.getStepTags(e.stepName));case v.Question:return new vr(t,e,t.getStepTags(e.stepName));case v.Text:return new br(t,e,t.getStepTags(e.stepName));case v.Illustration:return new Cr(t,e,t.getStepTags(e.stepName));case v.Picture:return new Sr(t,e,t.getStepTags(e.stepName));case v.Shape:return new Er(t,e,t.getStepTags(e.stepName));case v.Material:return new wr(t,e,t.getStepTags(e.stepName));case v.Model:return new yr(t,e,t.getStepTags(e.stepName));case v.Frame:return new _r(t,e,t.getStepTags(e.stepName));case v.Module:return new Pr(t,e,t.getStepTags(e.stepName));default:throw new L(`Step type ${e.type} not yet supported in Core SDK`)}}}const xr=w.gql`
2217
+ `,Il=C.gql`
2218
+ mutation DeleteBundle($id: String!) {
2219
+ bundleDelete(id: $id)
2220
+ }
2221
+ `;var pe=(n=>(n.Error="Error",n.Warning="Warning",n.Info="Info",n))(pe||{});const Pl=1e3;class mn extends Ma{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},Pl)})}}class Dl{constructor(t,e,a,r,i,o,s,l,c,d,A,u,h,g=!1,p,m=!1,f=!1,v=!1){this.workflowStatePromiseQueue=new Ta(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.renderLayouts=()=>{if(!this.previewService)return;const b=this.getCommandContext().getAllLayouts(),D=this.getLayoutPreviewService()?.getAll();if(D)for(const[,w]of D)w.render(b)},this.experience=t,this.client=e,this.updateTransaction=s,this.graphQlClient=l,this.commandContext=o,this.reloadedState=h,this.transaction=c,this.readOnly=g,this.singleVariantsRenderable=f,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=a,this.stepSpecificServices={},this.profanityFilter=r,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=d,this.previewService=A,this.modelContainer=p,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},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.currentAdjustingStepId="",this.renderableContextService=u,this.renderableContextService?.setWorkflowManager(this),this.isReloadedTransaction=m,this.workflow.steps.forEach(b=>{this.stepTags[b.stepName]=b.tags??[]}),v&&(this.workflowStatePromiseQueue.enabled=!1),this.initializationPromise=this.initializeDefaultWorkflowState(a),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(b=>{throw console.error(b),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.getCommandContext().registerStateCallback(()=>{console.log("LOG: wflow manager constructor"),this.updateStateWithServer(),this.renderLayouts()}))}getTemplatingContext(){const t=this.transaction.recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const r=a.uniqueIdentifier??a.title??"";a.type===Xt.FirstName?e[r]=t?.firstName:a.type===Xt.LastName?e[r]=t?.lastName:a.type===Xt.Custom&&(a.customFieldIndex===1?e[r]=t?.customField1:a.customFieldIndex===2?e[r]=t?.customField2:a.customFieldIndex===3?e[r]=t?.customField3:a.customFieldIndex===4?e[r]=t?.customField4:a.customFieldIndex===5&&(e[r]=t?.customField5))}),e}async updateRecipient(t,e,a,r,i,o,s,l,c,d,A,u,h,g,p,m,f){if(this.transaction.recipient?.id)this.transaction.recipient={id:this.transaction.recipient.id,firstName:t??this.transaction.recipient.firstName,lastName:e??this.transaction.recipient.lastName,address:a??this.transaction.recipient.address,suburb:r??this.transaction.recipient.suburb,state:i??this.transaction.recipient.state,email:o??this.transaction.recipient.email,postalCode:s??this.transaction.recipient.postalCode,country:l??this.transaction.recipient.country,mobile:c??this.transaction.recipient.mobile,company:d??this.transaction.recipient.company,apartment:A??this.transaction.recipient.apartment,customField1:u??this.transaction.recipient.customField1,customField2:h??this.transaction.recipient.customField2,customField3:g??this.transaction.recipient.customField3,customField4:p??this.transaction.recipient.customField4,customField5:m??this.transaction.recipient.customField5,conversionConfigurationId:f||this.transaction.recipient.conversionConfigurationId},await this.graphQlClient().mutate({mutation:bl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:r||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:o||this.transaction.recipient.email,postalCode:s||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company,apartment:A||this.transaction.recipient.apartment,customField1:u||this.transaction.recipient.customField1,customField2:h||this.transaction.recipient.customField2,customField3:g||this.transaction.recipient.customField3,customField4:p||this.transaction.recipient.customField4,customField5:m||this.transaction.recipient.customField5,conversionConfigurationId:f||this.transaction.recipient.conversionConfigurationId}});else{const v=await this.graphQlClient().mutate({mutation:El,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:r,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:A,customField1:u,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f}});this.transaction.recipient={id:v?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:r,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:A,customField1:u,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f},await this.graphQlClient().mutate({mutation:Bl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id,recipientId:v.data?.recipientCreate?.id},context:{transactionOwnerId:this.transaction.transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(v=>v(this.transaction.recipient))}async fetchConversionConfiguration(){const t=this.transaction.recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=await this.graphQlClient().query({query:fo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}});e.data.conversionConfiguration&&(this.recipientConversionConfiguration=e.data.conversionConfiguration)}}async initializeDefaultWorkflowState(t){const e=()=>{const s=this.workflow.finalizeStepConfig;if(!s)return;const l=s.lookAtAnimation,c=s.modelAnimation;l&&this.previewService?.executeCameraAnimation(l),c&&this.modelContainer?.executeAnimation(c)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(s=>{this.storage[s.stepName]=s.storage||{}}),await this.fetchConversionConfiguration(),this.allScenes=await Oo(t);const r=Et(this.allScenes,this.stepSelections).map(s=>s.silentSteps).flat(),{stepElements:i,commands:o}=await this.stepElementsForIntroducedSilentSteps(r,!!this.reloadedState);this.commandContext.apply(new Q(o),!0),this.stepElements={...this.stepElements,...i},await this.ensureStepsAreLoaded(),this.isReloadedTransaction||(console.log("LOG: init default wflow state"),this.updateStateWithServer()),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}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.transaction.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}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}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))}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.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=M();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())}getMandatoryUnfulfilledSteps(){return Et(this.allScenes,this.stepSelections).flatMap(i=>i.renderableSteps).filter(i=>i.mandatory).filter(i=>!this.mandatorySteps[i.stepName]).map(i=>i.stepName)}setStepError(t,e,a){let r=!1;if(!this.validationErrors.steps.has(t)&&a)r=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const i=this.validationErrors.steps.get(t);a&&a!==i.get(e)?(r=!0,i.set(e,a)):a||(r=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}r&&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.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const a=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(a),Et(this.allScenes,this.stepSelections).filter(o=>o).map(o=>o.renderableSteps).flat().filter(o=>o.type===E.Model||o.type===E.Material).forEach(o=>{if(!o.option?.id){console.error(`Failed to read option id from step: ${o.stepName}`);return}const s=this.stepSelections[o.stepName]?.selectedVariants||[];if(s.length===0)return;const l=s[0];if(o.type===E.Model){if(!this.modelContainer)throw new U("We should always have a model container when injecting a preview!");const c=l.asset?.fileLink;if(!c){console.error(`Failed to read model url from variant: ${l.id} for step: ${o.stepName}`);return}const d=o.data;this.modelContainer.applyModelVariant(o.stepName,{model:c,contextService:this.getLayoutPreviewService()},d.replaceProductModel||!1)}else{const c=l.material;if(!c){console.error(`Failed to read material from variant: ${l.id} for step: ${o.stepName}`);return}o.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new U("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,o.option.id,c)})}}),await a.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(!De(a,this.storage)){this.storage=a;const r=new An(this.constructSerializableWorkflow());this.commandContext.apply(r,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const r={stepName:a.stepName};r.storage=this.storage[a.stepName],r.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(i=>({id:i.id,priceModifier:i.priceModifier})),t.push(r)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new mn(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new mn(async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new U("Attempted to serialize state before it was initialized.");const e=It(t.transaction),a=this.dehydrateState(e);return JSON.stringify(a)}dehydrateState(t){for(const e of Object.values(t.layouts).map(a=>a.elements).flat())e.type==="illustration"&&(delete e.cachedObjectURL,e.src&&delete e.svg),e.type==="frame"&&delete e.pattern?.svg;return this.deleteFieldNameFromObjectRecursive(t,"__typename"),t}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}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,r)=>Object.keys(a).reduce((i,o)=>{const s=[...a[o]||[]];return r.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),i[o]=s,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce((t,e)=>(Bt(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])}getInvalidModelVariants(){return this.workflow.steps.reduce((t,e)=>(e.type===E.Model&&!Bt(e,this.stepSelections)&&t.push(e.stepName),t),[])}async stepElementsForIntroducedSilentSteps(t,e){const a=this.product;if(!a)return Promise.resolve({stepElements:{},commands:[]});const r=async(c,d,A)=>{if(c.type===E.SilentIllustration){const u=await new un(c,d).trigger();return{step:c,results:u}}else if(c.type===E.ProductOverlay){const u=await new un(c,d,A).trigger();return{step:c,results:u}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||s.push(r(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.transaction.id);this.transaction.transactionShareActions=t}async updateTransactionStakeholders(){const t=await y.getShadowGraphqlClient().query({query:vo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.transaction.currentStakeholder=void 0,this.transaction.stakeholders=void 0):(this.transaction.stakeholders=t.data.transactions[0].stakeholders,this.transaction.currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:Sl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async rejectTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:vl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async reset(){this.commandContext.getAllLayouts().forEach(e=>e.layoutState.elements.forEach(a=>{this.getCommandDispatcher()(new yt(a.id))})),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,r){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((w,S)=>w+S.selectedVariants.map(P=>P.priceModifier||0).reduce((P,F)=>P+F,0),0),this.workflow.steps.forEach(w=>{Bt(w,this.stepSelections)||(this.stepInitialised[w.stepName]=!1,delete this.stepMetadata[w.stepName],delete this.stepSelections[w.stepName],delete this.storage[w.stepName])});const o=this.allScenes,s=Et(o,i),l=Et(o,this.stepSelections),c=s.map(w=>w.silentSteps).flat(),A=l.map(w=>w.silentSteps).flat().filter(w=>!c.some(S=>S.stepName===w.stepName));c.forEach(w=>{Bt(w,this.stepSelections)||(this.stepInitialised[w.stepName]=!1)});const u=this.getInvalidCanvasRegions(),{stepElements:h,commands:g}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...h,[t]:a},this.removeElements(u);const p=this.workflow.steps.find(w=>w.stepName===t);p?.type===E.Frame&&this.getWorkflowExperience().getStepById(p.stepName)?.frameService?.setTargetElements(a.map(S=>S.id));const m=u.map(w=>new yt(w.id)),f=new An(this.constructSerializableWorkflow()),v=[...g,...m,f];v.length>0&&this.commandContext.apply(new Q(v),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const b=this.getInvalidModelVariants(),D=this.modelContainer;if(D){const w=b.map(S=>D.applyModelVariant(S,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(w)}await this.onSelectionChange(),r&&await r()}async ensureStepsAreLoaded(){const e=Et(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],r=e.flat();for(const l of r)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case E.DigitalContent:a.push(Ua.init(l,this,this.reloadedState));break;case E.Frame:a.push(ht.init(l,this,this.reloadedState));break;case E.Illustration:a.push(Jt.init(l,this,this.reloadedState));break;case E.Material:a.push(La.init(l,this,this.reloadedState));break;case E.Model:a.push(Va.init(l,this,this.reloadedState));break;case E.Module:this.stepSpecificServices[l.stepName]={module:await Cr(l.data.module)},a.push(za.init(l,this,this.reloadedState));break;case E.Picture:a.push(qa.init(l,this,this.reloadedState));break;case E.Question:a.push(Ga.init(l,this,this.reloadedState));break;case E.Shape:a.push(kt.init(l,this,this.reloadedState));break;case E.Text:a.push(G.init(l,this,this.reloadedState));break}const i=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=i.filter(l=>!!l&&!!l.command).map(l=>l.command),s=i.filter(l=>!!l&&!!l.followup).map(l=>l.followup);o&&o.length>0&&this.commandContext.apply(new Q(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 Lo(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class rt{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}}const Zt=class Zt{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){Zt.updateState.set(`${this.step.stepName}-${this.manager.getTransaction().id}`,t)}getUpdateState(){return!!Zt.updateState.get(`${this.step.stepName}-${this.manager.getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new rt(a)}getAvailableVariants(){return(this.step.option?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.step.option?.variants||[]).map(e=>new rt(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(),r=this.step.data.modelAnimation,i=this.step.data.lookAtAnimation;e?i&&e.executeCameraAnimation(i):console.warn("No preview service available, cannot execute camera animations."),a?r&&a.executeAnimation(r,t):console.warn("No model container available, cannot execute model animations.")}};Zt.updateState=new Map;let Z=Zt;class wr extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Jt.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=O(t[0].id,this.manager.getAllLayoutData()).colors,i=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=i?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=i.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 r=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?r.set(c,{browserValue:e,pmsValue:a}):r.set(c,e)}}):a?r.set(t,{browserValue:e,pmsValue:a}):r.set(t,e),Jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),r)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?Jt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}}class yr extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return La.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Sr extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Va.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class vr extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){return qa.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Er 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 Ga.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class br extends Z{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return kt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return kt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return kt.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()}`),kt.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}}class Br extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(t){G.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:pe.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(r=>r.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?G.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await G.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return G.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await G.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return G.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);G.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,r=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:r,defaultCleared:!1}),this.setText(r)}setText(t){const e={input:t,helperData:{}},a=G.findLayoutElements(this.manager,this.step),r=G.filterUnsupportedCharacters(t,a[0]?.fontData),i=Mt(r,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&i>this.step.data.maxLength;o||(e.input=r);const s=a.length<=0,l=s?{inputText:r,text:r}:{inputText:r};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=G.getProcessedInput(r,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:A,errorData:u,helperData:h}=G.updateInputText(r,a,this.step,this.manager);A&&this.manager.getCommandDispatcher()(A),e.helperData=h,e.errorData=u,!o&&!u&&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=G.findLayoutElements(this.manager,this.step);return G.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=Mt(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.")}getAvailableStrokeColors(){return this.step.data.strokeEnabled?G.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 G.changeStrokeColor(this.step,t,e,this.manager)}}class Ir extends Z{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Pr 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 Ua.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Dr 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=Mt(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){za.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(r=>r.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class Se{static get(t,e){switch(e.type){case E.DigitalContent:return new Pr(t,e,t.getStepTags(e.stepName));case E.Information:return new Ir(t,e,t.getStepTags(e.stepName));case E.Question:return new Er(t,e,t.getStepTags(e.stepName));case E.Text:return new Br(t,e,t.getStepTags(e.stepName));case E.Illustration:return new wr(t,e,t.getStepTags(e.stepName));case E.Picture:return new vr(t,e,t.getStepTags(e.stepName));case E.Shape:return new br(t,e,t.getStepTags(e.stepName));case E.Material:return new yr(t,e,t.getStepTags(e.stepName));case E.Model:return new Sr(t,e,t.getStepTags(e.stepName));case E.Frame:return new Xr(t,e,t.getStepTags(e.stepName));case E.Module:return new Dr(t,e,t.getStepTags(e.stepName));default:throw new U(`Step type ${e.type} not yet supported in Core SDK`)}}}const Fr=C.gql`
2218
2222
  fragment CreateDesignTransaction on Transaction {
2219
2223
  id
2220
2224
  designName
@@ -2239,8 +2243,8 @@
2239
2243
  externalProductVariantId
2240
2244
  }
2241
2245
  }
2242
- `,Pl=w.gql`
2243
- ${xr}
2246
+ `,Fl=C.gql`
2247
+ ${Fr}
2244
2248
  mutation CreateDesign(
2245
2249
  $name: String!
2246
2250
  $layouts: [LayoutInput]!
@@ -2271,8 +2275,8 @@
2271
2275
  }
2272
2276
  }
2273
2277
  }
2274
- `,xl=w.gql`
2275
- ${xr}
2278
+ `,xl=C.gql`
2279
+ ${Fr}
2276
2280
  mutation CreateDesigns($inputs: [DesignCreateInput]!) {
2277
2281
  designCreateMany(inputs: $inputs) {
2278
2282
  id
@@ -2285,7 +2289,7 @@
2285
2289
  }
2286
2290
  }
2287
2291
  }
2288
- `;function _t(n){const t=JSON.parse(atob(n.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const Dl=async(n,t)=>{const e={};try{if(!t)throw new Error}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!_t(s)&&(e.Authorization=`Bearer ${s}`)}return(await y.getShadowGraphqlClient().mutate({mutation:Pl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:n.name,layouts:n.layouts,workflowId:n.workflowId,transactionId:n.transactionId,previewImage:n.previewImage,useThreeDimPreview:n.useThreeDimPreview,metadata:n.metadata,selectedVariants:n.selectedVariants},context:{headers:e}})).data?.designCreate},Fl=async(n,t)=>{const e={};try{if(!t)throw new Error}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!_t(s)&&(e.Authorization=`Bearer ${s}`)}return(await y.getShadowGraphqlClient().mutate({mutation:xl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:n.map(r=>({name:r.name,layouts:r.layouts,workflowId:r.workflowId,transactionId:r.transactionId,previewImage:r.previewImage,useThreeDimPreview:r.useThreeDimPreview,metadata:r.metadata,selectedVariants:r.selectedVariants}))},context:{headers:e}})).data?.designCreateMany},mn=(n,t,e)=>{const a=i=>{const o={};if(i.type==="Frame"){const s=n[i.stepName],l=i.data;if(!s||!s.image||l.hideImageInCart&&e)return o;o[`${i.stepTitle} image`]=s.image}if(i.type==="Illustration"){const s=n[i.stepName],l=i.data;if(!s||l.hideColorsInCart&&e||!s.colors)return o;if(s.colors.length>0){const c=s.colors.join(", ").toUpperCase();o[`${i.stepTitle} colors`]=c}}if(i.type==="Module"){const s=n[i.stepName],l=i.data;if(!s||s.text===void 0||s.text===null||l.hideTextInCart&&e)return o;o[`${i.stepTitle} text`]=s.text}if(i.type==="Text"){const s=n[i.stepName];if(!s)return o;const l=i.data;(!l.hideTextInCart||!e&&s.text!==void 0&&s.text!==null)&&(o[`${i.stepTitle} text`]=s.text),s.color&&(!l.hideColorInCart||!e)&&(o[`${i.stepTitle} color`]=s.color),s.strokeColor&&(!l.hideStrokeInCart||!e)&&(o[`${i.stepTitle} stroke`]=s.strokeColor)}return o},r={};return t.steps.forEach(i=>{Object.assign(r,a(i))}),r},kl=(n,t,e,a)=>{const r={};let i={};a&&(i=a);const s=t.steps.map(l=>l.stepTitle).filter((l,c,d)=>d.indexOf(l)==c);for(const l of s){if(Object.keys(n).includes(l)){const c=n[l],d=t.steps.find(A=>A.stepTitle===l);r[`${d?.stepTitle} selection`]={value:c[0].name,priceModifier:c[0].priceModifier}}for(const c of Object.keys(i))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(c)&&(r[c]={value:i[c],priceModifier:0})}return r},Dr=(n,t,e,a,r,i,o,s)=>{const l=t.basePrice||0,c=n.priceModifierTotal||0,d=kl(a,e,void 0,i),u=(k.getMap("transactionOwnerIds")||new Map).get(n.id),h={additionalExternalProductId:n.integrationProduct?.additionalExternalProductId,additionalExternalVariantId:n.integrationProduct?.additionalExternalVariantId,baseCost:l,designExternalVariants:n.designExternalVariants,designProductId:n.externalDesignProductId,designProductVariantId:n.externalDesignProductVariantId,event:"onComplete",exportedData:d,externalCartProductId:n.externalCartProductId,externalCartProductVariantId:n.externalCartProductVariantId,lineItemImageUrl:o||"",optionsCost:c,processExecutionId:s,quantity:n.quantity,transactionId:n.id,transactionOwnerId:u,weight:t.weight,workflowViewerLink:n.workflowViewerLink||"",workflowViewerReadOnlyLink:n.workflowViewerReadOnlyLink||""};return i&&(h.metadata=i),a&&(h.selectedVariants=a),r&&(h.sku=r),h},Fr=async(n,t,e,a,r,i,o,s,l,c)=>{await(async()=>{if(c!==void 0)return c;await n.outstandingRequestsPromise();const D=(k.getMap("transactionOwnerIds")||new Map).get(r.id),T=await y.getShadowGraphqlClient().query({query:_n,variables:{ids:[r.id]},fetchPolicy:"no-cache",errorPolicy:"all",context:{transactionOwnerId:D}}),et=T.data?.transactions[0].workflowState;return T.errors?(T.errors.forEach(at=>{T.errors&&console.log("Server Error:",at.message)}),null):et??null})()||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(a())),await n.updateStateWithServerImmediate(a),console.log("Server state is undefined @ Workflow completion"));const u=n.getPreviewService(),h=t?.finalizeStepConfig?.lookAtAnimation,g=u&&t.showModelOnFinishStep&&!!h,m=l&&mn(l,t,!0),p=l&&mn(l,t,!1),f=async B=>{const D={};let O=0;if(Object.keys(i).length>0)for(const T of Object.keys(i)){const et=i[T],at=t.steps.find(H=>H.stepName===T);for(let H=0;H<et.selections.length;++H){const Y=et.selections[H];if(at&&(!B||at.option&&(at.option.variants||[]).length>1&&!at.data.hideSelectionInCart&&!at.data.hideSelectionsInCart)){const vt=at.stepTitle;D[vt]?D[vt].push({id:Y.id||"",name:Y.name,priceModifier:Y.priceModifier}):D[vt]=[{id:Y.id||"",name:Y.name,priceModifier:Y.priceModifier}]}O+=Y.priceModifier}}return[D,O]},[S]=await f(!0),b=Object.fromEntries(Object.keys(S).map(B=>[B,S[B].map(D=>D.id)])),[P]=await f(!1),C=Object.fromEntries(Object.keys(P).map(B=>[B,P[B].map(D=>D.id)]));let E=await s(g,r.id);if(E){const B=await(await it(E)).blob();E=(await R.uploadAsset({name:`${r.id}-preview-image.png`,blob:B},te.Image,!0,!1)).fileLink}return{designDetails:(()=>{const B={name:o,layouts:e.map(D=>({index:D.index,panelId:D.panelId})),workflowId:t.id,transactionId:r.id,useThreeDimPreview:!!g,previewImage:E};if(p){const D=[];for(const[O,T]of Object.entries(p))D.push({key:O,value:T});B.metadata=D}if(b){const D=[];for(const[O,T]of Object.entries(C))D.push({key:O,ids:T});B.selectedVariants=D}return B})(),cartSelectionsWithPrices:S,cartMetadata:m}},kr=async(n,t,e,a,r,i,o,s,l,c,d)=>{l("workflow.steps.finish.finalize.buildingLayouts");const{designDetails:A,cartSelectionsWithPrices:u,cartMetadata:h}=await Fr(n,t,e,a,i,o,s,c,d);l("workflow.steps.finish.finalize.creatingDesign");const g=await Dl(A),m=g?.transaction?.previewImageLink;if(!g?.transaction)throw new Error("Failed to create design");l("workflow.steps.finish.finalize.updatingTransaction");const p=g.transaction;return Dr(p,r,t,u,g?.sku,h,m,g?.processExecution?.id)},Ml=async(n,t,e)=>{t("workflow.steps.finish.finalize.buildingLayouts"),await Promise.all(n.map(async s=>{await s.workflowManager.outstandingRequestsPromise()}));const r=await(async()=>{const l=await y.getShadowGraphqlClient().query({query:_n,variables:{ids:n.map(c=>c.transaction.id)},fetchPolicy:"no-cache",errorPolicy:"all"});return l.errors?(l.errors.forEach(c=>{l.errors&&console.log("Server Error:",c.message)}),null):l.data?.transactions?l.data.transactions.map(c=>c.workflowState??null):null})(),i=await Promise.all(n.map(async(s,l)=>await Fr(s.workflowManager,s.workflow,s.layouts,s.getReducerState,s.transaction,s.workflowSelections,s.designName,e??(()=>Promise.resolve(void 0)),s.workflowMetadata,r?r[l]:void 0)));t("workflow.steps.finish.finalize.creatingDesign");const o=await Fl(i.map(s=>s.designDetails));if(!o)throw new Error("Failed to create designs");return t("workflow.steps.finish.finalize.updatingTransaction"),o.map((s,l)=>{const c=n[l],d=i[l],A=s.transaction;return Dr(A,c.product,c.workflow,d.cartSelectionsWithPrices,s.sku,d.cartMetadata,A.previewImageLink,s.processExecution?.id)})};class Tl{constructor(){this.localPersistenceKey="designTransactions",this.storageMethod="Local",this.designSavedListeners=[]}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter(e=>e!==t)}async getSavedDesigns(){if(this.storageMethod==="Local"){const t=k.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new L("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find(a=>a.transactionId===t)}async addDesign(t){const a=(await this.getSavedDesigns()).filter(r=>r.transactionId!==t.transactionId);a.unshift(t),await this.setDesigns(a),this.designSavedListeners.forEach(r=>r(t))}async renameDesign(t,e){const a=await this.getSavedDesigns(),r=a.find(i=>i.transactionId===t);if(!r)throw new Error(`No saved design for transaction ${t}.`);r.title=e,await this.setDesigns(a)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter(a=>a.transactionId!==t))}async setDesigns(t){if(this.storageMethod==="Local"){k.set(this.localPersistenceKey,JSON.stringify(t));return}throw new L("Unexpected storage method requested")}}const Ie=new Tl,Nl=w.gql`
2292
+ `;function _t(n){const t=JSON.parse(atob(n.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const kl=async(n,t)=>{const e={};try{if(!t)throw new Error}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!_t(s)&&(e.Authorization=`Bearer ${s}`)}return(await y.getShadowGraphqlClient().mutate({mutation:Fl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:n.name,layouts:n.layouts,workflowId:n.workflowId,transactionId:n.transactionId,previewImage:n.previewImage,useThreeDimPreview:n.useThreeDimPreview,metadata:n.metadata,selectedVariants:n.selectedVariants},context:{headers:e}})).data?.designCreate},Ml=async(n,t)=>{const e={};try{if(!t)throw new Error}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!_t(s)&&(e.Authorization=`Bearer ${s}`)}return(await y.getShadowGraphqlClient().mutate({mutation:xl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:n.map(r=>({name:r.name,layouts:r.layouts,workflowId:r.workflowId,transactionId:r.transactionId,previewImage:r.previewImage,useThreeDimPreview:r.useThreeDimPreview,metadata:r.metadata,selectedVariants:r.selectedVariants}))},context:{headers:e}})).data?.designCreateMany},pn=(n,t,e)=>{const a=i=>{const o={};if(i.type==="Frame"){const s=n[i.stepName],l=i.data;if(!s||!s.image||l.hideImageInCart&&e)return o;o[`${i.stepTitle} image`]=s.image}if(i.type==="Illustration"){const s=n[i.stepName],l=i.data;if(!s||l.hideColorsInCart&&e||!s.colors)return o;if(s.colors.length>0){const c=s.colors.join(", ").toUpperCase();o[`${i.stepTitle} colors`]=c}}if(i.type==="Module"){const s=n[i.stepName],l=i.data;if(!s||s.text===void 0||s.text===null||l.hideTextInCart&&e)return o;o[`${i.stepTitle} text`]=s.text}if(i.type==="Text"){const s=n[i.stepName];if(!s)return o;const l=i.data;(!l.hideTextInCart||!e&&s.text!==void 0&&s.text!==null)&&(o[`${i.stepTitle} text`]=s.text),s.color&&(!l.hideColorInCart||!e)&&(o[`${i.stepTitle} color`]=s.color),s.strokeColor&&(!l.hideStrokeInCart||!e)&&(o[`${i.stepTitle} stroke`]=s.strokeColor)}return o},r={};return t.steps.forEach(i=>{Object.assign(r,a(i))}),r},Tl=(n,t,e,a)=>{const r={};let i={};a&&(i=a);const s=t.steps.map(l=>l.stepTitle).filter((l,c,d)=>d.indexOf(l)==c);for(const l of s){if(Object.keys(n).includes(l)){const c=n[l],d=t.steps.find(A=>A.stepTitle===l);r[`${d?.stepTitle} selection`]={value:c[0].name,priceModifier:c[0].priceModifier}}for(const c of Object.keys(i))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(c)&&(r[c]={value:i[c],priceModifier:0})}return r},xr=(n,t,e,a,r,i,o,s)=>{const l=t.basePrice||0,c=n.priceModifierTotal||0,d=Tl(a,e,void 0,i),u=(k.getMap("transactionOwnerIds")||new Map).get(n.id),h={additionalExternalProductId:n.integrationProduct?.additionalExternalProductId,additionalExternalVariantId:n.integrationProduct?.additionalExternalVariantId,baseCost:l,designExternalVariants:n.designExternalVariants,designProductId:n.externalDesignProductId,designProductVariantId:n.externalDesignProductVariantId,event:"onComplete",exportedData:d,externalCartProductId:n.externalCartProductId,externalCartProductVariantId:n.externalCartProductVariantId,lineItemImageUrl:o||"",optionsCost:c,processExecutionId:s,quantity:n.quantity,transactionId:n.id,transactionOwnerId:u,weight:t.weight,workflowViewerLink:n.workflowViewerLink||"",workflowViewerReadOnlyLink:n.workflowViewerReadOnlyLink||""};return i&&(h.metadata=i),a&&(h.selectedVariants=a),r&&(h.sku=r),h},kr=async(n,t,e,a,r,i,o,s,l,c)=>{await(async()=>{if(c!==void 0)return c;await n.outstandingRequestsPromise();const B=(k.getMap("transactionOwnerIds")||new Map).get(r.id),V=await y.getShadowGraphqlClient().query({query:Xn,variables:{ids:[r.id]},fetchPolicy:"no-cache",errorPolicy:"all",context:{transactionOwnerId:B}}),Y=V.data?.transactions[0].workflowState;return V.errors?(V.errors.forEach(X=>{V.errors&&console.log("Server Error:",X.message)}),null):Y??null})()||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(a())),console.log("LOG: create design details"),await n.updateStateWithServerImmediate(a),console.log("Server state is undefined @ Workflow completion"));const u=n.getPreviewService(),h=t?.finalizeStepConfig?.lookAtAnimation,g=u&&t.showModelOnFinishStep&&!!h,p=l&&pn(l,t,!0),m=l&&pn(l,t,!1),f=async F=>{const B={};let T=0;if(Object.keys(i).length>0)for(const V of Object.keys(i)){const Y=i[V],X=t.steps.find(vt=>vt.stepName===V);for(let vt=0;vt<Y.selections.length;++vt){const q=Y.selections[vt];if(X&&(!F||X.option&&(X.option.variants||[]).length>1&&!X.data.hideSelectionInCart&&!X.data.hideSelectionsInCart)){const et=X.stepTitle;B[et]?B[et].push({id:q.id||"",name:q.name,priceModifier:q.priceModifier}):B[et]=[{id:q.id||"",name:q.name,priceModifier:q.priceModifier}]}T+=q.priceModifier}}return[B,T]},[v]=await f(!0),b=Object.fromEntries(Object.keys(v).map(F=>[F,v[F].map(B=>B.id)])),[D]=await f(!1),w=Object.fromEntries(Object.keys(D).map(F=>[F,D[F].map(B=>B.id)]));let S=await s(g,r.id);if(S){const F=await(await it(S)).blob();S=(await R.uploadAsset({name:`${r.id}-preview-image.png`,blob:F},te.Image,!0,!1)).fileLink}return{designDetails:(()=>{const F={name:o,layouts:e.map(B=>({index:B.index,panelId:B.panelId})),workflowId:t.id,transactionId:r.id,useThreeDimPreview:!!g,previewImage:S};if(m){const B=[];for(const[T,V]of Object.entries(m))B.push({key:T,value:V});F.metadata=B}if(b){const B=[];for(const[T,V]of Object.entries(w))B.push({key:T,ids:V});F.selectedVariants=B}return F})(),cartSelectionsWithPrices:v,cartMetadata:p}},Mr=async(n,t,e,a,r,i,o,s,l,c,d)=>{l("workflow.steps.finish.finalize.buildingLayouts");const{designDetails:A,cartSelectionsWithPrices:u,cartMetadata:h}=await kr(n,t,e,a,i,o,s,c,d);l("workflow.steps.finish.finalize.creatingDesign");const g=await kl(A),p=g?.transaction?.previewImageLink;if(!g?.transaction)throw new Error("Failed to create design");l("workflow.steps.finish.finalize.updatingTransaction");const m=g.transaction;return xr(m,r,t,u,g?.sku,h,p,g?.processExecution?.id)},Nl=async(n,t,e)=>{t("workflow.steps.finish.finalize.buildingLayouts"),await Promise.all(n.map(async s=>{await s.workflowManager.outstandingRequestsPromise()}));const r=await(async()=>{const l=await y.getShadowGraphqlClient().query({query:Xn,variables:{ids:n.map(c=>c.transaction.id)},fetchPolicy:"no-cache",errorPolicy:"all"});return l.errors?(l.errors.forEach(c=>{l.errors&&console.log("Server Error:",c.message)}),null):l.data?.transactions?l.data.transactions.map(c=>c.workflowState??null):null})(),i=await Promise.all(n.map(async(s,l)=>await kr(s.workflowManager,s.workflow,s.layouts,s.getReducerState,s.transaction,s.workflowSelections,s.designName,e??(()=>Promise.resolve(void 0)),s.workflowMetadata,r?r[l]:void 0)));t("workflow.steps.finish.finalize.creatingDesign");const o=await Ml(i.map(s=>s.designDetails));if(!o)throw new Error("Failed to create designs");return t("workflow.steps.finish.finalize.updatingTransaction"),o.map((s,l)=>{const c=n[l],d=i[l],A=s.transaction;return xr(A,c.product,c.workflow,d.cartSelectionsWithPrices,s.sku,d.cartMetadata,A.previewImageLink,s.processExecution?.id)})};class Ql{constructor(){this.localPersistenceKey="designTransactions",this.storageMethod="Local",this.designSavedListeners=[]}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter(e=>e!==t)}async getSavedDesigns(){if(this.storageMethod==="Local"){const t=k.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new U("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find(a=>a.transactionId===t)}async addDesign(t){const a=(await this.getSavedDesigns()).filter(r=>r.transactionId!==t.transactionId);a.unshift(t),await this.setDesigns(a),this.designSavedListeners.forEach(r=>r(t))}async renameDesign(t,e){const a=await this.getSavedDesigns(),r=a.find(i=>i.transactionId===t);if(!r)throw new Error(`No saved design for transaction ${t}.`);r.title=e,await this.setDesigns(a)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter(a=>a.transactionId!==t))}async setDesigns(t){if(this.storageMethod==="Local"){k.set(this.localPersistenceKey,JSON.stringify(t));return}throw new U("Unexpected storage method requested")}}const Ie=new Ql,Rl=C.gql`
2289
2293
  mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
2290
2294
  transactionAddStakeholder(id: $id, details: $details, type: $type) {
2291
2295
  id
@@ -2299,7 +2303,7 @@
2299
2303
  }
2300
2304
  }
2301
2305
  }
2302
- `,Ql=w.gql`
2306
+ `,Ol=C.gql`
2303
2307
  mutation AddAddressToTransaction(
2304
2308
  $transactionId: String!
2305
2309
  $streetAddress: String
@@ -2321,13 +2325,13 @@
2321
2325
  id
2322
2326
  }
2323
2327
  }
2324
- `,Rl=w.gql`
2328
+ `,$l=C.gql`
2325
2329
  mutation AddOrganizationToTransaction($transactionId: String!, $organizationName: String!) {
2326
2330
  organizationAttachToTransaction(transactionId: $transactionId, organizationName: $organizationName) {
2327
2331
  id
2328
2332
  }
2329
2333
  }
2330
- `;var Mr=(n=>(n.QuantityChanged="QuantityChanged",n.PriceBreakChanged="PriceBreakChanged",n))(Mr||{});class Tr{constructor(t,e){if(this.cachedStepHandles=new Map,this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=In(async()=>{await Ie.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async r=>new Promise((i,o)=>{try{r.toBlob(s=>{if(s){const l=URL.createObjectURL(s);i(l)}})}catch(s){o(s)}}),!e.workflow)throw new Error("No Workflow ID provided.");this.client=t;const a=e.layouts;this.commandContext=new or,this.commandContext.initialize(a,e.reloadedState),this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Il(this,t,e.workflow,e.product.profanities?.map(r=>r.word)||[],a,this.commandContext,r=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(r)},e.graphQlClient,e.transaction,e.product,e.previewService,e.renderableContextService,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(r=>{const i=r.traversableScenes.map(o=>{const s=o.renderableSteps.map(l=>l.stepName);return{id:o.name,title:o.title,renderableSteps:s,workflowScene:o}});this.renderableScenes=i,this.renderableSceneCallbacks.forEach(o=>o(i))}),this.currentPriceBreak=this.priceBreakToBeApplied()}async attachAddress(t,e,a,r,i,o){await this.graphQlClient().mutate({mutation:Ql,variables:{transactionId:this.getWorkflowManager().getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:Rl,variables:{transactionId:this.getWorkflowManager().getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.workflowManager.getWorkflow(),r=a?.finalizeStepConfig?.lookAtAnimation;if(t){if(!r)throw new Error("Failed to generate cart preview image!");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,r)||""}let i=2048;e&&e<=2048&&(i=e);const o=ft(i,i),s=this.commandContext.getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=s.find(b=>b.layoutState?.layout.panelId===c?.name)||s[0],A=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},u=this.commandContext.getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new Oe("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),m=We(u.layoutState.layout,u.layoutState.elements,{renderingConfiguration:{purpose:Nt.Print,region:{left:A.x,top:A.y,width:A.width,height:A.height},templatingContext:g}}),p=Rn(m);await(await ba.Pith.from(h,p,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:ft,createImage:le,DOMParser:xa(),fetch})).render();const S=await this.getCanvasObjectURLAsync(o);return o.toDataURL(S)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find(i=>i.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const r=Se.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,r),r}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>Bt(e.getRaw(),this.getWorkflowManager().getStepSelections())))}getScenes(){return this.getWorkflowManager().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(r=>{a+=r.selections.reduce((i,o)=>i+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getWorkflowManager().getProduct().basePrice||0,e);if(t){const r=this.getAdditionalProductPriceSubunits(e)||0;return a+r}return a}getAdditionalProductPriceSubunits(t){const e=this.getWorkflowManager().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(),r=t*a;return Math.ceil(r)}priceBreakToBeApplied(){const t=(this.getWorkflowManager().getProduct().priceBreaks||[]).sort((r,i)=>-(r.minQty-i.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((r,i)=>r+i.getQuantity(),0);for(const r of t)if(r.minQty<=a)return r.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=>t.getWorkflowManager().getTransaction().id!==this.getWorkflowManager().getTransaction().id&&t.getWorkflowManager().getProduct().id===this.getWorkflowManager().getProduct().id)}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const r=await t.getGlobalProperties(),i=a?.map(c=>c.getId()),o=this.getSteps().filter(c=>i===void 0||i.includes(c.getId())),s=e.getSteps(),l=c=>r.find(d=>d.getRawProperty().name===c.aspectName);o.forEach(c=>{const d=new Set,A=c.getRaw().globalPropertyAspectConfigurations;A!==void 0&&(A.forEach(u=>d.add(JSON.stringify(u))),s.forEach(u=>{const h=u.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const m=l(g),p=d.has(JSON.stringify(g));if(p&&m?.getType()==="Option"){const f=u.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(p&&m?.getType()==="Text"){const f=u.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return Se.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter(e=>e.type===t).map(e=>Se.get(this.getWorkflowManager(),e))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find(a=>a.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(a=>this.getWorkflowManager().getWorkflow().steps.find(r=>r.stepName===a)).filter(a=>this.stepHasHandle(a)).map(a=>Se.get(this.getWorkflowManager(),a))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:Nl,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(r=>r.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const r=k.getMap("transactionCustomerIds")||new Map;r.set(this.getWorkflowManager().getTransaction().id,a.customer.id),k.setMap("transactionCustomerIds",r)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){if(!this.getCommandContext().getState())throw new L("State undefined!");const r={title:await(async()=>{if(t)return t;const i=this.getWorkflowManager().getTransaction().id,s=(await Ie.getSavedDesigns()).find(l=>l.transactionId===i)?.title;return s||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await Ie.addDesign(r),r}async copy(){const t=It(this.getCommandContext().getState());if(!t)throw new L("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflowManager().getWorkflow(),r=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!r)throw new L("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:r,workflowId:a.id,workflowState:e})}async onDesignFinished(t,e=!0){const a=this.workflowManager.getTransaction();return a.completed?(await this.graphQlClient().mutate({mutation:vo,variables:{transactionId:a.id}}),{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:a.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""}):kr(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),()=>this.commandContext.getState(),this.workflowManager.getProduct(),a,this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),r=>e?this.createPreviewImage(r,1024):Promise.resolve(void 0),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==v.SilentIllustration&&t.type!==v.ProductOverlay}getExportedStepData(){const t=this.getWorkflowManager().getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),r=[];return t.steps.forEach(i=>{const o=i.stepName,s=e[o],l=a[o]?.selections[0],c={stepId:o,title:i.stepTitle,properties:[]};if(l&&$l(i,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){r.push(c);return}switch(i.type){case v.Frame:{const d=i.data,A=s;A.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:A.image,priceModifier:0})}break;case v.Illustration:{const d=i.data,A=s;if(A&&A.colors&&A.colors.length>0&&d.displayColorsOnFinishStep){const u=A.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:u,priceModifier:0})}}break;case v.Module:{const d=i.data,A=s;A&&A.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:A.text,priceModifier:0})}break;case v.Text:{const d=i.data,A=s;A&&A.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:A.text,priceModifier:0}),A&&A.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:A.color,priceModifier:0})}}r.push(c)}),r.filter(i=>i.properties&&i.properties.length>0)}getQuantity(){return this.getWorkflowManager().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.getWorkflowManager().getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getWorkflowManager().getTransaction();await this.graphQlClient().mutate({mutation:mo,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(r=>r!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const Ol=n=>{if([v.Question,v.Frame,v.Illustration,v.Material,v.Model,v.Picture,v.Shape,v.Text].includes(n.type)){const e=n.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},$l=(n,t)=>{if(!Ol(n))return!1;if(n.option&&(n.option.variants||[]).length>1){const e=t[n.stepName];return!!(e&&e.selections.length>0)}return!1},Ul=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],Ll=async(n,t,e)=>{const a=t.data,r=e.data.baseUrl,i=a.assetUrl.replace("localhost","localstack"),o=r.slice(0,4)==="http"?"":"https://",s=new URL(o+r);s.searchParams.append("video",nn(JSON.stringify([{href:i}]))),s.pathname=s.pathname+(s.pathname.slice(-1)==="/"?"":"/");const l=s.toString(),d=`data:image/svg+xml;base64,${nn(await Bn.toString(l,{type:"svg"}))}`,A=h=>{const g=n.find(p=>p.panelId===h.panelId);if(!g)throw new j(h);const m=M();return new z({id:m,src:d,type:F.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},g)},u=e.data.regions;try{return u.map(A)}catch(h){return console.error(h),[]}},Vl=async(n,t,e,a)=>{const r=e.data,i=r.assetUrl,o=await pa(i);try{const s=gs(r,a.option);s&&(t[a.stepName]={selectedVariants:[s]});const l=async c=>{const d=await lr(c,s?.asset?.fileLink),A=await he(d),u=M(),h=n.find(m=>m.panelId===c.panelId);if(!h)throw new j(c);const g=Na(o,A,{scale:r.scale,left:r.x,top:r.y},a.data.forceImageCover);return[new z({id:u,path:A.path,type:F.Frame,forceImageCover:a.data.forceImageCover,x:c.left,y:c.top,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,rotation:c.rotation,scaleX:c.width/A.width,scaleY:c.height/A.height,pattern:{id:`${u}-pattern`,src:o.src,x:g.x,y:g.y,width:o.width,height:o.height,rotation:0,scaleX:g.zoom,scaleY:g.zoom,svg:o.svg,colors:o.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(s){return console.error(s),[]}},zl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(C=>C.id===r.illustrationVariantId)||ue(i);if(!o)return console.error(`No variant with ID: ${r.illustrationVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${r.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${r.illustrationVariantId}`),[];const l=await tt(s,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],A=d?.length>0?d[0]:"",g=lt().parseFromString(A,"image/svg+xml").firstElementChild;if(!g)return console.error("Failed to read SVG."),[];Ve(g);const m={};Ot(g,C=>{Ul.includes(C.tagName)&&!C.attributes.getNamedItem("fill")&&C.setAttribute("fill","#000000");const E=C.attributes.getNamedItem("fill");if(E&&E.value!=="none"){const B=E.value,O=`spiff-fill-${B.replace(/\W/g,"")}`;C.classList.add(O),m[O]={browserValue:B}}const x=C.attributes.getNamedItem("stroke");if(x&&x.value!=="none"){const B=x.value,O=`spiff-stroke-${B.replace(/\W/g,"")}`;C.classList.add(O),m[O]={browserValue:B}}});const f=St().serializeToString(g),S=r.colors;if(S){for(const[C,E]of Object.entries(m))for(const x of Object.keys(S))if(E.browserValue===x){m[C]={browserValue:S[x]};break}}const b=C=>{const E=n.find(B=>B.panelId===C.panelId);if(!E)throw new j(C);const x=M();return new z({colors:m,id:x,svg:f,type:F.Illustration,y:C.top,x:C.left,rotation:C.rotation,width:C.width,height:C.height,layer:C.layer,layerIndex:C.layerIndex,immutable:C.immutable},E)},P=a.data.regions;try{return P.map(b)}catch(C){return console.error(C),[]}},ql=async(n,t,e)=>{const a=await fr(e.data.module),r=t.data,i=(s,l)=>{const c=n.find(A=>A.panelId===l.panelId);if(!c)throw new j(l);const d=M();return new z({colors:{},id:d,svg:s,type:F.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},o=e.data.regions;try{return o.map(s=>i(a.svgPrint(r.text,s),s))}catch(s){return console.error(s),[]}},Gl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(d=>d.id===r.pictureVariantId)||ue(i);if(!o)return console.error(`No variant with ID: ${r.pictureVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${r.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${r.pictureVariantId}`),[];const l=d=>{const A=n.find(h=>h.panelId===d.panelId);if(!A)throw new j(d);const u=M();return new z({id:u,src:s,type:F.Image,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable,preserveAspectRatio:"none"},A)},c=a.data.regions;try{return c.map(l)}catch(d){return console.error(d),[]}},Wl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(c=>c.id===r.colorVariantId)||ue(i);if(!o)return console.error(`No variant with ID: ${r.colorVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=c=>{const d=n.find(m=>m.panelId===c.panelId);if(!d)throw new j(c);const A=`
2334
+ `;var Tr=(n=>(n.QuantityChanged="QuantityChanged",n.PriceBreakChanged="PriceBreakChanged",n))(Tr||{});class Nr{constructor(t,e){if(this.cachedStepHandles=new Map,this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=Pn(async()=>{await Ie.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async r=>new Promise((i,o)=>{try{r.toBlob(s=>{if(s){const l=URL.createObjectURL(s);i(l)}})}catch(s){o(s)}}),!e.workflow)throw new Error("No Workflow ID provided.");this.client=t;const a=e.layouts;this.commandContext=new sr,this.commandContext.initialize(a,e.reloadedState),this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Dl(this,t,e.workflow,e.product.profanities?.map(r=>r.word)||[],a,this.commandContext,r=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(r)},e.graphQlClient,e.transaction,e.product,e.previewService,e.renderableContextService,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(r=>{const i=r.traversableScenes.map(o=>{const s=o.renderableSteps.map(l=>l.stepName);return{id:o.name,title:o.title,renderableSteps:s,workflowScene:o}});this.renderableScenes=i,this.renderableSceneCallbacks.forEach(o=>o(i))}),this.currentPriceBreak=this.priceBreakToBeApplied()}async attachAddress(t,e,a,r,i,o){await this.graphQlClient().mutate({mutation:Ol,variables:{transactionId:this.getWorkflowManager().getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:$l,variables:{transactionId:this.getWorkflowManager().getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.workflowManager.getWorkflow(),r=a?.finalizeStepConfig?.lookAtAnimation;if(t){if(!r)throw new Error("Failed to generate cart preview image!");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,r)||""}let i=2048;e&&e<=2048&&(i=e);const o=ft(i,i),s=this.commandContext.getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=s.find(b=>b.layoutState?.layout.panelId===c?.name)||s[0],A=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},u=this.commandContext.getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new Oe("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),p=We(u.layoutState.layout,u.layoutState.elements,{renderingConfiguration:{purpose:Nt.Print,region:{left:A.x,top:A.y,width:A.width,height:A.height},templatingContext:g}}),m=On(p);await(await Ba.Pith.from(h,m,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:ft,createImage:le,DOMParser:Fa(),fetch})).render();const v=await this.getCanvasObjectURLAsync(o);return o.toDataURL(v)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find(i=>i.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const r=Se.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,r),r}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>Bt(e.getRaw(),this.getWorkflowManager().getStepSelections())))}getScenes(){return this.getWorkflowManager().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(r=>{a+=r.selections.reduce((i,o)=>i+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getWorkflowManager().getProduct().basePrice||0,e);if(t){const r=this.getAdditionalProductPriceSubunits(e)||0;return a+r}return a}getAdditionalProductPriceSubunits(t){const e=this.getWorkflowManager().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(),r=t*a;return Math.ceil(r)}priceBreakToBeApplied(){const t=(this.getWorkflowManager().getProduct().priceBreaks||[]).sort((r,i)=>-(r.minQty-i.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((r,i)=>r+i.getQuantity(),0);for(const r of t)if(r.minQty<=a)return r.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=>t.getWorkflowManager().getTransaction().id!==this.getWorkflowManager().getTransaction().id&&t.getWorkflowManager().getProduct().id===this.getWorkflowManager().getProduct().id)}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const r=await t.getGlobalProperties(),i=a?.map(c=>c.getId()),o=this.getSteps().filter(c=>i===void 0||i.includes(c.getId())),s=e.getSteps(),l=c=>r.find(d=>d.getRawProperty().name===c.aspectName);o.forEach(c=>{const d=new Set,A=c.getRaw().globalPropertyAspectConfigurations;A!==void 0&&(A.forEach(u=>d.add(JSON.stringify(u))),s.forEach(u=>{const h=u.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=u.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(m&&p?.getType()==="Text"){const f=u.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return Se.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter(e=>e.type===t).map(e=>Se.get(this.getWorkflowManager(),e))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find(a=>a.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(a=>this.getWorkflowManager().getWorkflow().steps.find(r=>r.stepName===a)).filter(a=>this.stepHasHandle(a)).map(a=>Se.get(this.getWorkflowManager(),a))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:Rl,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(r=>r.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const r=k.getMap("transactionCustomerIds")||new Map;r.set(this.getWorkflowManager().getTransaction().id,a.customer.id),k.setMap("transactionCustomerIds",r)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){if(!this.getCommandContext().getState())throw new U("State undefined!");const r={title:await(async()=>{if(t)return t;const i=this.getWorkflowManager().getTransaction().id,s=(await Ie.getSavedDesigns()).find(l=>l.transactionId===i)?.title;return s||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await Ie.addDesign(r),r}async copy(){const t=It(this.getCommandContext().getState());if(!t)throw new U("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflowManager().getWorkflow(),r=this.getWorkflowManager().getTransaction().integrationProduct?.id;if(!r)throw new U("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:r,workflowId:a.id,workflowState:e})}async onDesignFinished(t,e=!0){const a=this.workflowManager.getTransaction();return a.completed?(await this.graphQlClient().mutate({mutation:Eo,variables:{transactionId:a.id}}),{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:a.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""}):Mr(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),()=>this.commandContext.getState(),this.workflowManager.getProduct(),a,this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),r=>e?this.createPreviewImage(r,1024):Promise.resolve(void 0),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==E.SilentIllustration&&t.type!==E.ProductOverlay}getExportedStepData(){const t=this.getWorkflowManager().getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),r=[];return t.steps.forEach(i=>{const o=i.stepName,s=e[o],l=a[o]?.selections[0],c={stepId:o,title:i.stepTitle,properties:[]};if(l&&Ll(i,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){r.push(c);return}switch(i.type){case E.Frame:{const d=i.data,A=s;A.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:A.image,priceModifier:0})}break;case E.Illustration:{const d=i.data,A=s;if(A&&A.colors&&A.colors.length>0&&d.displayColorsOnFinishStep){const u=A.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:u,priceModifier:0})}}break;case E.Module:{const d=i.data,A=s;A&&A.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:A.text,priceModifier:0})}break;case E.Text:{const d=i.data,A=s;A&&A.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:A.text,priceModifier:0}),A&&A.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:A.color,priceModifier:0})}}r.push(c)}),r.filter(i=>i.properties&&i.properties.length>0)}getQuantity(){return this.getWorkflowManager().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.getWorkflowManager().getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getWorkflowManager().getTransaction();await this.graphQlClient().mutate({mutation:po,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(r=>r!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const Ul=n=>{if([E.Question,E.Frame,E.Illustration,E.Material,E.Model,E.Picture,E.Shape,E.Text].includes(n.type)){const e=n.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Ll=(n,t)=>{if(!Ul(n))return!1;if(n.option&&(n.option.variants||[]).length>1){const e=t[n.stepName];return!!(e&&e.selections.length>0)}return!1},Vl=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],zl=async(n,t,e)=>{const a=t.data,r=e.data.baseUrl,i=a.assetUrl.replace("localhost","localstack"),o=r.slice(0,4)==="http"?"":"https://",s=new URL(o+r);s.searchParams.append("video",rn(JSON.stringify([{href:i}]))),s.pathname=s.pathname+(s.pathname.slice(-1)==="/"?"":"/");const l=s.toString(),d=`data:image/svg+xml;base64,${rn(await In.toString(l,{type:"svg"}))}`,A=h=>{const g=n.find(m=>m.panelId===h.panelId);if(!g)throw new H(h);const p=M();return new z({id:p,src:d,type:x.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},g)},u=e.data.regions;try{return u.map(A)}catch(h){return console.error(h),[]}},ql=async(n,t,e,a)=>{const r=e.data,i=r.assetUrl,o=await fa(i);try{const s=ms(r,a.option);s&&(t[a.stepName]={selectedVariants:[s]});const l=async c=>{const d=await cr(c,s?.asset?.fileLink),A=await he(d),u=M(),h=n.find(p=>p.panelId===c.panelId);if(!h)throw new H(c);const g=Qa(o,A,{scale:r.scale,left:r.x,top:r.y},a.data.forceImageCover);return[new z({id:u,path:A.path,type:x.Frame,forceImageCover:a.data.forceImageCover,x:c.left,y:c.top,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,rotation:c.rotation,scaleX:c.width/A.width,scaleY:c.height/A.height,pattern:{id:`${u}-pattern`,src:o.src,x:g.x,y:g.y,width:o.width,height:o.height,rotation:0,scaleX:g.zoom,scaleY:g.zoom,svg:o.svg,colors:o.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(s){return console.error(s),[]}},Gl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(w=>w.id===r.illustrationVariantId)||ue(i);if(!o)return console.error(`No variant with ID: ${r.illustrationVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${r.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${r.illustrationVariantId}`),[];const l=await at(s,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],A=d?.length>0?d[0]:"",g=lt().parseFromString(A,"image/svg+xml").firstElementChild;if(!g)return console.error("Failed to read SVG."),[];Ve(g);const p={};Ot(g,w=>{Vl.includes(w.tagName)&&!w.attributes.getNamedItem("fill")&&w.setAttribute("fill","#000000");const S=w.attributes.getNamedItem("fill");if(S&&S.value!=="none"){const F=S.value,T=`spiff-fill-${F.replace(/\W/g,"")}`;w.classList.add(T),p[T]={browserValue:F}}const P=w.attributes.getNamedItem("stroke");if(P&&P.value!=="none"){const F=P.value,T=`spiff-stroke-${F.replace(/\W/g,"")}`;w.classList.add(T),p[T]={browserValue:F}}});const f=St().serializeToString(g),v=r.colors;if(v){for(const[w,S]of Object.entries(p))for(const P of Object.keys(v))if(S.browserValue===P){p[w]={browserValue:v[P]};break}}const b=w=>{const S=n.find(F=>F.panelId===w.panelId);if(!S)throw new H(w);const P=M();return new z({colors:p,id:P,svg:f,type:x.Illustration,y:w.top,x:w.left,rotation:w.rotation,width:w.width,height:w.height,layer:w.layer,layerIndex:w.layerIndex,immutable:w.immutable},S)},D=a.data.regions;try{return D.map(b)}catch(w){return console.error(w),[]}},Wl=async(n,t,e)=>{const a=await Cr(e.data.module),r=t.data,i=(s,l)=>{const c=n.find(A=>A.panelId===l.panelId);if(!c)throw new H(l);const d=M();return new z({colors:{},id:d,svg:s,type:x.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},o=e.data.regions;try{return o.map(s=>i(a.svgPrint(r.text,s),s))}catch(s){return console.error(s),[]}},jl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(d=>d.id===r.pictureVariantId)||ue(i);if(!o)return console.error(`No variant with ID: ${r.pictureVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${r.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${r.pictureVariantId}`),[];const l=d=>{const A=n.find(h=>h.panelId===d.panelId);if(!A)throw new H(d);const u=M();return new z({id:u,src:s,type:x.Image,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable,preserveAspectRatio:"none"},A)},c=a.data.regions;try{return c.map(l)}catch(d){return console.error(d),[]}},Hl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(c=>c.id===r.colorVariantId)||ue(i);if(!o)return console.error(`No variant with ID: ${r.colorVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=c=>{const d=n.find(p=>p.panelId===c.panelId);if(!d)throw new H(c);const A=`
2331
2335
  <svg
2332
2336
  xmlns="http://www.w3.org/2000/svg"
2333
2337
  xmlnsXlink="http://www.w3.org/1999/xlink"
@@ -2347,8 +2351,8 @@
2347
2351
  fill="${o?.color}"
2348
2352
  />
2349
2353
  </svg>
2350
- `,h={"spiff-fill-shape":{browserValue:o.color||"#000000"}},g=M();return new z({colors:h,id:g,svg:A,type:F.Illustration,y:c.top,x:c.left,rotation:c.rotation,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,immutable:c.immutable},d)},l=a.data.regions;try{return l.map(s)}catch(c){return console.error(c),[]}},jl=async(n,t,e)=>{const a=[],i=t.type===v.ProductOverlay?e||t.data.asset?.fileLink||"":t.data.asset?.fileLink||"",s=i.endsWith(".jpeg")||i.endsWith(".jpg")||i.endsWith(".png")?F.Image:(i.endsWith(".svg"),F.Illustration),l=t.data.regions;if(s==="image")try{l.forEach(c=>{const d=n.find(u=>u.panelId===c.panelId);if(!d)throw new j(c);const A={id:M(),src:i,type:s,y:c.top,x:c.left,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,productOverlay:t.type===v.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:c.rotation,excludeFromExport:t.data.excludeFromPrint,preserveAspectRatio:"none"};a.push(new z(A,d))})}catch(c){console.error(c)}else{const c=await tt(i,!0),d=A=>{const u=/<svg.*?<\/svg>/s,h=A.match(u)||[],g=h?.length>0?h[0]:"",f=lt().parseFromString(g,"image/svg+xml").firstElementChild;if(!f)throw new bt("Failed to read SVG.");return Ve(f),St().serializeToString(f)};l.forEach(A=>{const u=n.find(g=>g.panelId===A.panelId);if(!u)throw new j(A);const h={id:M(),src:i,asset_key:i,svg:d(c),colors:{},type:s,y:A.top,x:A.left,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,scaleX:1,scaleY:1,rotation:A.rotation,productOverlay:t.type===v.ProductOverlay?!0:void 0,excludeFromExport:t.data.excludeFromPrint};a.push(new z(h,u))})}return a},Hl=async(n,t,e,a)=>{const r=[],i=e.data,o=30,s=p=>p.vertical?"center":p.textAlign||"center",l=()=>{const p=a.option;if(!p)return;const f=p.variants?.find(b=>b.id===i.fontVariantId)||ue(p);if(!f||!f.asset)return;t[a.stepName]={selectedVariants:[f]};const S=f.asset.fileLink;if(S)return S},d=await(async()=>{const p=l();if(!p)return;const f=await xt(p);return{assetUrl:p,name:f.names.fullName.en}})(),A=(a.data.replaceableText?a.data.replaceableText.replace("{{}}",i.text):i.text)||"",u=ke(A,{vertical:a.data.vertical,uppercase:a.data.uppercase}),h=async p=>{const f=p.colorOption;return f?W.getDefaultVariant(f)?.color:void 0},g=i.color||await h(a.data),m=a.data.regions;for(const p of m){const f=n.find(b=>b.panelId===p.panelId);if(!f)continue;const S={stepName:e.name,id:M(),align:s(a.data),curved:a.data.curved,fill:i.color||g||"#000000",fontData:d,fontSize:a.data.size||o,height:p.height,layer:p.layer,layerIndex:p.layerIndex,paths:a.data.paths,rotation:p.rotation,text:u,type:F.Textbox,vertical:a.data.vertical,verticalAlign:a.data.verticalAlign||"middle",width:p.width,x:p.left,y:p.top};if(d){const[b,P]=Kt(a.data.size||o,d,p,[ke(u,{vertical:a.data.vertical,uppercase:a.data.uppercase})],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});r.push(new z({...S,fontSize:b,text:S.curved?S.text:(P||[]).join(`
2351
- `)},f))}else r.push(new z(S,f))}return r},Yl=(n,t)=>n.conditions?n.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const r=a.selectedVariants;return e.requiredVariantSelections.some(i=>r.find(o=>o.id===i)!==void 0)}return!1}):!0,Nr=async(n,t,e,a)=>{const r=[],i={};for(const o of n){const s=t.steps.find(l=>l.stepName===o.name);if(s)switch(s.type){case v.DigitalContent:r.push(...await Ll(e,o,s));break;case v.Frame:case v.Photo:r.push(...await Vl(e,i,o,s));break;case v.Illustration:r.push(...await zl(e,i,o,s));break;case v.Module:r.push(...await ql(e,o,s));break;case v.Picture:r.push(...await Gl(e,i,o,s));break;case v.Shape:r.push(...await Wl(e,i,o,s));break;case v.Text:r.push(...await Hl(e,i,o,s));break}}for(const o of t.steps)o.type!==v.SilentIllustration&&o.type!==v.ProductOverlay||Yl(o,i)&&r.push(...await jl(e,o,a));return r};class Jl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Xl(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Kl=()=>new Promise((n,t)=>{try{const a=ft().getContext("webgl2");n(!!a)}catch{n(!1)}}),_l=Kl();class Xl{constructor(t,e,a,r,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Ma(2),this.id=t,this.name=e,this.service=a,this.panelSize=r,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=It(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new Zl(this.getID(),a,await _l,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class Zl extends ka{constructor(t,e,a,r,i,o){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=r,this.layouts=i,this.getWorkflowManager=o}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,r=e/t.height,i=Math.min(a,r);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){const t=this.layouts.find(g=>g.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,r=t.layoutState.layout.height,i=a===1||r===1?{width:1,height:1}:this.getDynamicTextureResolution(),o=i.width,s=i.height;let l,c;if(this.nonPOTSupport){const g=o/s;a/r<g?(l=o,c=r*(o/a)):(l=a*(s/r),c=s);const p=this.resizeFit({width:l,height:c});l=p.width,c=p.height}else l=i.width,c=i.height;const d=this.getWorkflowManager?.()?.getTemplatingContext(),A=We(t.layoutState.layout,e,{renderingConfiguration:{purpose:Nt.ThreeD,templatingContext:d}}),u=Rn(A),h=await ba.Pith.from(this.ctx,u,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:ft,createImage:le,DOMParser:xa(),fetch});h.resize(l,c),await h.render(),this.onRender()}}const tc=(n,t)=>{const e=[];return n.forEach(a=>{const r=t.steps.find(i=>i.stepName===a.stepName);r?.type===v.Text&&a.stepAspectType==="Text"&&e.push({name:r.stepName,data:{text:a.value}})}),e},ec=async(n,t,e,a)=>{let r={serializableWorkflow:{steps:[]},layouts:{}};r=new Q(e.map(l=>new Oa(l))).apply(r);const o=await Nr(n,t,e,a);return new Q(o).apply(r)};class ac{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 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.conditions.some(a=>{const r=e.aspects.find(i=>i.name===a.targetAspectName);return r?a.requiredVariantSelections.some(i=>i===r.value):!1})}async createHandle(t){switch(t.type){case U.FileUpload:return new Qr(this.bundle,t).initialize();case U.ColorOption:return new ya(this.bundle,t,t.entityId?await W.getOption(t.entityId):void 0);case U.Option:{const e=t.entityId?await W.getOption(t.entityId):void 0;return e?.type==="Color"?new ya(this.bundle,t,e):new Wa(this.bundle,t,e)}case U.Text:return new Rr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class je{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)}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(r=>r.getStepsConditionallyActive().filter(i=>i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:i.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Qr extends je{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await W.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 tt(t?.fileLink),a=await Qa(t?.fileLink),r=a.width,i=a.height,o=await ot(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:r,height:i,aspect:r/i,svg:o.svg,colors:o.colors};dt.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,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Qe.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(),r=await R.removeBackgroundFromAsset(e),o={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:r.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,r.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(r,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),r}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return R.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Le(ze(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 R.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return R.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(),r=a.getAspectStorage(this.property.name);if(r?.useOriginalAsset===t)return;const i={...r,useOriginalAsset:t},o=t?r?.originalAssetKey:r?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",i)];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(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await R.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(r){if(this.updateSharedStepStorage({...r}),r.colors){const i=new Map(r.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);this.getSharedSteps(t).forEach(o=>{o.changeColors(i)})}}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 ot(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(i=>{i.changeColors(a)});const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...r,colors:Object.entries(t).map(([i,o])=>({key:i,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,r=!0){const o=this.getSharedSteps(e).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,a,r)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(r=>{if(r.getOverrideGlobalPropertyConfiguration(this.property.type))return;r.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(r.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Rr extends je{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 r=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(r)}}class Wa extends je{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new rt(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 rt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new rt(e):void 0}}getAvailableVariants(){return(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.optionResource?.variants||[]).map(e=>new rt(e))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(r=>r.id===e);return a?this.applyVariantSelection(new rt(a),t):Promise.resolve()}async applyVariantSelection(t,e){const r=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(r)}}class ya extends Wa{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 Promise.resolve();const a=this.optionResource?.variants?.find(i=>i.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new rt(a),t);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;r&&this.setCustomColor(r)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(o=>{switch(o.getType()){case v.Shape:return o.selectVariant(t);case v.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case v.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getCurrentVariant()?.getColor()&&this.getCurrentVariant().getColor().toLowerCase()==="#custom"&&this.getSharedSteps().forEach(a=>a.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=(n,t,e,a)=>n.flatMap(r=>r.getSteps()).filter(r=>r.getGlobalPropertyAspects(t).includes(e)&&r.getType()===a),rc=(n,t,e)=>{const r=nc(n,t,e,v.Illustration).map(i=>{const o=i.getCurrentVariant()?.getAssetResource(),s=i.getColors();return!o?.assetConfiguration||!s?0:Object.getOwnPropertyNames(s).length});return Math.max(...r)};function Sa(n,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!oc(a))return a;if(Array.isArray(a))return Sa(a,t);let r={};for(const[i,o]of Object.entries(a))r[i]=ic(o)?o:Sa(o,t);return gi(r,t)}return Array.isArray(n)?n.map(e):e(n)}function ic(n){return n==null}function oc(n){return typeof n=="object"&&!Array.isArray(n)&&n!==null}function Or(n){const t=new Map;return n?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}function ve(n){return Sa(n,["__typename"])}class sc{constructor(t,e,a,r,i){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const o=i?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=ve(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=ve(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=r}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=Or(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=It(this.globalPropertyState);this.globalPropertyState={...ve(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(r=>r.name===t&&r.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,r){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 i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=It(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(r){const l=s.find(c=>c.channel===r);if(l)l.value=e,l.type=i.type,l.channel=r,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(r===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:i.type,storage:a!==null?a:void 0,channel:r})}}else{const l=s[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:r});xe(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 r=this.configuration.aspects.find(s=>s.name===t);if(!r)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=It(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=r.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=r.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:r.type,storage:e!==null?e:void 0,channel:a});xe(i,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await y.getShadowGraphqlClient().mutate({mutation:Ys,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 U.FileUpload:{a.fileUpload=e.storage;break}case U.Option:{a.option=e.storage;break}case U.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=ve(t.data.globalPropertyStateUpdate);else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:Hs,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 lc{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find(o=>o.transactionId===t.getWorkflowManager().getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const r=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=r.position,i.rotation=r.rotation,i.scale=r.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const r=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(o=>o.transactionId===r);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:r,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer()||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,r=this.state.transactions.find(l=>l.transactionId===a),i=r?.transforms?.[e];if(!i)return;const o=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),s=t.getWorkflowManager().getModelContainer();s.position=o.position,s.rotation=o.rotation,s.scale=o.scale,r.activeTransform=e}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)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const cc=w.gql`
2354
+ `,h={"spiff-fill-shape":{browserValue:o.color||"#000000"}},g=M();return new z({colors:h,id:g,svg:A,type:x.Illustration,y:c.top,x:c.left,rotation:c.rotation,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,immutable:c.immutable},d)},l=a.data.regions;try{return l.map(s)}catch(c){return console.error(c),[]}},Yl=async(n,t,e)=>{const a=[],i=t.type===E.ProductOverlay?e||t.data.asset?.fileLink||"":t.data.asset?.fileLink||"",s=i.endsWith(".jpeg")||i.endsWith(".jpg")||i.endsWith(".png")?x.Image:(i.endsWith(".svg"),x.Illustration),l=t.data.regions;if(s==="image")try{l.forEach(c=>{const d=n.find(u=>u.panelId===c.panelId);if(!d)throw new H(c);const A={id:M(),src:i,type:s,y:c.top,x:c.left,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,productOverlay:t.type===E.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:c.rotation,excludeFromExport:t.data.excludeFromPrint,preserveAspectRatio:"none"};a.push(new z(A,d))})}catch(c){console.error(c)}else{const c=await at(i,!0),d=A=>{const u=/<svg.*?<\/svg>/s,h=A.match(u)||[],g=h?.length>0?h[0]:"",f=lt().parseFromString(g,"image/svg+xml").firstElementChild;if(!f)throw new bt("Failed to read SVG.");return Ve(f),St().serializeToString(f)};l.forEach(A=>{const u=n.find(g=>g.panelId===A.panelId);if(!u)throw new H(A);const h={id:M(),src:i,asset_key:i,svg:d(c),colors:{},type:s,y:A.top,x:A.left,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,scaleX:1,scaleY:1,rotation:A.rotation,productOverlay:t.type===E.ProductOverlay?!0:void 0,excludeFromExport:t.data.excludeFromPrint};a.push(new z(h,u))})}return a},Jl=async(n,t,e,a)=>{const r=[],i=e.data,o=30,s=m=>m.vertical?"center":m.textAlign||"center",l=()=>{const m=a.option;if(!m)return;const f=m.variants?.find(b=>b.id===i.fontVariantId)||ue(m);if(!f||!f.asset)return;t[a.stepName]={selectedVariants:[f]};const v=f.asset.fileLink;if(v)return v},d=await(async()=>{const m=l();if(!m)return;const f=await Dt(m);return{assetUrl:m,name:f.names.fullName.en}})(),A=(a.data.replaceableText?a.data.replaceableText.replace("{{}}",i.text):i.text)||"",u=ke(A,{vertical:a.data.vertical,uppercase:a.data.uppercase}),h=async m=>{const f=m.colorOption;return f?j.getDefaultVariant(f)?.color:void 0},g=i.color||await h(a.data),p=a.data.regions;for(const m of p){const f=n.find(b=>b.panelId===m.panelId);if(!f)continue;const v={stepName:e.name,id:M(),align:s(a.data),curved:a.data.curved,fill:i.color||g||"#000000",fontData:d,fontSize:a.data.size||o,height:m.height,layer:m.layer,layerIndex:m.layerIndex,paths:a.data.paths,rotation:m.rotation,text:u,type:x.Textbox,vertical:a.data.vertical,verticalAlign:a.data.verticalAlign||"middle",width:m.width,x:m.left,y:m.top};if(d){const[b,D]=Kt(a.data.size||o,d,m,[ke(u,{vertical:a.data.vertical,uppercase:a.data.uppercase})],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});r.push(new z({...v,fontSize:b,text:v.curved?v.text:(D||[]).join(`
2355
+ `)},f))}else r.push(new z(v,f))}return r},Kl=(n,t)=>n.conditions?n.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const r=a.selectedVariants;return e.requiredVariantSelections.some(i=>r.find(o=>o.id===i)!==void 0)}return!1}):!0,Qr=async(n,t,e,a)=>{const r=[],i={};for(const o of n){const s=t.steps.find(l=>l.stepName===o.name);if(s)switch(s.type){case E.DigitalContent:r.push(...await zl(e,o,s));break;case E.Frame:case E.Photo:r.push(...await ql(e,i,o,s));break;case E.Illustration:r.push(...await Gl(e,i,o,s));break;case E.Module:r.push(...await Wl(e,o,s));break;case E.Picture:r.push(...await jl(e,i,o,s));break;case E.Shape:r.push(...await Hl(e,i,o,s));break;case E.Text:r.push(...await Jl(e,i,o,s));break}}for(const o of t.steps)o.type!==E.SilentIllustration&&o.type!==E.ProductOverlay||Kl(o,i)&&r.push(...await Yl(e,o,a));return r};class _l{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new tc(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Xl=()=>new Promise((n,t)=>{try{const a=ft().getContext("webgl2");n(!!a)}catch{n(!1)}}),Zl=Xl();class tc{constructor(t,e,a,r,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Ta(2),this.id=t,this.name=e,this.service=a,this.panelSize=r,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=It(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new ec(this.getID(),a,await Zl,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class ec extends Ma{constructor(t,e,a,r,i,o){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=r,this.layouts=i,this.getWorkflowManager=o}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,r=e/t.height,i=Math.min(a,r);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){const t=this.layouts.find(g=>g.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,r=t.layoutState.layout.height,i=a===1||r===1?{width:1,height:1}:this.getDynamicTextureResolution(),o=i.width,s=i.height;let l,c;if(this.nonPOTSupport){const g=o/s;a/r<g?(l=o,c=r*(o/a)):(l=a*(s/r),c=s);const m=this.resizeFit({width:l,height:c});l=m.width,c=m.height}else l=i.width,c=i.height;const d=this.getWorkflowManager?.()?.getTemplatingContext(),A=We(t.layoutState.layout,e,{renderingConfiguration:{purpose:Nt.ThreeD,templatingContext:d}}),u=On(A),h=await Ba.Pith.from(this.ctx,u,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:ft,createImage:le,DOMParser:Fa(),fetch});h.resize(l,c),await h.render(),this.onRender()}}const ac=(n,t)=>{const e=[];return n.forEach(a=>{const r=t.steps.find(i=>i.stepName===a.stepName);r?.type===E.Text&&a.stepAspectType==="Text"&&e.push({name:r.stepName,data:{text:a.value}})}),e},nc=async(n,t,e,a)=>{let r={serializableWorkflow:{steps:[]},layouts:{}};r=new Q(e.map(l=>new $a(l))).apply(r);const o=await Qr(n,t,e,a);return new Q(o).apply(r)};class rc{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 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.conditions.some(a=>{const r=e.aspects.find(i=>i.name===a.targetAspectName);return r?a.requiredVariantSelections.some(i=>i===r.value):!1})}async createHandle(t){switch(t.type){case $.FileUpload:return new Rr(this.bundle,t).initialize();case $.ColorOption:return new Sa(this.bundle,t,t.entityId?await j.getOption(t.entityId):void 0);case $.Option:{const e=t.entityId?await j.getOption(t.entityId):void 0;return e?.type==="Color"?new Sa(this.bundle,t,e):new ja(this.bundle,t,e)}case $.Text:return new Or(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class je{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)}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(r=>r.getStepsConditionallyActive().filter(i=>i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:i.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Rr extends je{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await j.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 at(t?.fileLink),a=await Ra(t?.fileLink),r=a.width,i=a.height,o=await ot(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:r,height:i,aspect:r/i,svg:o.svg,colors:o.colors};dt.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,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Qe.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(),r=await R.removeBackgroundFromAsset(e),o={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:r.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,r.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(r,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),r}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return R.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Le(ze(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 R.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return R.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(),r=a.getAspectStorage(this.property.name);if(r?.useOriginalAsset===t)return;const i={...r,useOriginalAsset:t},o=t?r?.originalAssetKey:r?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",i)];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(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await R.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(r){if(this.updateSharedStepStorage({...r}),r.colors){const i=new Map(r.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);this.getSharedSteps(t).forEach(o=>{o.changeColors(i)})}}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 ot(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(i=>{i.changeColors(a)});const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...r,colors:Object.entries(t).map(([i,o])=>({key:i,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,r=!0){const o=this.getSharedSteps(e).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,a,r)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(r=>{if(r.getOverrideGlobalPropertyConfiguration(this.property.type))return;r.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(r.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Or extends je{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 r=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(r)}}class ja extends je{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new rt(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 rt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new rt(e):void 0}}getAvailableVariants(){return(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.optionResource?.variants||[]).map(e=>new rt(e))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(r=>r.id===e);return a?this.applyVariantSelection(new rt(a),t):Promise.resolve()}async applyVariantSelection(t,e){const r=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(r)}}class Sa extends ja{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 Promise.resolve();const a=this.optionResource?.variants?.find(i=>i.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new rt(a),t);const r=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;r&&this.setCustomColor(r)}async applyColorVariant(t,e,a){const i=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(i)}setCustomColor(t){this.getCurrentVariant()?.getColor()&&this.getCurrentVariant().getColor().toLowerCase()==="#custom"&&this.getSharedSteps().forEach(a=>a.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 ic=(n,t,e,a)=>n.flatMap(r=>r.getSteps()).filter(r=>r.getGlobalPropertyAspects(t).includes(e)&&r.getType()===a),oc=(n,t,e)=>{const r=ic(n,t,e,E.Illustration).map(i=>{const o=i.getCurrentVariant()?.getAssetResource(),s=i.getColors();return!o?.assetConfiguration||!s?0:Object.getOwnPropertyNames(s).length});return Math.max(...r)};function va(n,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!lc(a))return a;if(Array.isArray(a))return va(a,t);let r={};for(const[i,o]of Object.entries(a))r[i]=sc(o)?o:va(o,t);return mi(r,t)}return Array.isArray(n)?n.map(e):e(n)}function sc(n){return n==null}function lc(n){return typeof n=="object"&&!Array.isArray(n)&&n!==null}function $r(n){const t=new Map;return n?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}function ve(n){return va(n,["__typename"])}class cc{constructor(t,e,a,r,i){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const o=i?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=ve(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=ve(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=r}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=$r(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=It(this.globalPropertyState);this.globalPropertyState={...ve(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(r=>r.name===t&&r.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,r){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 i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=It(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(r){const l=s.find(c=>c.channel===r);if(l)l.value=e,l.type=i.type,l.channel=r,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(r===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:i.type,storage:a!==null?a:void 0,channel:r})}}else{const l=s[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:r});De(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 r=this.configuration.aspects.find(s=>s.name===t);if(!r)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=It(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=r.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=r.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:r.type,storage:e!==null?e:void 0,channel:a});De(i,this.globalPropertyState)||(await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await y.getShadowGraphqlClient().mutate({mutation:Js,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 $.FileUpload:{a.fileUpload=e.storage;break}case $.Option:{a.option=e.storage;break}case $.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=ve(t.data.globalPropertyStateUpdate);else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:Ys,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 dc{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find(o=>o.transactionId===t.getWorkflowManager().getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const r=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=r.position,i.rotation=r.rotation,i.scale=r.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const r=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(o=>o.transactionId===r);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:r,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer()||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,r=this.state.transactions.find(l=>l.transactionId===a),i=r?.transforms?.[e];if(!i)return;const o=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),s=t.getWorkflowManager().getModelContainer();s.position=o.position,s.rotation=o.rotation,s.scale=o.scale,r.activeTransform=e}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)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const Ac=C.gql`
2352
2356
  query GetManyMetafields($entityIds: [String!]!) {
2353
2357
  metafieldsMany(entityIds: $entityIds) {
2354
2358
  id
@@ -2359,14 +2363,14 @@
2359
2363
  }
2360
2364
  }
2361
2365
  }
2362
- `;class dc{constructor(){this.internalMap=new Map}async requestKeysForEntity(t,e){const a=new Map;return await this.ensureIdsArePresent([t]),e.forEach(r=>{const i=this.requestKeyForEntityIfAvailable(t,r);i&&a.set(r,i)}),a}async ensureIdsArePresent(t){if(t.every(a=>this.internalMap.has(a)))return;const e=await y.getShadowGraphqlClient().query({query:cc,errorPolicy:"all",variables:{entityIds:t.filter(a=>!this.internalMap.has(a))}});t.forEach((a,r)=>{const i=e.data.metafieldsMany[r];this.internalMap.set(a,i.map(o=>({key:o.metafieldConfiguration.name,value:o.value})))})}async requestKeyForEntity(t,e){if(!this.internalMap.has(t))return;let a=this.internalMap.get(t);const r=a.find(i=>i.key===e);return r||(await this.ensureIdsArePresent([t]),a=this.internalMap.get(t)),r?JSON.parse(r.value):void 0}requestKeyForEntityIfAvailable(t,e){if(!this.internalMap.has(t))return;const r=this.internalMap.get(t).find(i=>i.key===e);if(r)return JSON.parse(r.value)}}const $r=new dc;var Ur=(n=>(n.Default="Default",n.Name="Name",n.Price="Price",n))(Ur||{});class ja{constructor(t){this.fullFetched=!1,this.collection=t;const e=this.collection.productCollectionProducts;e&&e.length>0&&(this.fullFetched=!0)}getId(){return this.collection.id}getName(){return this.collection.name}getDescription(){return this.collection.description||""}getDispatchStartDate(){if(this.collection.dispatchStartDate)return new Date(this.collection.dispatchStartDate)}getDispatchEndDate(){if(this.collection.dispatchEndDate)return new Date(this.collection.dispatchEndDate)}getImage(){return this.collection.image}getProducts(){if(!this.collection.productCollectionProducts)throw new Error("Failed to find products on collection. Ensure you fetch them first!");return this.collection.productCollectionProducts.filter(t=>!!t.product).map(t=>new Ht(t))}async fetchProducts(t){if(this.fullFetched)return this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new Ht(a));const e=await y.getShadowGraphqlClient().query({query:tl,variables:{id:this.getId(),productIds:t},errorPolicy:"all"});return t||(this.fullFetched=!0),this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new Ht(a))}async filterProducts(t,e,a,r){const i=await y.getShadowGraphqlClient().query({query:el,errorPolicy:"all",variables:{id:this.getId(),filters:t?{link:"And",metafields:t}:void 0,tags:e?{include:e.include??[],exclude:e.exclude??[]}:void 0,sortKey:a,sortDescending:r}});if(!i.data?.productCollections||i.data?.productCollections.length===0)throw new Error("Failed to filter product collection products.");const o=this.getProducts(),s=i.data.productCollections[0].productCollectionProducts.map(l=>l.product.id);return o.filter(l=>s.includes(l.getId()))}async fetchProductsFeed(t,e,a,r,i,o,s,l){if(this.fullFetched){const u=await(a?this.filterProducts(a):this.fetchProducts());return{total:u.length,items:u.slice(t,t+e)}}const c=new AbortController,{signal:d}=c,A=y.getShadowGraphqlClient().watchQuery({query:al,variables:{id:this.getId(),limit:e,offset:t,productFilters:a?{link:"And",metafields:a}:void 0,productWorkflowFilters:l?{link:"And",metafields:l}:void 0,tags:r?{include:r.include??[],exclude:r.exclude??[]}:void 0,sortKey:i,sortDescending:o,quickSearch:s},errorPolicy:"all",fetchPolicy:"cache-first",returnPartialData:!0,context:{fetchOptions:{signal:d}}});return new Promise(u=>{let h=!1;const g=A.subscribe({next(m){if(h||m.partial&&(!m.data.productCollections||m.data.productCollections.length===0||!m.data.productCollections[0].productCollectionProductsFeed?.items||m.data.productCollections[0].productCollectionProductsFeed?.items.length===0))return;c.abort(),h=!0,g.unsubscribe();const p=m.data.productCollections?.[0].productCollectionProductsFeed?.items.filter(f=>!!f.product).map(f=>new Ht(It(f)))||[];u({items:p,total:m.data.productCollections?.[0].productCollectionProductsFeed?.total??0})},error(){h||(h=!0,g.unsubscribe(),u({items:[],total:0}))}})})}getTransformCollection(){if(this.collection.transformCollection)return new Lr(this.collection.transformCollection)}getResource(){return this.collection}}class Ht{constructor(t){this.product=t.product,this.productResource=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t,e){const r=(this.product.integrationProducts||[]).find(i=>{const o=i.integration?.type,s=i.integration?.type===t,l=e?i.integration?.externalIntegrationId===e:!0;return o&&s&&l});if(!r)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return r}getCurrentIntegration(){const e=(this.product.integrationProducts||[]).find(a=>a.integration?.isCurrent);if(!e)throw new Error(`Product: ${this.productResource.id} is not linked to this current integration. This is generally due to a configuration error.`);return e}getDefaultWorkflow(){const t=this.product.workflows;if(t===void 0)throw new gt("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(t.length===0)throw new gt("Called getDefaultWorkflow() but no workflows on requested product. Ensure at least 1 workflow is assigned to this product.");const e=this.productResource.workflowId;if(e){const a=t.find(r=>r.workflowName===e);if(a)return new Tt(a)}if(t.length===1)return console.warn("Called getDefaultWorkflow() but no default was configured. There is only one workflow available so we will fall back to using this!"),new Tt(t[0]);throw new gt("Called getDefaultWorkflow() but no default workflow is configured for the requested product. Multiple workflows exist so we can't assume!")}getAllWorkflows(){if((this.product.workflows||[]).length===0)throw new gt("No workflows on configured product. Ensure at least 1 workflow is assigned to this product.");return this.product.workflows.sort((e,a)=>(e.index??0)-(a.index??0)).map(e=>new Tt(e))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(t){const e=this.product.basePrice||0;if(!t)return e;if(!t.integrationType&&!t.externalId&&!t.integrationId)throw new Error("You must provide at least one of the following fields on the includeAdditionalProduct object: integrationType, externalId, integrationId");let a;return t.integrationId?a=this.product.integrationProducts?.find(r=>r.integration?.id===t.integrationId):t.externalId?a=this.product.integrationProducts?.find(r=>r.integration?.externalIntegrationId===t.externalId):a=this.product.integrationProducts?.find(r=>r.integration?.type===t.integrationType),a?.additionalIntegrationProduct?.product?e+(a.additionalIntegrationProduct.product.basePrice||0):e}async requestMetafields(t){return $r.requestKeysForEntity(this.product.id,t)}}class Tt{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class Lr{constructor(t){this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(t=>new Vr(t))}}class Vr{constructor(t){this.transform=t}getId(){return this.transform.id}getName(){return this.transform.name}get(){return{position:this.transform.position,rotation:this.transform.rotation,scale:this.transform.scale}}}const Ac=w.gql`
2366
+ `;class uc{constructor(){this.internalMap=new Map}async requestKeysForEntity(t,e){const a=new Map;return await this.ensureIdsArePresent([t]),e.forEach(r=>{const i=this.requestKeyForEntityIfAvailable(t,r);i&&a.set(r,i)}),a}async ensureIdsArePresent(t){if(t.every(a=>this.internalMap.has(a)))return;const e=await y.getShadowGraphqlClient().query({query:Ac,errorPolicy:"all",variables:{entityIds:t.filter(a=>!this.internalMap.has(a))}});t.forEach((a,r)=>{const i=e.data.metafieldsMany[r];this.internalMap.set(a,i.map(o=>({key:o.metafieldConfiguration.name,value:o.value})))})}async requestKeyForEntity(t,e){if(!this.internalMap.has(t))return;let a=this.internalMap.get(t);const r=a.find(i=>i.key===e);return r||(await this.ensureIdsArePresent([t]),a=this.internalMap.get(t)),r?JSON.parse(r.value):void 0}requestKeyForEntityIfAvailable(t,e){if(!this.internalMap.has(t))return;const r=this.internalMap.get(t).find(i=>i.key===e);if(r)return JSON.parse(r.value)}}const Ur=new uc;var Lr=(n=>(n.Default="Default",n.Name="Name",n.Price="Price",n))(Lr||{});class Ha{constructor(t){this.fullFetched=!1,this.collection=t;const e=this.collection.productCollectionProducts;e&&e.length>0&&(this.fullFetched=!0)}getId(){return this.collection.id}getName(){return this.collection.name}getDescription(){return this.collection.description||""}getDispatchStartDate(){if(this.collection.dispatchStartDate)return new Date(this.collection.dispatchStartDate)}getDispatchEndDate(){if(this.collection.dispatchEndDate)return new Date(this.collection.dispatchEndDate)}getImage(){return this.collection.image}getProducts(){if(!this.collection.productCollectionProducts)throw new Error("Failed to find products on collection. Ensure you fetch them first!");return this.collection.productCollectionProducts.filter(t=>!!t.product).map(t=>new Ht(t))}async fetchProducts(t){if(this.fullFetched)return this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new Ht(a));const e=await y.getShadowGraphqlClient().query({query:el,variables:{id:this.getId(),productIds:t},errorPolicy:"all"});return t||(this.fullFetched=!0),this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new Ht(a))}async filterProducts(t,e,a,r){const i=await y.getShadowGraphqlClient().query({query:al,errorPolicy:"all",variables:{id:this.getId(),filters:t?{link:"And",metafields:t}:void 0,tags:e?{include:e.include??[],exclude:e.exclude??[]}:void 0,sortKey:a,sortDescending:r}});if(!i.data?.productCollections||i.data?.productCollections.length===0)throw new Error("Failed to filter product collection products.");const o=this.getProducts(),s=i.data.productCollections[0].productCollectionProducts.map(l=>l.product.id);return o.filter(l=>s.includes(l.getId()))}async fetchProductsFeed(t,e,a,r,i,o,s,l){if(this.fullFetched){const u=await(a?this.filterProducts(a):this.fetchProducts());return{total:u.length,items:u.slice(t,t+e)}}const c=new AbortController,{signal:d}=c,A=y.getShadowGraphqlClient().watchQuery({query:nl,variables:{id:this.getId(),limit:e,offset:t,productFilters:a?{link:"And",metafields:a}:void 0,productWorkflowFilters:l?{link:"And",metafields:l}:void 0,tags:r?{include:r.include??[],exclude:r.exclude??[]}:void 0,sortKey:i,sortDescending:o,quickSearch:s},errorPolicy:"all",fetchPolicy:"cache-first",returnPartialData:!0,context:{fetchOptions:{signal:d}}});return new Promise(u=>{let h=!1;const g=A.subscribe({next(p){if(h||p.partial&&(!p.data.productCollections||p.data.productCollections.length===0||!p.data.productCollections[0].productCollectionProductsFeed?.items||p.data.productCollections[0].productCollectionProductsFeed?.items.length===0))return;c.abort(),h=!0,g.unsubscribe();const m=p.data.productCollections?.[0].productCollectionProductsFeed?.items.filter(f=>!!f.product).map(f=>new Ht(It(f)))||[];u({items:m,total:p.data.productCollections?.[0].productCollectionProductsFeed?.total??0})},error(){h||(h=!0,g.unsubscribe(),u({items:[],total:0}))}})})}getTransformCollection(){if(this.collection.transformCollection)return new Vr(this.collection.transformCollection)}getResource(){return this.collection}}class Ht{constructor(t){this.product=t.product,this.productResource=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t,e){const r=(this.product.integrationProducts||[]).find(i=>{const o=i.integration?.type,s=i.integration?.type===t,l=e?i.integration?.externalIntegrationId===e:!0;return o&&s&&l});if(!r)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return r}getCurrentIntegration(){const e=(this.product.integrationProducts||[]).find(a=>a.integration?.isCurrent);if(!e)throw new Error(`Product: ${this.productResource.id} is not linked to this current integration. This is generally due to a configuration error.`);return e}getDefaultWorkflow(){const t=this.product.workflows;if(t===void 0)throw new gt("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(t.length===0)throw new gt("Called getDefaultWorkflow() but no workflows on requested product. Ensure at least 1 workflow is assigned to this product.");const e=this.productResource.workflowId;if(e){const a=t.find(r=>r.workflowName===e);if(a)return new Tt(a)}if(t.length===1)return console.warn("Called getDefaultWorkflow() but no default was configured. There is only one workflow available so we will fall back to using this!"),new Tt(t[0]);throw new gt("Called getDefaultWorkflow() but no default workflow is configured for the requested product. Multiple workflows exist so we can't assume!")}getAllWorkflows(){if((this.product.workflows||[]).length===0)throw new gt("No workflows on configured product. Ensure at least 1 workflow is assigned to this product.");return this.product.workflows.sort((e,a)=>(e.index??0)-(a.index??0)).map(e=>new Tt(e))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(t){const e=this.product.basePrice||0;if(!t)return e;if(!t.integrationType&&!t.externalId&&!t.integrationId)throw new Error("You must provide at least one of the following fields on the includeAdditionalProduct object: integrationType, externalId, integrationId");let a;return t.integrationId?a=this.product.integrationProducts?.find(r=>r.integration?.id===t.integrationId):t.externalId?a=this.product.integrationProducts?.find(r=>r.integration?.externalIntegrationId===t.externalId):a=this.product.integrationProducts?.find(r=>r.integration?.type===t.integrationType),a?.additionalIntegrationProduct?.product?e+(a.additionalIntegrationProduct.product.basePrice||0):e}async requestMetafields(t){return Ur.requestKeysForEntity(this.product.id,t)}}class Tt{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class Vr{constructor(t){this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(t=>new zr(t))}}class zr{constructor(t){this.transform=t}getId(){return this.transform.id}getName(){return this.transform.name}get(){return{position:this.transform.position,rotation:this.transform.rotation,scale:this.transform.scale}}}const hc=C.gql`
2363
2367
  ${me(!1)}
2364
2368
  query GetProductCollections($ids: [String!]!) {
2365
2369
  productCollections(ids: $ids) {
2366
2370
  ...ProductCollectionFields
2367
2371
  }
2368
2372
  }
2369
- `,uc=async n=>(await y.getShadowGraphqlClient().query({query:Ac,errorPolicy:"all",variables:{ids:n}})).data?.productCollections?.map(e=>new ja(e));class hc{constructor(){this.listeners={}}on(t,e){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e)}off(t,e){this.listeners[t]&&(this.listeners[t]=this.listeners[t].filter(a=>a!==e))}emit(t,e){if(this.listeners[t])for(const a of this.listeners[t])a(e)}clear(t){if(t)delete this.listeners[t];else for(const e in this.listeners)delete this.listeners[e]}}const gc=w.gql`
2373
+ `,gc=async n=>(await y.getShadowGraphqlClient().query({query:hc,errorPolicy:"all",variables:{ids:n}})).data?.productCollections?.map(e=>new Ha(e));class mc{constructor(){this.listeners={}}on(t,e){this.listeners[t]||(this.listeners[t]=[]),this.listeners[t].push(e)}off(t,e){this.listeners[t]&&(this.listeners[t]=this.listeners[t].filter(a=>a!==e))}emit(t,e){if(this.listeners[t])for(const a of this.listeners[t])a(e)}clear(t){if(t)delete this.listeners[t];else for(const e in this.listeners)delete this.listeners[e]}}const pc=C.gql`
2370
2374
  mutation AddAddressToBundle(
2371
2375
  $bundleId: String!
2372
2376
  $streetAddress: String
@@ -2388,26 +2392,26 @@
2388
2392
  id
2389
2393
  }
2390
2394
  }
2391
- `,mc=w.gql`
2395
+ `,fc=C.gql`
2392
2396
  mutation AddOrganizationToBundle($bundleId: String!, $organizationName: String!) {
2393
2397
  organizationAttachToBundle(bundleId: $bundleId, organizationName: $organizationName) {
2394
2398
  id
2395
2399
  }
2396
2400
  }
2397
- `,pc=w.gql`
2401
+ `,Cc=C.gql`
2398
2402
  mutation GenerateQuoteId($id: String!) {
2399
2403
  bundleGenerateQuoteId(id: $id) {
2400
2404
  id
2401
2405
  quoteId
2402
2406
  }
2403
2407
  }
2404
- `;class ra{constructor(t,e,a,r,i,o){this.workflowExperiences=[],this.eventEmitter=new hc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new lc(e.bundleStateData);const s=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=s?.id,this.globalPropertyStateManager=new sc(this.id,this.ownerId,s,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new ac(this),this.setPreviewService(a);const l=new Promise((c,d)=>{if(o?.readonly){c([]);return}console.log("Setting default global variants.");const A=this.globalPropertyStateManager.getGlobalPropertyState();A?this.globalPropertyHandleService.getHandles().then(u=>{const h=u.map(g=>{if(g.getType()===U.ColorOption||g.getType()===U.Option){const m=g;if(!A.aspects.find(f=>f.name===m.getName()))return m.initDefaultVariant()}});Promise.all(h).then(c).catch(d)}):(console.log("Attempted to set global default variant before state was initialized."),c([]))});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(e.transactions?.map(c=>c.id)||[],{...r,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}getTemplate(){return this.template}async generateQuoteId(){const e=(await y.getShadowGraphqlClient().mutate({mutation:pc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,r,i,o){await y.getShadowGraphqlClient().mutate({mutation:gc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await y.getShadowGraphqlClient().mutate({mutation:mc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const a of t.aspects){const r=a?.name;this.getGlobalPropertyStateManager().setAspect(r,a.value)}for(const a of t.aspects){const r=a?.name,i=e.find(o=>o.getName()===r);if(i)switch(a.type){case U.FileUpload:{const o=i,s=await De([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case U.ColorOption:{const o=i,l=o.getAllVariants().find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case U.Option:{const o=i,l=o.getAllVariants().find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case U.Text:{await i.setText(a.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===U.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,r)=>a+r,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new ja(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(v.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const r of a){const i=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===r);if(i&&i.type===U.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=rc(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",r),d=[...new Set(s.map(u=>u.number))];if(d.length>c)for(const u of d){const h=this.getGlobalPropertyStateManager(),g=l.find(m=>m.channelNumber===u);g&&await h.setAspect(r,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getWorkflowManager().getTransaction().id),a=e.map(s=>this.workflowExperiences.find(l=>l.getWorkflowManager().getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getWorkflowManager().getTransaction().id).join(", "));const r=k.getMap("transactionOwnerIds")||new Map,i=e.map(s=>r.get(s));await y.getShadowGraphqlClient().mutate({mutation:sl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(k.getMap("transactionOwnerIds")||new Map).get(a);await y.getShadowGraphqlClient().mutate({mutation:ol,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const r=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);if(r.setBundle(void 0),this.previewService&&r.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await y.getShadowGraphqlClient().mutate({mutation:ll,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,o])=>({key:i,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),r.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(r=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===r.id));if(e.some(r=>r===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((r,i)=>e[i]===-1).map(r=>r.id).join(", "));const a=t.map(r=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===r.id),1)[0]);a.forEach(r=>r.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(r=>r.checkForPriceBreakChanges()),this.previewService&&a.forEach(r=>r.getWorkflowManager().ejectFromPreviewService()),t.forEach(r=>this.bundleStateManager.removeStateForTransaction(r.id)),await y.getShadowGraphqlClient().mutate({mutation:cl,variables:{id:this.id,transactionIds:t.map(r=>r.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,i])=>({key:r,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(r=>r.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const r=await this.getGlobalProperties();await Promise.all(r.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const a=await y.getShadowGraphqlClient().mutate({mutation:dl,variables:{id:this.id,details:t,type:e||ee.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const r=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(r)}async removeStakeholder(t){if(!(await y.getShadowGraphqlClient().mutate({mutation:Al,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ul,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await y.getShadowGraphqlClient().query({query:hn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await y.getShadowGraphqlClient().query({query:hn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){this.completed&&await y.getShadowGraphqlClient().mutate({mutation:fl,variables:{bundleId:this.id}});const a=await Ml(this.workflowExperiences.map(r=>({workflowManager:r.getWorkflowManager(),workflow:r.getWorkflowManager().getWorkflow(),layouts:r.getWorkflowManager().getLayouts(),getReducerState:()=>r.getCommandContext().getState(),product:r.getWorkflowManager().getProduct(),transaction:r.getWorkflowManager().getTransaction(),workflowSelections:r.getWorkflowManager().getWorkflowSelections(),designName:r.getWorkflowManager().getWorkflow().name,workflowMetadata:r.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(r,i)=>{const o=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===i);return o?e(o,r):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getWorkflowManager().getTransaction().id,amountToOrder:e.getWorkflowManager().getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await y.getShadowGraphqlClient().mutate({mutation:ml,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await y.getShadowGraphqlClient().mutate({mutation:gl(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),this.globalConfigurationPropertyId=a?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const r=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===r.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(r=>({type:"transaction",transactionId:r})),e);if(a.forEach(r=>r.setBundle(this)),a.forEach(r=>r.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const r of a)await this.injectExperienceIntoPreviewService(r)}async updateBundle(){if(!(await y.getShadowGraphqlClient().mutate({mutation:il,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await y.getShadowGraphqlClient().mutate({mutation:hl,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const a=await this.globalPropertyHandleService.getHandles(),r=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(r,i),this.checkMandatoryHandlesChanged(t,i);const o=a.map(s=>{if(s.getType()===U.ColorOption||s.getType()===U.Option){const l=s;if(!e.aspects.find(d=>d.name===l.getName()))return l.initDefaultVariant()}});await Promise.all(o),await Promise.all(i.map(s=>s.applyGlobalState()))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let r=0;r<t.length;r++)if(t[r].getName()!==e[r].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],r=[],i=[],o=Or(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?r.push(s):i.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:r,remaining:i})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await y.getShadowGraphqlClient().mutate({mutation:Cl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await y.getShadowGraphqlClient().mutate({mutation:wl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const fc=w.gql`
2408
+ `;class ia{constructor(t,e,a,r,i,o){this.workflowExperiences=[],this.eventEmitter=new mc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new dc(e.bundleStateData);const s=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=s?.id,this.globalPropertyStateManager=new cc(this.id,this.ownerId,s,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new rc(this),this.setPreviewService(a);const l=new Promise((c,d)=>{if(o?.readonly){c([]);return}console.log("Setting default global variants.");const A=this.globalPropertyStateManager.getGlobalPropertyState();A?this.globalPropertyHandleService.getHandles().then(u=>{const h=u.map(g=>{if(g.getType()===$.ColorOption||g.getType()===$.Option){const p=g;if(!A.aspects.find(f=>f.name===p.getName()))return p.initDefaultVariant()}});Promise.all(h).then(c).catch(d)}):(console.log("Attempted to set global default variant before state was initialized."),c([]))});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(e.transactions?.map(c=>c.id)||[],{...r,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}getTemplate(){return this.template}async generateQuoteId(){const e=(await y.getShadowGraphqlClient().mutate({mutation:Cc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,r,i,o){await y.getShadowGraphqlClient().mutate({mutation:pc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await y.getShadowGraphqlClient().mutate({mutation:fc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const a of t.aspects){const r=a?.name;this.getGlobalPropertyStateManager().setAspect(r,a.value)}for(const a of t.aspects){const r=a?.name,i=e.find(o=>o.getName()===r);if(i)switch(a.type){case $.FileUpload:{const o=i,s=await Fe([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case $.ColorOption:{const o=i,l=o.getAllVariants().find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case $.Option:{const o=i,l=o.getAllVariants().find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case $.Text:{await i.setText(a.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===$.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,r)=>a+r,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new Ha(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(E.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const r of a){const i=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===r);if(i&&i.type===$.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=oc(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",r),d=[...new Set(s.map(u=>u.number))];if(d.length>c)for(const u of d){const h=this.getGlobalPropertyStateManager(),g=l.find(p=>p.channelNumber===u);g&&await h.setAspect(r,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getWorkflowManager().getTransaction().id),a=e.map(s=>this.workflowExperiences.find(l=>l.getWorkflowManager().getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getWorkflowManager().getTransaction().id).join(", "));const r=k.getMap("transactionOwnerIds")||new Map,i=e.map(s=>r.get(s));await y.getShadowGraphqlClient().mutate({mutation:ll,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(k.getMap("transactionOwnerIds")||new Map).get(a);await y.getShadowGraphqlClient().mutate({mutation:sl,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const r=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);if(r.setBundle(void 0),this.previewService&&r.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await y.getShadowGraphqlClient().mutate({mutation:cl,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,o])=>({key:i,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),r.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(r=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===r.id));if(e.some(r=>r===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((r,i)=>e[i]===-1).map(r=>r.id).join(", "));const a=t.map(r=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===r.id),1)[0]);a.forEach(r=>r.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(r=>r.checkForPriceBreakChanges()),this.previewService&&a.forEach(r=>r.getWorkflowManager().ejectFromPreviewService()),t.forEach(r=>this.bundleStateManager.removeStateForTransaction(r.id)),await y.getShadowGraphqlClient().mutate({mutation:dl,variables:{id:this.id,transactionIds:t.map(r=>r.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,i])=>({key:r,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(r=>r.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const r=await this.getGlobalProperties();await Promise.all(r.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const a=await y.getShadowGraphqlClient().mutate({mutation:Al,variables:{id:this.id,details:t,type:e||ee.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const r=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(r)}async removeStakeholder(t){if(!(await y.getShadowGraphqlClient().mutate({mutation:ul,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await y.getShadowGraphqlClient().mutate({mutation:hl,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await y.getShadowGraphqlClient().query({query:gn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await y.getShadowGraphqlClient().query({query:gn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){this.completed&&await y.getShadowGraphqlClient().mutate({mutation:Cl,variables:{bundleId:this.id}});const a=await Nl(this.workflowExperiences.map(r=>({workflowManager:r.getWorkflowManager(),workflow:r.getWorkflowManager().getWorkflow(),layouts:r.getWorkflowManager().getLayouts(),getReducerState:()=>r.getCommandContext().getState(),product:r.getWorkflowManager().getProduct(),transaction:r.getWorkflowManager().getTransaction(),workflowSelections:r.getWorkflowManager().getWorkflowSelections(),designName:r.getWorkflowManager().getWorkflow().name,workflowMetadata:r.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(r,i)=>{const o=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===i);return o?e(o,r):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getWorkflowManager().getTransaction().id,amountToOrder:e.getWorkflowManager().getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await y.getShadowGraphqlClient().mutate({mutation:pl,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ml(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),this.globalConfigurationPropertyId=a?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const r=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===r.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(r=>({type:"transaction",transactionId:r})),e);if(a.forEach(r=>r.setBundle(this)),a.forEach(r=>r.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const r of a)await this.injectExperienceIntoPreviewService(r)}async updateBundle(){if(!(await y.getShadowGraphqlClient().mutate({mutation:ol,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await y.getShadowGraphqlClient().mutate({mutation:gl,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const a=await this.globalPropertyHandleService.getHandles(),r=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(r,i),this.checkMandatoryHandlesChanged(t,i);const o=a.map(s=>{if(s.getType()===$.ColorOption||s.getType()===$.Option){const l=s;if(!e.aspects.find(d=>d.name===l.getName()))return l.initDefaultVariant()}});await Promise.all(o),await Promise.all(i.map(s=>s.applyGlobalState()))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let r=0;r<t.length;r++)if(t[r].getName()!==e[r].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],r=[],i=[],o=$r(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?r.push(s):i.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:r,remaining:i})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await y.getShadowGraphqlClient().mutate({mutation:wl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await y.getShadowGraphqlClient().mutate({mutation:yl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const wc=C.gql`
2405
2409
  mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
2406
2410
  processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
2407
2411
  id
2408
2412
  }
2409
2413
  }
2410
- `;class zr{async execute(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:fc,variables:{processFlowId:t,inputs:[...e.map(A=>A.getValueForTransmission())]}})).data?.processExecutionCreate?.id;if(!i)throw new Error("Failed to create process execution.");function o(A){return new Promise(u=>{setTimeout(u,A)})}let s=!1,l=0,c,d;for(;!s;){c=await y.getShadowGraphqlClient().query({query:w.gql`
2414
+ `;class qr{async execute(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:wc,variables:{processFlowId:t,inputs:[...e.map(A=>A.getValueForTransmission())]}})).data?.processExecutionCreate?.id;if(!i)throw new Error("Failed to create process execution.");function o(A){return new Promise(u=>{setTimeout(u,A)})}let s=!1,l=0,c,d;for(;!s;){c=await y.getShadowGraphqlClient().query({query:C.gql`
2411
2415
  query getProcessFlowExecution($ids: [String]!) {
2412
2416
  processExecutions(ids: $ids) {
2413
2417
  id
@@ -2420,7 +2424,7 @@
2420
2424
  }
2421
2425
  }
2422
2426
  }
2423
- `,variables:{ids:[i]}});const A=c.data?.processExecutions[0];if(!c||!A)throw new Error("Failed to retrieve server response for execution.");if(A.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(A.completedAt){s=!0,d=new qr(A);break}l+=1;const u=a?.repeats?a?.repeats:5;if(l>=u)throw new Error("Maximum wait time exceeded for execution result.");await o(a?.sleepTime?Math.max(a.sleepTime,500):2e3)}if(!d)throw new Error("Failed to retrieve server response for execution.");return Promise.resolve(d)}}class qr{constructor(t){this.execution=t}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(t=>new Yt(t))}getNodesByType(t){return this.execution.nodes.filter(e=>e.type===t).map(e=>new Yt(e))}getInputs(){return this.execution.nodes.filter(t=>t.type==="StartTerminal").map(t=>new Yt(t))}getOutputs(){return this.execution.nodes.filter(t=>t.type==="EndTerminal").map(t=>new Yt(t))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class Yt{constructor(t){this.node=t}getId(){return this.node.id}getType(){return this.node.type}getArtifacts(){return new Map(Object.entries(JSON.parse(this.node.artifacts).value))}getArtifactByName(t){return this.getArtifacts().get(t)}}class Ha{constructor(t){this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):t}}var Gr=(n=>(n.Transaction="Transaction",n.Bundle="Bundle",n.Product="Product",n.Variant="Variant",n.Option="Option",n.LineItem="LineItem",n.Asset="Asset",n))(Gr||{});class Cc extends Ha{constructor(t){super(`"${t}"`)}}class Ya extends Ha{constructor(t,e){if(e!=="Asset"&&!Ya.validUUID(t))throw new Error("Invalid ID, must be a valid v4 UUID. https://www.uuidgenerator.net/");super(`{"isSpiffObject": true, "id": "${t}", "type": "${e}"}`)}static validUUID(t){return t.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)}}class wc extends Ha{constructor(t){super(`[${t.map(e=>e.getRaw()).join(",")}]`)}}class va{constructor(t){this.integrationProduct=t}getId(){return this.integrationProduct.id}getResource(){return this.integrationProduct}getBasePrice(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.basePrice||0,e=this.integrationProduct?.additionalIntegrationProduct;if(!e)return t;if(e&&!e.product)throw new Error("An additional integration product was found, but it does not have a product");return t+(e.product.basePrice||0)}getDefaultWorkflow(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.workflows||[];if(t.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return new Tt(t[0])}getAllWorkflows(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.workflows||[];if(t.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return t.sort((e,a)=>(e.index??0)-(a.index??0)).map(e=>new Tt(e))}}const Ee=w.gql`
2427
+ `,variables:{ids:[i]}});const A=c.data?.processExecutions[0];if(!c||!A)throw new Error("Failed to retrieve server response for execution.");if(A.failedAt)throw new Error("Execution has failed to complete. See Automation > FLows in Flight on partner account on SpiffCommerce Hub.");if(A.completedAt){s=!0,d=new Gr(A);break}l+=1;const u=a?.repeats?a?.repeats:5;if(l>=u)throw new Error("Maximum wait time exceeded for execution result.");await o(a?.sleepTime?Math.max(a.sleepTime,500):2e3)}if(!d)throw new Error("Failed to retrieve server response for execution.");return Promise.resolve(d)}}class Gr{constructor(t){this.execution=t}getRaw(){return this.execution}getNodes(){return this.execution.nodes.map(t=>new Yt(t))}getNodesByType(t){return this.execution.nodes.filter(e=>e.type===t).map(e=>new Yt(e))}getInputs(){return this.execution.nodes.filter(t=>t.type==="StartTerminal").map(t=>new Yt(t))}getOutputs(){return this.execution.nodes.filter(t=>t.type==="EndTerminal").map(t=>new Yt(t))}getCompletedAt(){if(this.execution.completedAt)return new Date(this.execution.completedAt)}getFailedAt(){if(this.execution.failedAt)return new Date(this.execution.failedAt)}}class Yt{constructor(t){this.node=t}getId(){return this.node.id}getType(){return this.node.type}getArtifacts(){return new Map(Object.entries(JSON.parse(this.node.artifacts).value))}getArtifactByName(t){return this.getArtifacts().get(t)}}class Ya{constructor(t){this.value=t}getRaw(){return this.value}getValueForTransmission(){const t=this.value;return t.startsWith("[")?JSON.stringify(JSON.parse(t)):t}}var Wr=(n=>(n.Transaction="Transaction",n.Bundle="Bundle",n.Product="Product",n.Variant="Variant",n.Option="Option",n.LineItem="LineItem",n.Asset="Asset",n))(Wr||{});class yc extends Ya{constructor(t){super(`"${t}"`)}}class Ja extends Ya{constructor(t,e){if(e!=="Asset"&&!Ja.validUUID(t))throw new Error("Invalid ID, must be a valid v4 UUID. https://www.uuidgenerator.net/");super(`{"isSpiffObject": true, "id": "${t}", "type": "${e}"}`)}static validUUID(t){return t.match(/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i)}}class Sc extends Ya{constructor(t){super(`[${t.map(e=>e.getRaw()).join(",")}]`)}}class Ea{constructor(t){this.integrationProduct=t}getId(){return this.integrationProduct.id}getResource(){return this.integrationProduct}getBasePrice(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.basePrice||0,e=this.integrationProduct?.additionalIntegrationProduct;if(!e)return t;if(e&&!e.product)throw new Error("An additional integration product was found, but it does not have a product");return t+(e.product.basePrice||0)}getDefaultWorkflow(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.workflows||[];if(t.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return new Tt(t[0])}getAllWorkflows(){if(!this.integrationProduct.product)throw new Error("IntegrationProductResource does not have a product");const t=this.integrationProduct.product.workflows||[];if(t.length===0)throw new Error("No workflows found on product. This is generally due to a configuration error. Please confirm at least one workflow is configured for this product.");return t.sort((e,a)=>(e.index??0)-(a.index??0)).map(e=>new Tt(e))}}const Ee=C.gql`
2424
2428
  query GetCustomer($emailAddress: String!) {
2425
2429
  customer(emailAddress: $emailAddress) {
2426
2430
  id
@@ -2437,7 +2441,7 @@
2437
2441
  }
2438
2442
  }
2439
2443
  }
2440
- `,yc=w.gql`
2444
+ `,vc=C.gql`
2441
2445
  mutation CustomerCreate($details: CustomerDetailsInput!) {
2442
2446
  customerCreate(details: $details) {
2443
2447
  id
@@ -2447,7 +2451,7 @@
2447
2451
  }
2448
2452
  }
2449
2453
  }
2450
- `;w.gql`
2454
+ `;C.gql`
2451
2455
  mutation CustomerAuthenticate($loginToken: String!) {
2452
2456
  customerAuthenticate(loginToken: $loginToken) {
2453
2457
  id
@@ -2477,11 +2481,11 @@
2477
2481
  }
2478
2482
  }
2479
2483
  }
2480
- `;const Sc=w.gql`
2484
+ `;const Ec=C.gql`
2481
2485
  mutation CustomerGenerateVerificationCode($emailAddress: String!) {
2482
2486
  customerGenerateVerificationCode(emailAddress: $emailAddress)
2483
2487
  }
2484
- `;w.gql`
2488
+ `;C.gql`
2485
2489
  mutation CustomerVerifyCode($emailAddress: String!, $verificationCode: String!) {
2486
2490
  customerVerifyCode(emailAddress: $emailAddress, verificationCode: $verificationCode) {
2487
2491
  id
@@ -2512,7 +2516,7 @@
2512
2516
  }
2513
2517
  }
2514
2518
  }
2515
- `;const vc=w.gql`
2519
+ `;const bc=C.gql`
2516
2520
  query CustomerMetafields($id: String!) {
2517
2521
  metafields(entityId: $id) {
2518
2522
  id
@@ -2530,13 +2534,13 @@
2530
2534
  }
2531
2535
  }
2532
2536
  }
2533
- `;class Ec{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 bc{init(t,e,a){this.cognitoClient=new fe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new fe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}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 fe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new bc;class Wr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return ui(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Za.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Za.code(e)?.code==="CLP")return"USD0,0"}}const pn=new Wr;class jr{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,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,pn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,pn.getPrecisionForCurrency(e))}}const Bc=async(n,t)=>{const e=await y.getShadowGraphqlClient().query({query:Po(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&R.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&R.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&R.cacheAsset(o.asset),o.thumbnail&&R.cacheAsset(o.thumbnail),o.material&&R.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},Ic=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},Ja=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=Bc(a,t),i=a.map(s=>$t.set({id:s,options:t},Ic(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},Pc=async(n,t)=>(await Ja([n],t))[0],xc=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:M(),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})),Dc=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(r=>r.layout):xc(t.panels)};class Fc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:go})}catch(a){throw console.error(a),new gt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Fi(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 32.2.7"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.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&&Un(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return R}getFlowService(){if(!ki())throw new Error("Application key required to use Flow Service.");return new zr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:Qo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new jr(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=Hr(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}}async authenticateBundleFromLocalStorage(t){if(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=y.getShadowGraphqlClient(),a=await e.query({query:xo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const u=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(u)return Promise.resolve({success:!0,stakeholderType:u.type})}const c=(await e.query({query:Do,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await y.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.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(),r=(await e.query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:yc,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(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}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 r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:Ee,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:Sc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await Wt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:Ee,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),r=new Date().getTime()/1e3,i=!a?.AccessToken||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){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:vc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:nl(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(!i?.id)throw new Error("Unable to create bundle");const o=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new ra(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const m=Object.entries(localStorage).find(([f,S])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(m);p&&!_t(p)&&(s.Authorization=`Bearer ${p}`)}const l={bundleOwnerId:o,...s,...r?.graphql?.additionalHeaders},c=await y.getShadowGraphqlClient().query({query:Xs(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],A=k.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",A);const u=new ra(this,d,e,a,o,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:r?.readonly});return await u.getInitializationPromise(),u}async duplicateBundle(t,e,a,r){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const u=await this.loggedInBearerToken();o.Authorization=`Bearer ${u}`}catch{const g=Object.entries(localStorage).find(([p,f])=>p.startsWith("CognitoIdentityServiceProvider")&&p.endsWith("idToken"))?.[0]||"",m=localStorage.getItem(g);m&&!_t(m)&&(o.Authorization=`Bearer ${m}`)}const s={bundleOwnerId:i,...o,...r?.graphql?.additionalHeaders},c=(await y.getShadowGraphqlClient().mutate({mutation:rl(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const A=k.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",A),async()=>{const u=new ra(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await u.getInitializationPromise(),u}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:pl(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:Zs,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||[],r=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",r),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),r=a[0];return e&&await r.getWorkflowManager().injectIntoPreviewService(e(r.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new gt("No options provided!");const a=y.getShadowGraphqlClient(),r=async C=>{if(C.length===0)return[];const E=C.map(D=>D.option.transactionId),x=await a.query({query:ho,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),B=x.data.transactions;if(B.length!==C.length){const D=x.errors?.[0]?.message||"Unknown error";throw new gt(`Not all transactions were found: ${D}`)}return!this.activeIntegration&&B[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(B[0].integrationProduct.integration)),B.map((D,O)=>({transaction:D,workflowId:D.workflowId,readOnly:C.find(T=>T.option.transactionId===D.id)?.option.readOnly??!1,index:C[O].index}))},i=async C=>{if(C.length===0)return[];const E=await a.mutate({mutation:uo,variables:{inputs:C.map(B=>({integrationProductId:B.option.type==="integration"?B.option.integrationProductId:void 0,externalIntegrationId:B.option.type==="external"?B.option.externalIntegrationId:void 0,externalProductId:B.option.type==="external"?B.option.externalProductId:void 0,workflowId:B.option.workflowId,designName:B.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),x=E.data?.transactionCreateMany;if(!x||x.length===0){const B=E.errors?.[0]?.message||"Unknown error";throw new gt(`Failed to create transactions: ${B}`)}return x.map((B,D)=>({transaction:B,workflowId:B.workflowId,readOnly:!1,index:C[D].index}))},o=t.map((C,E)=>({option:C,index:E})),s=o.filter(C=>C.option.type==="transaction"),l=o.filter(C=>C.option.type==="integration"||C.option.type==="external"),c=Xa(s,10),d=Xa(l,10),A=(await Promise.all([...c.map(r),...d.map(i)])).flat(),u=[...new Set(A.map(C=>C.workflowId))],h=await Ja(u,e),g=new Map(h.map(C=>[C.id,C])),m=k.getMap("transactionOwnerIds")||new Map,p=A.map(async C=>{const{transaction:E,workflowId:x,readOnly:B,index:D}=C,O=g.get(x),T=t[D];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const et=m.get(E.id)||void 0,at=new Ec({onMutate:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}})}),H={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:T?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:B?async()=>{throw new L("State mutation is forbidden in read only mode!")}:async Y=>this.updateTransactionState({...Y,context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>at,readOnly:B,workflow:O,isReloadedTransaction:T.type==="transaction"};if(T.type==="transaction"&&E.workflowState){const Y=JSON.parse(E.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),H.reloadedState=Y}else if(!B&&T.workflowState){const Y=JSON.parse(T.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),H.reloadedState=Y}else H.layouts=Dc(H.transaction,H.workflow);return H.renderableContextService=new Jl(H.layouts),H.delayWorkflowStateSync=!0,{experienceOptions:H,index:D,options:T}}),f=await Promise.all(p);k.setMap("transactionOwnerIds",m);const b=f.sort((C,E)=>C.index-E.index).map(async C=>{const{experienceOptions:E,options:x}=C,B=new Tr(this,E);return await B.getWorkflowManager().getInitializationPromise(),x.type!=="transaction"&&this.customer&&await B.attachCustomerDetails({email:this.customer.emailAddress}),B}),P=await Promise.all(b);return P.forEach(C=>C.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),P}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:wo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new va(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:yo(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 va(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await y.getShadowGraphqlClient().query({query:Co,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:No,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 Hr=async(n,t)=>(await y.getShadowGraphqlClient().query({query:ko,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,kc=async n=>{const e=await y.getShadowGraphqlClient().query({query:fo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Mc=async(n,t)=>(await y.getShadowGraphqlClient().query({query:Fo,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,Tc=async n=>(await y.getShadowGraphqlClient().query({query:To,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Nc=async n=>(await y.getShadowGraphqlClient().query({query:Mo,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;function Yr(n,t,e,a){const r=e.width*n.zoom,i=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=be(n.x,t.width-c,0),s.y=be(n.y,t.height-d,0),s}const o=n;return o.x=be(o.x,-r,t.width),o.y=be(o.y,-i,t.height),o}function be(n,t,e){return Math.min(Math.max(n,t),e)}class Jr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=In(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 r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await he(s),c=this.frameData?this.frameData[o]:void 0;xe(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(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 r=Ft.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=ze(this.imageData.svg,this.imageData.colors||{},!1);return Le(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=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],A=a[s]-c*t[s];return{x:d,y:A,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),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 r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new L("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]=Yr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,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,r,i){if(!a||a.length===0||a.some(s=>!s))throw new L("Frame data not set. This is a bug");if(!this.workflowManager)throw new L("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new Q([new ws(s,e,t[l]),new ys(s,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}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,r)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*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]=Na(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Qc{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,A,u,h,g,m,p,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(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}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 Kr=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Kr||{});class _r extends X{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new Jr(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.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 ht.selectImage(this.step,t,this.manager,a),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Qe.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 R.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,r){return r&&r.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 R.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return R.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}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 r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Rc=w.gql`
2537
+ `;class Bc{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 Ic{init(t,e,a){this.cognitoClient=new fe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new fe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}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 fe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new Ic;class jr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return hi(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=tn.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(tn.code(e)?.code==="CLP")return"USD0,0"}}const fn=new jr;class Hr{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,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,fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,fn.getPrecisionForCurrency(e))}}const Pc=async(n,t)=>{const e=await y.getShadowGraphqlClient().query({query:Do(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&R.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&R.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&R.cacheAsset(o.asset),o.thumbnail&&R.cacheAsset(o.thumbnail),o.material&&R.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},Dc=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},Ka=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=Pc(a,t),i=a.map(s=>$t.set({id:s,options:t},Dc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},Fc=async(n,t)=>(await Ka([n],t))[0],xc=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:M(),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})),kc=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(r=>r.layout):xc(t.panels)};class Mc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:mo})}catch(a){throw console.error(a),new gt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&ki(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 32.3.0-beta.0b8f2e31-be99-5e83-b9f9-3c0530b9e37e"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.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&&Ln(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return R}getFlowService(){if(!Mi())throw new Error("Application key required to use Flow Service.");return new qr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:Ro,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new Hr(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=Yr(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}}async authenticateBundleFromLocalStorage(t){if(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=y.getShadowGraphqlClient(),a=await e.query({query:Fo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const u=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(u)return Promise.resolve({success:!0,stakeholderType:u.type})}const c=(await e.query({query:xo,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await y.getShadowGraphqlClient().query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.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(),r=(await e.query({query:Ee,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:vc,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(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}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 r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:Ee,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:Ec,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await Wt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:Ee,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),r=new Date().getTime()/1e3,i=!a?.AccessToken||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){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:bc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:rl(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(!i?.id)throw new Error("Unable to create bundle");const o=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new ia(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const p=Object.entries(localStorage).find(([f,v])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",m=localStorage.getItem(p);m&&!_t(m)&&(s.Authorization=`Bearer ${m}`)}const l={bundleOwnerId:o,...s,...r?.graphql?.additionalHeaders},c=await y.getShadowGraphqlClient().query({query:Zs(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],A=k.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",A);const u=new ia(this,d,e,a,o,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:r?.readonly});return await u.getInitializationPromise(),u}async duplicateBundle(t,e,a,r){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const u=await this.loggedInBearerToken();o.Authorization=`Bearer ${u}`}catch{const g=Object.entries(localStorage).find(([m,f])=>m.startsWith("CognitoIdentityServiceProvider")&&m.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(g);p&&!_t(p)&&(o.Authorization=`Bearer ${p}`)}const s={bundleOwnerId:i,...o,...r?.graphql?.additionalHeaders},c=(await y.getShadowGraphqlClient().mutate({mutation:il(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const A=k.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",A),async()=>{const u=new ia(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await u.getInitializationPromise(),u}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:fl(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:tl,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||[],r=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",r),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),r=a[0];return e&&await r.getWorkflowManager().injectIntoPreviewService(e(r.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new gt("No options provided!");const a=y.getShadowGraphqlClient(),r=async S=>{if(S.length===0)return[];const P=S.map(T=>T.option.transactionId),F=await a.query({query:go,variables:{ids:P},errorPolicy:"all",fetchPolicy:"no-cache"}),B=F.data.transactions;if(B.length!==S.length){const T=F.errors?.[0]?.message||"Unknown error";throw new gt(`Not all transactions were found: ${T}`)}return!this.activeIntegration&&B[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(B[0].integrationProduct.integration)),B.map((T,V)=>({transaction:T,workflowId:T.workflowId,readOnly:S.find(Y=>Y.option.transactionId===T.id)?.option.readOnly??!1,index:S[V].index}))},i=async S=>{if(S.length===0)return[];const P=await a.mutate({mutation:ho,variables:{inputs:S.map(B=>({integrationProductId:B.option.type==="integration"?B.option.integrationProductId:void 0,externalIntegrationId:B.option.type==="external"?B.option.externalIntegrationId:void 0,externalProductId:B.option.type==="external"?B.option.externalProductId:void 0,workflowId:B.option.workflowId,designName:B.option.designName,claim:!0,quantity:B.option.type==="integration"?B.option.quantity:void 0,recipient:B.option.type==="integration"?B.option.recipient:void 0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),F=P.data?.transactionCreateMany;if(!F||F.length===0){const B=P.errors?.[0]?.message||"Unknown error";throw new gt(`Failed to create transactions: ${B}`)}return F.map((B,T)=>({transaction:B,workflowId:B.workflowId,readOnly:!1,index:S[T].index}))},o=t.map((S,P)=>({option:S,index:P})),s=o.filter(S=>S.option.type==="transaction"),l=o.filter(S=>S.option.type==="integration"||S.option.type==="external"),c=15,d=Za(s,c),A=Za(l,c),u=(await Promise.all([...d.map(r),...A.map(i)])).flat(),h=[...new Set(u.map(S=>S.workflowId))],g=await Ka(h,e),p=new Map(g.map(S=>[S.id,S])),m=k.getMap("transactionOwnerIds")||new Map,f=u.map(async S=>{const{transaction:P,workflowId:F,readOnly:B,index:T}=S,V=p.get(F),Y=t[T];!m.get(P.id)&&P.transactionOwnerId&&m.set(P.id,P.transactionOwnerId);const X=m.get(P.id)||void 0,vt=new Bc({onMutate:()=>({context:{transactionOwnerId:X,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:X,bundleOwnerId:e?.bundleOwnerId}})}),q={product:P.product,transaction:P,layouts:[],singleVariantsRenderable:Y?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:B?async()=>{throw new U("State mutation is forbidden in read only mode!")}:async et=>this.updateTransactionState({...et,context:{transactionOwnerId:X,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>vt,readOnly:B,workflow:V,isReloadedTransaction:Y.type==="transaction"};if(Y.type==="transaction"&&P.workflowState){const et=JSON.parse(P.workflowState);q.layouts=Object.values(et.layouts||{}).map(He=>He.layout),await Ca(et),q.reloadedState=et}else if(!B&&Y.workflowState){const et=JSON.parse(Y.workflowState);q.layouts=Object.values(et.layouts||{}).map(He=>He.layout),await Ca(et),q.reloadedState=et}else q.layouts=kc(q.transaction,q.workflow);return q.renderableContextService=new _l(q.layouts),q.delayWorkflowStateSync=!0,{experienceOptions:q,index:T,options:Y}}),v=await Promise.all(f);k.setMap("transactionOwnerIds",m);const D=v.sort((S,P)=>S.index-P.index).map(async S=>{const{experienceOptions:P,options:F}=S,B=new Nr(this,P);return await B.getWorkflowManager().getInitializationPromise(),F.type!=="transaction"&&this.customer&&await B.attachCustomerDetails({email:this.customer.emailAddress}),B}),w=await Promise.all(D);return w.forEach(S=>S.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),w}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:yo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new Ea(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:So(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 Ea(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await y.getShadowGraphqlClient().query({query:wo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:Qo,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 Yr=async(n,t)=>(await y.getShadowGraphqlClient().query({query:Mo,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,Tc=async n=>{const e=await y.getShadowGraphqlClient().query({query:Co,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Nc=async(n,t)=>(await y.getShadowGraphqlClient().query({query:ko,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,Qc=async n=>(await y.getShadowGraphqlClient().query({query:No,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Rc=async n=>(await y.getShadowGraphqlClient().query({query:To,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,Oc=async n=>{const t=await y.getShadowGraphqlClient().mutate({mutation:Il,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n}});if(t.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${t.errors}`)};function Jr(n,t,e,a){const r=e.width*n.zoom,i=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=be(n.x,t.width-c,0),s.y=be(n.y,t.height-d,0),s}const o=n;return o.x=be(o.x,-r,t.width),o.y=be(o.y,-i,t.height),o}function be(n,t,e){return Math.min(Math.max(n,t),e)}class Kr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Pn(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 r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await he(s),c=this.frameData?this.frameData[o]:void 0;De(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(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 r=xt.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=ze(this.imageData.svg,this.imageData.colors||{},!1);return Le(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=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],A=a[s]-c*t[s];return{x:d,y:A,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),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 r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new U("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]=Jr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,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,r,i){if(!a||a.length===0||a.some(s=>!s))throw new U("Frame data not set. This is a bug");if(!this.workflowManager)throw new U("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new Q([new ys(s,e,t[l]),new Ss(s,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}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,r)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*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]=Qa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class $c{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,A,u,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(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}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 _r=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(_r||{});class Xr extends Z{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new Kr(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.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 ht.selectImage(this.step,t,this.manager,a),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Qe.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 R.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,r){return r&&r.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 R.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return R.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}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 r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Uc=C.gql`
2534
2538
  query GetLoggedInCustomer($email: String!) {
2535
2539
  customer(emailAddress: $email) {
2536
2540
  id
2537
2541
  }
2538
2542
  }
2539
- `,Ka=w.gql`
2543
+ `,_a=C.gql`
2540
2544
  query GetCustomerTransactions(
2541
2545
  $id: String!
2542
2546
  $limit: Int!
@@ -2573,21 +2577,21 @@
2573
2577
  total
2574
2578
  }
2575
2579
  }
2576
- `,Oc=w.gql`
2580
+ `,Lc=C.gql`
2577
2581
  mutation SetTransactionDesignName($id: String!, $name: String!) {
2578
2582
  transactionUpdate(id: $id, designName: $name) {
2579
2583
  id
2580
2584
  designName
2581
2585
  }
2582
2586
  }
2583
- `,$c=w.gql`
2587
+ `,Vc=C.gql`
2584
2588
  mutation DuplicateTransaction($id: String!, $template: Boolean!) {
2585
2589
  transactionDuplicate(id: $id, template: $template) {
2586
2590
  id
2587
2591
  workflowViewerLink
2588
2592
  }
2589
2593
  }
2590
- `,Uc=w.gql`
2594
+ `,zc=C.gql`
2591
2595
  query GetCustomerBundles($id: String!, $limit: Int!, $offset: Int!) {
2592
2596
  customerBundlesFeed(id: $id, limit: $limit, offset: $offset) {
2593
2597
  items {
@@ -2602,7 +2606,7 @@
2602
2606
  total
2603
2607
  }
2604
2608
  }
2605
- `,Lc=w.gql`
2609
+ `,qc=C.gql`
2606
2610
  query GetTransactionsForBundle($id: String!) {
2607
2611
  bundles(ids: [$id]) {
2608
2612
  id
@@ -2623,21 +2627,21 @@
2623
2627
  }
2624
2628
  }
2625
2629
  }
2626
- `,Vc=w.gql`
2630
+ `,Gc=C.gql`
2627
2631
  mutation SetBundleName($id: String!, $name: String!) {
2628
2632
  bundleUpdate(id: $id, name: $name) {
2629
2633
  id
2630
2634
  name
2631
2635
  }
2632
2636
  }
2633
- `,zc=w.gql`
2637
+ `,Wc=C.gql`
2634
2638
  mutation DuplicateBundle($id: String!, $template: Boolean!) {
2635
2639
  bundleDuplicate(id: $id, template: $template) {
2636
2640
  id
2637
2641
  workflowViewerLink
2638
2642
  }
2639
2643
  }
2640
- `,qc=w.gql`
2644
+ `,jc=C.gql`
2641
2645
  query GetBundleTemplates($id: String!, $limit: Int!, $offset: Int!) {
2642
2646
  customerBundlesFeed(id: $id, limit: $limit, offset: $offset, template: true) {
2643
2647
  items {
@@ -2650,7 +2654,7 @@
2650
2654
  total
2651
2655
  }
2652
2656
  }
2653
- `,Gc=async(n,t,e)=>await y.getShadowGraphqlClient().mutate({mutation:Vc,errorPolicy:"all",variables:{id:n,name:t},context:e}),Wc=async(n,t)=>await y.getShadowGraphqlClient().mutate({mutation:Oc,errorPolicy:"all",variables:{id:n,name:t}}),jc=async(n,t)=>await y.getShadowGraphqlClient().mutate({mutation:zc,errorPolicy:"all",variables:{id:n,template:t}}),Hc=async(n,t)=>await y.getShadowGraphqlClient().mutate({mutation:$c,errorPolicy:"all",variables:{id:n,template:t}}),Yc=async n=>(await y.getShadowGraphqlClient().query({query:Rc,errorPolicy:"all",variables:{email:n}})).data.customer,Jc=async(n,t,e)=>await y.getShadowGraphqlClient().query({query:Uc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,offset:e,limit:t}}),Kc=async(n,t)=>await y.getShadowGraphqlClient().query({query:Lc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:t}),_c=async(n,t,e)=>(await y.getShadowGraphqlClient().query({query:Ka,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,quicksearch:"",filters:{link:"and",status:{operator:"isAnyOf",values:["Created","DesignCompleted","ExternallyOrdered"]},template:{value:"false"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],Xc=async(n,t,e)=>(await y.getShadowGraphqlClient().query({query:Ka,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,quicksearch:"",filters:{link:"and",status:{operator:"equals",value:"Ordered"},template:{value:"false"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],Zc=async(n,t,e)=>(await y.getShadowGraphqlClient().query({query:Ka,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,quicksearch:"",filters:{link:"and",template:{value:"true"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],td=async(n,t,e)=>(await y.getShadowGraphqlClient().query({query:qc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,offset:e,limit:t}}))?.data.customerBundlesFeed?.items||[];(function(){try{if(typeof document<"u"){var n=document.createElement("style");n.appendChild(document.createTextNode("#spiffThemeWrapper{width:100%;height:100%}")),document.head.appendChild(n)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}})();var Xr=(n=>(n.Manual="Manual",n.OnStart="OnStart",n.OnQuit="OnQuit",n.OnEnd="OnEnd",n))(Xr||{}),Xt=(n=>(n.Email="Email",n.FirstName="FirstName",n.LastName="LastName",n.Phone="Phone",n.Apartment="Apartment",n.City="City",n.Country="Country",n.OrganizationName="OrganizationName",n.PostCode="PostCode",n.State="State",n.StreetAddress="StreetAddress",n.Custom="Custom",n))(Xt||{}),K;K={__e:function(n,t,e,a){for(var r,i,o;t=t.__;)if((r=t.__c)&&!r.__)try{if((i=r.constructor)&&i.getDerivedStateFromError!=null&&(r.setState(i.getDerivedStateFromError(n)),o=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(n,a||{}),o=r.__d),o)return r.__E=r}catch(s){n=s}throw n}},typeof Promise=="function"&&Promise.prototype.then.bind(Promise.resolve());var st,ia,fn,Zr=[],oa=[],Cn=K.__b,wn=K.__r,yn=K.diffed,Sn=K.__c,vn=K.unmount;function ed(){for(var n;n=Zr.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(Pe),n.__H.__h.forEach(Ea),n.__H.__h=[]}catch(t){n.__H.__h=[],K.__e(t,n.__v)}}K.__b=function(n){st=null,Cn&&Cn(n)},K.__r=function(n){wn&&wn(n);var t=(st=n.__c).__H;t&&(ia===st?(t.__h=[],st.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.__V=oa,e.__N=e.i=void 0})):(t.__h.forEach(Pe),t.__h.forEach(Ea),t.__h=[])),ia=st},K.diffed=function(n){yn&&yn(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(Zr.push(t)!==1&&fn===K.requestAnimationFrame||((fn=K.requestAnimationFrame)||ad)(ed)),t.__H.__.forEach(function(e){e.i&&(e.__H=e.i),e.__V!==oa&&(e.__=e.__V),e.i=void 0,e.__V=oa})),ia=st=null},K.__c=function(n,t){t.some(function(e){try{e.__h.forEach(Pe),e.__h=e.__h.filter(function(a){return!a.__||Ea(a)})}catch(a){t.some(function(r){r.__h&&(r.__h=[])}),t=[],K.__e(a,e.__v)}}),Sn&&Sn(n,t)},K.unmount=function(n){vn&&vn(n);var t,e=n.__c;e&&e.__H&&(e.__H.__.forEach(function(a){try{Pe(a)}catch(r){t=r}}),e.__H=void 0,t&&K.__e(t,e.__v))};var En=typeof requestAnimationFrame=="function";function ad(n){var t,e=function(){clearTimeout(a),En&&cancelAnimationFrame(t),setTimeout(n)},a=setTimeout(e,100);En&&(t=requestAnimationFrame(e))}function Pe(n){var t=st,e=n.__c;typeof e=="function"&&(n.__c=void 0,e()),st=t}function Ea(n){var t=st;n.__c=n.__(),st=t}const ti=w.gql`
2657
+ `,Hc=async(n,t,e)=>await y.getShadowGraphqlClient().mutate({mutation:Gc,errorPolicy:"all",variables:{id:n,name:t},context:e}),Yc=async(n,t)=>await y.getShadowGraphqlClient().mutate({mutation:Lc,errorPolicy:"all",variables:{id:n,name:t}}),Jc=async(n,t)=>await y.getShadowGraphqlClient().mutate({mutation:Wc,errorPolicy:"all",variables:{id:n,template:t}}),Kc=async(n,t)=>await y.getShadowGraphqlClient().mutate({mutation:Vc,errorPolicy:"all",variables:{id:n,template:t}}),_c=async n=>(await y.getShadowGraphqlClient().query({query:Uc,errorPolicy:"all",variables:{email:n}})).data.customer,Xc=async(n,t,e)=>await y.getShadowGraphqlClient().query({query:zc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,offset:e,limit:t}}),Zc=async(n,t)=>await y.getShadowGraphqlClient().query({query:qc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:t}),td=async(n,t,e)=>(await y.getShadowGraphqlClient().query({query:_a,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,quicksearch:"",filters:{link:"and",status:{operator:"isAnyOf",values:["Created","DesignCompleted","ExternallyOrdered"]},template:{value:"false"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],ed=async(n,t,e)=>(await y.getShadowGraphqlClient().query({query:_a,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,quicksearch:"",filters:{link:"and",status:{operator:"equals",value:"Ordered"},template:{value:"false"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],ad=async(n,t,e)=>(await y.getShadowGraphqlClient().query({query:_a,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,quicksearch:"",filters:{link:"and",template:{value:"true"}},offset:e,limit:t}}))?.data.customerTransactionsFeed?.items||[],nd=async(n,t,e)=>(await y.getShadowGraphqlClient().query({query:jc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n,offset:e,limit:t}}))?.data.customerBundlesFeed?.items||[];(function(){try{if(typeof document<"u"){var n=document.createElement("style");n.appendChild(document.createTextNode("#spiffThemeWrapper{width:100%;height:100%}")),document.head.appendChild(n)}}catch(t){console.error("vite-plugin-css-injected-by-js",t)}})();var Zr=(n=>(n.Manual="Manual",n.OnStart="OnStart",n.OnQuit="OnQuit",n.OnEnd="OnEnd",n))(Zr||{}),Xt=(n=>(n.Email="Email",n.FirstName="FirstName",n.LastName="LastName",n.Phone="Phone",n.Apartment="Apartment",n.City="City",n.Country="Country",n.OrganizationName="OrganizationName",n.PostCode="PostCode",n.State="State",n.StreetAddress="StreetAddress",n.Custom="Custom",n))(Xt||{}),K;K={__e:function(n,t,e,a){for(var r,i,o;t=t.__;)if((r=t.__c)&&!r.__)try{if((i=r.constructor)&&i.getDerivedStateFromError!=null&&(r.setState(i.getDerivedStateFromError(n)),o=r.__d),r.componentDidCatch!=null&&(r.componentDidCatch(n,a||{}),o=r.__d),o)return r.__E=r}catch(s){n=s}throw n}},typeof Promise=="function"&&Promise.prototype.then.bind(Promise.resolve());var st,oa,Cn,ti=[],sa=[],wn=K.__b,yn=K.__r,Sn=K.diffed,vn=K.__c,En=K.unmount;function rd(){for(var n;n=ti.shift();)if(n.__P&&n.__H)try{n.__H.__h.forEach(Pe),n.__H.__h.forEach(ba),n.__H.__h=[]}catch(t){n.__H.__h=[],K.__e(t,n.__v)}}K.__b=function(n){st=null,wn&&wn(n)},K.__r=function(n){yn&&yn(n);var t=(st=n.__c).__H;t&&(oa===st?(t.__h=[],st.__h=[],t.__.forEach(function(e){e.__N&&(e.__=e.__N),e.__V=sa,e.__N=e.i=void 0})):(t.__h.forEach(Pe),t.__h.forEach(ba),t.__h=[])),oa=st},K.diffed=function(n){Sn&&Sn(n);var t=n.__c;t&&t.__H&&(t.__H.__h.length&&(ti.push(t)!==1&&Cn===K.requestAnimationFrame||((Cn=K.requestAnimationFrame)||id)(rd)),t.__H.__.forEach(function(e){e.i&&(e.__H=e.i),e.__V!==sa&&(e.__=e.__V),e.i=void 0,e.__V=sa})),oa=st=null},K.__c=function(n,t){t.some(function(e){try{e.__h.forEach(Pe),e.__h=e.__h.filter(function(a){return!a.__||ba(a)})}catch(a){t.some(function(r){r.__h&&(r.__h=[])}),t=[],K.__e(a,e.__v)}}),vn&&vn(n,t)},K.unmount=function(n){En&&En(n);var t,e=n.__c;e&&e.__H&&(e.__H.__.forEach(function(a){try{Pe(a)}catch(r){t=r}}),e.__H=void 0,t&&K.__e(t,e.__v))};var bn=typeof requestAnimationFrame=="function";function id(n){var t,e=function(){clearTimeout(a),bn&&cancelAnimationFrame(t),setTimeout(n)},a=setTimeout(e,100);bn&&(t=requestAnimationFrame(e))}function Pe(n){var t=st,e=n.__c;typeof e=="function"&&(n.__c=void 0,e()),st=t}function ba(n){var t=st;n.__c=n.__(),st=t}const ei=C.gql`
2654
2658
  fragment AddressValidationResultFields on AddressValidationResult {
2655
2659
  addressComplete
2656
2660
  address {
@@ -2672,8 +2676,8 @@
2672
2676
  }
2673
2677
  missingComponentTypes
2674
2678
  }
2675
- `,_a=w.gql`
2676
- ${ti}
2679
+ `,Xa=C.gql`
2680
+ ${ei}
2677
2681
  fragment AddressValidationJobFields on AddressValidationJob {
2678
2682
  id
2679
2683
  entityId
@@ -2684,15 +2688,15 @@
2684
2688
  ...AddressValidationResultFields
2685
2689
  }
2686
2690
  }
2687
- `,nd=w.gql`
2688
- ${_a}
2691
+ `,od=C.gql`
2692
+ ${Xa}
2689
2693
  query GetAddressValidationJobs($ids: [String!]!) {
2690
2694
  addressValidationJobs(ids: $ids) {
2691
2695
  ...AddressValidationJobFields
2692
2696
  }
2693
2697
  }
2694
- `,rd=w.gql`
2695
- ${_a}
2698
+ `,sd=C.gql`
2699
+ ${Xa}
2696
2700
  query GetRecipientsWithAddressValidationJobs($ids: [String!]!) {
2697
2701
  recipients(ids: $ids) {
2698
2702
  id
@@ -2701,25 +2705,25 @@
2701
2705
  }
2702
2706
  }
2703
2707
  }
2704
- `,id=w.gql`
2705
- ${ti}
2708
+ `,ld=C.gql`
2709
+ ${ei}
2706
2710
  mutation ValidateRecipientAddress($id: String!) {
2707
2711
  recipientValidate(id: $id) {
2708
2712
  ...AddressValidationResultFields
2709
2713
  }
2710
2714
  }
2711
- `,od=w.gql`
2712
- ${_a}
2715
+ `,cd=C.gql`
2716
+ ${Xa}
2713
2717
  mutation BatchValidateRecipientAddress($ids: [String!]!) {
2714
2718
  recipientValidateBatch(ids: $ids) {
2715
2719
  ...AddressValidationJobFields
2716
2720
  }
2717
2721
  }
2718
- `,sd=w.gql`
2722
+ `,dd=C.gql`
2719
2723
  mutation OverrideRecipientAddress($id: String!) {
2720
2724
  recipientOverrideAddress(id: $id) {
2721
2725
  id
2722
2726
  }
2723
2727
  }
2724
- `;var ei=(n=>(n.Confirmed="Confirmed",n.Plausible="Plausible",n.Unlikely="Unlikely",n))(ei||{}),ai=(n=>(n.Created="Created",n.Processing="Processing",n.Completed="Completed",n.Failed="Failed",n.Cancelled="Cancelled",n))(ai||{});const ld=async n=>{const t=n.map(a=>a.getWorkflowManager().getTransaction().recipient?.id).filter(a=>!!a),e=await y.getShadowGraphqlClient().query({query:rd,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return n.map(a=>{const r=a.getWorkflowManager().getTransaction().recipient?.id;if(r)return e.data?.recipients?.find(i=>i.id===r)?.addressValidationJob})},cd=async n=>(await y.getShadowGraphqlClient().query({query:nd,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:n}})).data?.addressValidationJobs,dd=async n=>n.getWorkflowManager().getTransaction().recipient?.id?(await y.getShadowGraphqlClient().mutate({mutation:id,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n.getWorkflowManager().getTransaction().recipient.id}})).data?.recipientValidate:void 0,Ad=async n=>{const t=n.map(a=>a.getWorkflowManager().getTransaction().recipient?.id).filter(a=>!!a),e=await y.getShadowGraphqlClient().mutate({mutation:od,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return n.map(a=>{const r=a.getWorkflowManager().getTransaction().recipient?.id;if(r)return e.data?.recipientValidateBatch?.find(i=>i.entityId===r)})},ud=async n=>{const t=n.getWorkflowManager().getTransaction().recipient?.id;if(!t)return;(await y.getShadowGraphqlClient().mutate({mutation:sd,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:t}})).data?.recipientOverrideAddress?.id&&(n.getWorkflowManager().getTransaction().addressValidationStatus=Ba.Overridden)};exports.AddonHandle=Qe;exports.AddressValidationJobStatus=ai;exports.AddressValidationResultConfirmationLevel=ei;exports.AddressValidationStatus=Ba;exports.ArrayInput=wc;exports.AspectType=U;exports.AssetNotFoundError=pt;exports.AssetType=te;exports.BringForwardCommand=Bs;exports.BringToBackCommand=bs;exports.BringToFrontCommand=Es;exports.BundleDesignCreationCartAddMode=xn;exports.CanvasCommand=N;exports.CollectionProduct=Ht;exports.ColorOptionGlobalPropertyHandle=ya;exports.CommandContext=or;exports.ConversionDataType=Xt;exports.ConversionLocation=Xr;exports.CreateElementCommand=z;exports.CreateLayoutCommand=Oa;exports.CurrencyContext=jr;exports.CurrencyService=Wr;exports.DeleteElementCommand=yt;exports.DigitalContentStepHandle=Ir;exports.FileUploadGlobalPropertyHandle=Qr;exports.FlowExecutionNodeResult=Yt;exports.FlowExecutionResult=qr;exports.FlowService=zr;exports.FontAlignmentCommand=ur;exports.FontColorCommand=dr;exports.FontSizeCommand=Ar;exports.FontSourceCommand=Ca;exports.FrameService=Jr;exports.FrameStep=Kr;exports.FrameStepHandle=_r;exports.GlobalPropertyHandle=je;exports.GroupCommand=Q;exports.IllustrationStepHandle=Cr;exports.InformationMessageType=pe;exports.InformationStepHandle=Br;exports.IntegrationProduct=va;exports.IntegrationType=Fn;exports.LayoutElementFactory=ms;exports.LayoutElementType=F;exports.LayoutNotFoundError=j;exports.LayoutRenderingPurpose=Nt;exports.MaterialStepHandle=wr;exports.MisconfigurationError=ne;exports.MockWorkflowManager=Qc;exports.ModelStepHandle=yr;exports.ModuleStepHandle=Pr;exports.MoveCommand=ps;exports.ObjectInput=Ya;exports.ObjectInputType=Gr;exports.OptionGlobalPropertyHandle=Wa;exports.OptionNotFoundError=ae;exports.ParseError=bt;exports.PictureStepHandle=Sr;exports.ProductCameraRig=kn;exports.ProductCollection=ja;exports.ProductCollectionProductSortKey=Ur;exports.ProductWorkflow=Tt;exports.PromiseCache=$t;exports.PromiseQueue=Ma;exports.QuestionStepHandle=vr;exports.QueueablePromise=ka;exports.ResizeCommand=Cs;exports.ResourceNotFoundError=Qt;exports.RotateCommand=fs;exports.ScaleAxis=G;exports.SendBackwardsCommand=Is;exports.ShapeStepHandle=Er;exports.ShareActionType=Dn;exports.SpiffCommerceClient=Fc;exports.StakeholderType=ee;exports.StepAspectType=Pn;exports.StepHandle=X;exports.StepType=v;exports.TextAlgorithm=Pt;exports.TextChangeCommand=hr;exports.TextGlobalPropertyHandle=Rr;exports.TextInput=Cc;exports.TextStepHandle=br;exports.Transform=Vr;exports.TransformCollection=Lr;exports.UnhandledBehaviorError=L;exports.UnitOfMeasurement=Mn;exports.UpdateImageSourceCommand=Ss;exports.Variant=rt;exports.WorkflowExperienceEventType=Mr;exports.WorkflowExperienceImpl=Tr;exports.assetService=R;exports.browserColorToHex=zn;exports.cmPerPixel=Xo;exports.createDesign=kr;exports.currentDirection=Jo;exports.dataUrlFromExternalUrl=Bi;exports.designService=Ie;exports.determineCorrectFontSizeAndLines=Kt;exports.digitalContentStepService=$a;exports.domParser=lt;exports.duplicateBundle=jc;exports.duplicateTransaction=Hc;exports.fetchAsString=tt;exports.findAngle=zo;exports.findElement=$;exports.findPmsColors=Gi;exports.frameDataCache=Ft;exports.frameStepService=ht;exports.generate=M;exports.generateCommands=Nr;exports.generateSVGWithUnknownColors=ot;exports.generateStateFromDesignInputSteps=ec;exports.getAddressValidationJobs=cd;exports.getAttributesFromArrayBuffer=ce;exports.getAxisAlignedBoundingBox=Vo;exports.getBoundedOffsets=Yr;exports.getBundleThemeConfiguration=Tc;exports.getCustomer=Yc;exports.getCustomerBundles=Jc;exports.getElementVertices=Ko;exports.getFrameData=he;exports.getGlobalPropertyStateForBundle=Ks;exports.getIntegration=Hr;exports.getNEPoint=Ho;exports.getNWPoint=jo;exports.getOrderedTransactions=Xc;exports.getOverrideThemeConfiguration=Mc;exports.getPointOfRotation=Wo;exports.getProductCollections=uc;exports.getSEPoint=Yo;exports.getSvgElement=We;exports.getTemplateBundles=td;exports.getTemplateTransactions=Zc;exports.getTransaction=kc;exports.getTransactionThemeConfiguration=Nc;exports.getTransactionsForBundle=Kc;exports.getTrueCoordinates=Go;exports.getUnorderedTransactions=_c;exports.getValidationJobsForWorkflowExperiences=ld;exports.getWorkflow=Pc;exports.getWorkflows=Ja;exports.graphQlManager=y;exports.illustrationStepService=Jt;exports.isCloseToValue=qo;exports.loadFont=xt;exports.matchHexToPms=Vi;exports.materialStepService=Ua;exports.metafieldManager=$r;exports.mmPerPixel=_o;exports.modelStepService=La;exports.modifySVGColors=ze;exports.moduleStepService=Va;exports.nameBundle=Gc;exports.nameTransaction=Wc;exports.optionService=W;exports.outlineFontsInSvg=ns;exports.overrideWorkflowExperienceRecipientAddress=ud;exports.patternImageDataCache=dt;exports.persistenceService=k;exports.pictureStepService=za;exports.pmsToRgb=Li;exports.questionStepService=qa;exports.registerFetchImplementation=yi;exports.registerWindowImplementation=wi;exports.rehydrateSerializedLayout=fa;exports.rgbToPms=Vn;exports.rotateAroundPoint=jt;exports.sanitizeSvgTree=Ve;exports.setBearerAuthenticationToken=Un;exports.setCanvasModule=Pa;exports.shapeStepService=kt;exports.shortenUrl=gr;exports.spiffCoreConfiguration=At;exports.stepAspectValuesToDesignInputSteps=tc;exports.svgColorValueToDefinition=ha;exports.svgStringDimensions=Ra;exports.svgToDataUrl=Le;exports.textStepService=q;exports.toast=pr;exports.validateWorkflowExperienceRecipient=dd;exports.validateWorkflowExperienceRecipients=Ad;exports.xmlSerializer=St;
2728
+ `;var ai=(n=>(n.Confirmed="Confirmed",n.Plausible="Plausible",n.Unlikely="Unlikely",n))(ai||{}),ni=(n=>(n.Created="Created",n.Processing="Processing",n.Completed="Completed",n.Failed="Failed",n.Cancelled="Cancelled",n))(ni||{});const Ad=async n=>{const t=n.map(a=>a.getWorkflowManager().getTransaction().recipient?.id).filter(a=>!!a),e=await y.getShadowGraphqlClient().query({query:sd,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return n.map(a=>{const r=a.getWorkflowManager().getTransaction().recipient?.id;if(r)return e.data?.recipients?.find(i=>i.id===r)?.addressValidationJob})},ud=async n=>(await y.getShadowGraphqlClient().query({query:od,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:n}})).data?.addressValidationJobs,hd=async n=>n.getWorkflowManager().getTransaction().recipient?.id?(await y.getShadowGraphqlClient().mutate({mutation:ld,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n.getWorkflowManager().getTransaction().recipient.id}})).data?.recipientValidate:void 0,gd=async n=>{const t=n.map(a=>a.getWorkflowManager().getTransaction().recipient?.id).filter(a=>!!a),e=await y.getShadowGraphqlClient().mutate({mutation:cd,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return n.map(a=>{const r=a.getWorkflowManager().getTransaction().recipient?.id;if(r)return e.data?.recipientValidateBatch?.find(i=>i.entityId===r)})},md=async n=>{const t=n.getWorkflowManager().getTransaction().recipient?.id;if(!t)return;(await y.getShadowGraphqlClient().mutate({mutation:dd,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:t}})).data?.recipientOverrideAddress?.id&&(n.getWorkflowManager().getTransaction().addressValidationStatus=Ia.Overridden)};exports.AddonHandle=Qe;exports.AddressValidationJobStatus=ni;exports.AddressValidationResultConfirmationLevel=ai;exports.AddressValidationStatus=Ia;exports.ArrayInput=Sc;exports.AspectType=$;exports.AssetNotFoundError=pt;exports.AssetType=te;exports.BringForwardCommand=Is;exports.BringToBackCommand=Bs;exports.BringToFrontCommand=bs;exports.BundleDesignCreationCartAddMode=Fn;exports.CanvasCommand=N;exports.CollectionProduct=Ht;exports.ColorOptionGlobalPropertyHandle=Sa;exports.CommandContext=sr;exports.ConversionDataType=Xt;exports.ConversionLocation=Zr;exports.CreateElementCommand=z;exports.CreateLayoutCommand=$a;exports.CurrencyContext=Hr;exports.CurrencyService=jr;exports.DeleteElementCommand=yt;exports.DigitalContentStepHandle=Pr;exports.FileUploadGlobalPropertyHandle=Rr;exports.FlowExecutionNodeResult=Yt;exports.FlowExecutionResult=Gr;exports.FlowService=qr;exports.FontAlignmentCommand=hr;exports.FontColorCommand=Ar;exports.FontSizeCommand=ur;exports.FontSourceCommand=wa;exports.FrameService=Kr;exports.FrameStep=_r;exports.FrameStepHandle=Xr;exports.GlobalPropertyHandle=je;exports.GroupCommand=Q;exports.IllustrationStepHandle=wr;exports.InformationMessageType=pe;exports.InformationStepHandle=Ir;exports.IntegrationProduct=Ea;exports.IntegrationType=kn;exports.LayoutElementFactory=ps;exports.LayoutElementType=x;exports.LayoutNotFoundError=H;exports.LayoutRenderingPurpose=Nt;exports.MaterialStepHandle=yr;exports.MisconfigurationError=ne;exports.MockWorkflowManager=$c;exports.ModelStepHandle=Sr;exports.ModuleStepHandle=Dr;exports.MoveCommand=fs;exports.ObjectInput=Ja;exports.ObjectInputType=Wr;exports.OptionGlobalPropertyHandle=ja;exports.OptionNotFoundError=ae;exports.ParseError=bt;exports.PictureStepHandle=vr;exports.ProductCameraRig=Mn;exports.ProductCollection=Ha;exports.ProductCollectionProductSortKey=Lr;exports.ProductWorkflow=Tt;exports.PromiseCache=$t;exports.PromiseQueue=Ta;exports.QuestionStepHandle=Er;exports.QueueablePromise=Ma;exports.ResizeCommand=ws;exports.ResourceNotFoundError=Qt;exports.RotateCommand=Cs;exports.ScaleAxis=W;exports.SendBackwardsCommand=Ps;exports.ShapeStepHandle=br;exports.ShareActionType=xn;exports.SpiffCommerceClient=Mc;exports.StakeholderType=ee;exports.StepAspectType=Dn;exports.StepHandle=Z;exports.StepType=E;exports.TextAlgorithm=Pt;exports.TextChangeCommand=gr;exports.TextGlobalPropertyHandle=Or;exports.TextInput=yc;exports.TextStepHandle=Br;exports.Transform=zr;exports.TransformCollection=Vr;exports.UnhandledBehaviorError=U;exports.UnitOfMeasurement=Tn;exports.UpdateImageSourceCommand=vs;exports.Variant=rt;exports.WorkflowExperienceEventType=Tr;exports.WorkflowExperienceImpl=Nr;exports.assetService=R;exports.browserColorToHex=qn;exports.cmPerPixel=Zo;exports.createDesign=Mr;exports.currentDirection=Ko;exports.dataUrlFromExternalUrl=Ii;exports.deleteBundle=Oc;exports.designService=Ie;exports.determineCorrectFontSizeAndLines=Kt;exports.digitalContentStepService=Ua;exports.domParser=lt;exports.duplicateBundle=Jc;exports.duplicateTransaction=Kc;exports.fetchAsString=at;exports.findAngle=qo;exports.findElement=O;exports.findPmsColors=Wi;exports.frameDataCache=xt;exports.frameStepService=ht;exports.generate=M;exports.generateCommands=Qr;exports.generateSVGWithUnknownColors=ot;exports.generateStateFromDesignInputSteps=nc;exports.getAddressValidationJobs=ud;exports.getAttributesFromArrayBuffer=ce;exports.getAxisAlignedBoundingBox=zo;exports.getBoundedOffsets=Jr;exports.getBundleThemeConfiguration=Qc;exports.getCustomer=_c;exports.getCustomerBundles=Xc;exports.getElementVertices=_o;exports.getFrameData=he;exports.getGlobalPropertyStateForBundle=_s;exports.getIntegration=Yr;exports.getNEPoint=Yo;exports.getNWPoint=Ho;exports.getOrderedTransactions=ed;exports.getOverrideThemeConfiguration=Nc;exports.getPointOfRotation=jo;exports.getProductCollections=gc;exports.getSEPoint=Jo;exports.getSvgElement=We;exports.getTemplateBundles=nd;exports.getTemplateTransactions=ad;exports.getTransaction=Tc;exports.getTransactionThemeConfiguration=Rc;exports.getTransactionsForBundle=Zc;exports.getTrueCoordinates=Wo;exports.getUnorderedTransactions=td;exports.getValidationJobsForWorkflowExperiences=Ad;exports.getWorkflow=Fc;exports.getWorkflows=Ka;exports.graphQlManager=y;exports.illustrationStepService=Jt;exports.isCloseToValue=Go;exports.loadFont=Dt;exports.matchHexToPms=zi;exports.materialStepService=La;exports.metafieldManager=Ur;exports.mmPerPixel=Xo;exports.modelStepService=Va;exports.modifySVGColors=ze;exports.moduleStepService=za;exports.nameBundle=Hc;exports.nameTransaction=Yc;exports.optionService=j;exports.outlineFontsInSvg=rs;exports.overrideWorkflowExperienceRecipientAddress=md;exports.patternImageDataCache=dt;exports.persistenceService=k;exports.pictureStepService=qa;exports.pmsToRgb=Vi;exports.questionStepService=Ga;exports.registerFetchImplementation=Si;exports.registerWindowImplementation=yi;exports.rehydrateSerializedLayout=Ca;exports.rgbToPms=zn;exports.rotateAroundPoint=jt;exports.sanitizeSvgTree=Ve;exports.setBearerAuthenticationToken=Ln;exports.setCanvasModule=Da;exports.shapeStepService=kt;exports.shortenUrl=mr;exports.spiffCoreConfiguration=At;exports.stepAspectValuesToDesignInputSteps=ac;exports.svgColorValueToDefinition=ga;exports.svgStringDimensions=Oa;exports.svgToDataUrl=Le;exports.textStepService=G;exports.toast=fr;exports.validateWorkflowExperienceRecipient=hd;exports.validateWorkflowExperienceRecipients=gd;exports.xmlSerializer=St;
2725
2729
  //# sourceMappingURL=index.js.map