@spiffcommerce/core 25.0.8 → 25.0.9

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.d.ts CHANGED
@@ -1492,7 +1492,15 @@ interface BundleOptions {
1492
1492
  additionalHeaders?: {
1493
1493
  [key: string]: string;
1494
1494
  };
1495
+ /**
1496
+ * If set to true, the products associated with the bundle will be eagerly fetched.
1497
+ */
1495
1498
  eagerFetchProducts?: boolean;
1499
+ /**
1500
+ * If set to true, a new global state will be created. Typically for use when we
1501
+ * know the bundle is new and we want to skip the existing state check.
1502
+ */
1503
+ createNewGlobalState?: boolean;
1496
1504
  }
1497
1505
 
1498
1506
  /**
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("@apollo/client/core"),Gn=require("@apollo/client/link/context"),Tn=require("@apollo/client/link/error"),Jn=require("preact-render-to-string"),On=require("@apollo/client/link/remove-typename"),Ln=require("exifreader"),dA=require("pith"),sa=require("lodash.debounce"),oa=require("lodash.isequal"),zn=require("data-uri-to-buffer"),jn=require("css"),Kn=require("fuse.js"),xt=require("lodash.clonedeep"),S=require("preact/jsx-runtime"),Xe=require("opentype.js"),ra=require("qrcode"),qe=require("unicode-default-word-boundary"),BA=require("svg-path-bbox"),LA=require("lodash.chunk");var Xt=(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))(Xt||{}),st=(n=>(n.FileUpload="FileUpload",n.Option="Option",n.ColorOption="ColorOption",n.Text="Text",n))(st||{}),M=(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))(M||{}),ca=(n=>(n.Color="Color",n.Colors="Colors",n.Selection="Selection",n.Selections="Selections",n.Text="Text",n.Upload="Upload",n))(ca||{}),Pt=(n=>(n.ThreeD="ThreeD",n.FreeDesign="FreeDesign",n.Print="Print",n))(Pt||{}),k=(n=>(n.Frame="frame",n.Group="group",n.Image="image",n.Pattern="pattern",n.Illustration="illustration",n.Textbox="textbox",n))(k||{}),la=(n=>(n.Hyperlink="Hyperlink",n.Edit="Edit",n.Approve="Approve",n))(la||{}),ga=(n=>(n.Hub="Hub",n.Shopify="Shopify",n))(ga||{}),Me=(n=>(n.BackgroundRemover="BackgroundRemover",n.ConversionAccelerator="Conversion Accelerator",n.ProcessBuilder="ProcessBuilder",n))(Me||{}),da=(n=>(n[n.Orbit=0]="Orbit",n[n.Pan=1]="Pan",n))(da||{}),Ba=(n=>(n.Manual="Manual",n.OnStart="OnStart",n.OnQuit="OnQuit",n.OnEnd="OnEnd",n))(Ba||{}),ha=(n=>(n.Email="Email",n.FirstName="FirstName",n.LastName="LastName",n.Phone="Phone",n))(ha||{}),qt=(n=>(n.Owner="Owner",n.Approver="Approver",n.Editor="Editor",n.Viewer="Viewer",n))(qt||{}),Qt=(n=>(n.Autosize="Autosize",n.Traditional="Traditional",n))(Qt||{}),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||{}),Ca=(n=>(n.Pixel="px",n.Millimeter="mm",n.Centimeter="cm",n))(Ca||{});class wa extends Error{constructor(t){super(t),this.name=this.constructor.name}}class ee extends wa{constructor(t){super(`ConfigurationError - ${t}`)}}class Zt extends ee{constructor(t){super(`Option not Configured: ${t.stepTitle}`),this.optionId=(t==null?void 0:t.optionId)||"N/A"}}class X extends ee{constructor(t){super(`Panel not Found: ${t.panelId}`),this.panelId=(t==null?void 0:t.panelId)||"N/A"}}class dt extends ee{constructor(t){super(`Asset not found for variant: ${t.name}`),this.variant=t}}class vt extends ee{constructor(t){super(`Resource not found for asset: ${t.name}`),this.asset=t}}class $t extends ee{constructor(t,e){super(`Workflow Misconfiguration: ${t.stepName} - ${e}`),this.step=t}}class Se extends wa{constructor(t){super(`ImplementationError - ${t}`)}}class O extends Se{constructor(t){super(`Unhandled Behavior Encountered: ${t}`)}}class yt extends Se{constructor(t){super(`Parsing Error: ${t}`)}}class U extends Se{constructor(t){super(`Client Error: ${t}`)}}class xe extends Se{constructor(t){super(`Resource Generation Failed: ${t}`)}}class Vn{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 zA{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 Wn=()=>{try{return localStorage?new Vn:new zA}catch{return console.warn("Local storage was unavilable due to browser security settings. Using in-memory storage instead."),new zA}},Y=Wn();class Xn{constructor(){this.defaultServerUrl="https://api.spiff.com.au",this.defaultServicesApiUrl="https://services.spiff.com.au",this.defaultHubUrl="https://hub.spiff.com.au",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 nt=new Xn;let Ze,$e;function qn(n){Ze=n}function Zn(n){$e=n}function Ye(){if(!Ze)throw new Error("DOM constructor is not registered. Please register it before calling this function.");return new Ze}function rt(n,t){if(!$e){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 $e(n,t)}const ua=new Map,jA=new Map,KA=new Map,Ea=async n=>{const t=jA.get(n);if(t)return t;const A=(async()=>{var i;const a=await rt(n);return ua.set(n,((i=a.headers)==null?void 0:i.get("content-type"))||""),await a.arrayBuffer()})();return jA.set(n,A),A},$n=async n=>{const t=KA.get(n);if(t)return t;const A=(async()=>await(await rt(n)).text())();return KA.set(n,A),A},Ae=n=>n.every(t=>t!=="undefined"),de=n=>Ae([typeof document])?document.createElement(n):Ye().window.document.createElement(n),_n=(n,t)=>{if(Ae([typeof document]))return document.createElementNS(n,t);const A=Ye().window.document.createElement(t);return A.setAttribute("xmlns",n),A},wt=()=>{if(Ae([typeof DOMParser]))return new DOMParser;const n=Ye();return new n.window.DOMParser},Pe=(n,t)=>new Promise((e,A)=>{t?Ea(n).then(e).catch(A):rt(n).then(a=>{a.arrayBuffer().then(e).catch(A)}).catch(a=>{A(a)})}),tt=(n,t)=>new Promise((e,A)=>{t?$n(n).then(e).catch(A):rt(n).then(a=>{a.text().then(e).catch(A)}).catch(A)}),ma=n=>Jn.renderToStaticMarkup(n),be=new Map,ti=async(n,t)=>{if(Ae([typeof FontFace])){if(be.has(t))return be.get(t);const e=n.names.fullName.en,A=new FontFace(e,`url(${t})`);document.fonts.add(A);const a=A.load();return be.set(t,a),a}},ae=()=>{if(Ae([typeof XMLSerializer]))return new XMLSerializer;const n=Ye();return new n.window.XMLSerializer},VA=n=>btoa(n),ne=n=>{function t(){const A=new Uint8Array(n),a=4;if(A.length>=a){const i=new Array(a);for(let r=0;r<a;r++)i[r]=new Uint8Array(n)[r].toString(16);const s=i.join("").toUpperCase();switch(s){case"89504E47":return"image/png";case"47494638":return"image/gif";case"25504446":return"application/pdf";case"504B0304":return"application/zip"}switch(s.slice(0,4)){case"FFD8":return"image/jpeg"}}return null}const e=t();return e||"image/svg+xml"},ei=async n=>{const t=await Ea(n),e=ua.get(n)||ne(t);return await ni(new Blob([t],{type:e}))},Ai=n=>{let t="";const e=n.byteLength;for(let A=0;A<e;A++)t+=String.fromCharCode(n[A]);return t},ai=async n=>{const t=ne(n),e=new Uint8Array(n),A=Ai(e),a=btoa(A);return`data:${t};base64,${a}`},hA=n=>`data:image/svg+xml;base64,${btoa(n)}`,fa=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 a=!1;for(let s=1;s<A.length;s++)A[s]==="base64"&&(a=!0);const i=decodeURI(t.substring(e+1));return a?new Uint8Array(atob(i).split("").map(o=>o.charCodeAt(0))).buffer:new Uint8Array(i.split("").map(o=>o.charCodeAt(0))).buffer},ni=n=>new Promise((t,e)=>{const A=new FileReader;A.onload=function(a){const i=a.target;!i||!i.result?e():t(i.result.toString())},A.readAsDataURL(n)});let Qa;const WA=n=>{Qa=n};let CA;const ii=n=>{CA=n},si=()=>CA;let pa;const Ia=n=>{pa=n},oi=()=>new Promise(n=>{const t=nt.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))}),ri=async()=>{const n={applicationKey:CA,customerToken:Qa,bearer:pa};return typeof window<"u"&&(window.location.href.includes("/workflows/product/")||window.location.href.includes("hub=true"))?{...await oi(),...n}:n};class ci{constructor(){this.shadowGraphqlClient=this.constructShadowGraphqlClient(),nt.addServerUrlCallback(()=>{this.shadowGraphqlClient=this.constructShadowGraphqlClient()})}getShadowGraphqlClient(){return this.shadowGraphqlClient}constructShadowGraphqlClient(){const t=D.createHttpLink({uri:`${nt.getServerUrl()}/graphql`,fetch:rt}),e=Gn.setContext(async(i,s)=>{const{headers:o}=s,r=o||{},c=await ri(),l=s.bearer??c.bearer,g=s.partnerId??c.partnerId,d=s.activeIntegration??c.activeIntegration,B=s.transactionOwnerId,h=s.customerToken??c.customerToken,C=s.applicationKey??c.applicationKey,w=s.bundleOwnerId;try{if(window&&window.__SENTRY__){const u=window.__SENTRY__.hub;if(u){const E=u.traceHeaders();Object.entries(E).forEach(([m,f])=>{r[m]=f})}}}catch{}return l&&(r.Authorization=`Bearer ${l}`),g&&(r.partnerId=g),d&&(r.activeIntegration=d),B&&(r.transactionOwnerId=B),h&&(r.customerToken=h),C&&(r["X-Application-Key"]=C),w&&(r.bundleOwnerId=w),{headers:r}}),A=Tn.onError(({operation:i,graphQLErrors:s,networkError:o})=>{const r=s||[];o&&console.log("GraphQL Network error"),r.forEach(()=>console.log("GraphQL Error: "+i.operationName))}),a=On.removeTypenameFromVariables();return new D.ApolloClient({link:D.from([a,A,e,t]),cache:new D.InMemoryCache,name:"Core",devtools:{enabled:!0}})}}const P=new ci;let _e,tA;const Bt=(n,t,e)=>{if(_e!==void 0)return _e(n,t,e);try{const A=Da(!0);return wA(A),A.createCanvas(n,t,e)}catch{throw new Error("Canvas module not set")}},ie=(n,t)=>{if(tA!==void 0)return tA(n,t);try{const e=Da(!0);return wA(e),e.loadImage(n,t)}catch{throw new Error("Canvas module not set")}};function wA(n){_e=n==null?void 0:n.createCanvas,tA=n==null?void 0:n.loadImage}function Da(n){try{if(document.createElement("canvas").getContext("2d"))return{createCanvas:(e,A,a)=>{const i=document.createElement("canvas");return e!=null&&(i.width=e),A!=null&&(i.height=A),i},loadImage:(e,A)=>new Promise((a,i)=>{const s=document.createElement("img");A!==!1&&(s.crossOrigin="Anonymous"),s.onload=()=>{a(s)},s.onerror=i,s.src=e})}}catch(t){if(n)throw t}}let Ue;function uA(){return Ue===void 0&&(Ue=DOMParser),Ue}let Be=null;const li=n=>new Promise(t=>{var a;if(ne(n)!=="image/jpeg")return t(1);const A=(a=Ln.load(n).Orientation)==null?void 0:a.value;return t(A?Number(A):1)}),gi=async()=>{if(Be!==null)return!Be;const t=await ie("data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAAAAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/xABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAAAAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQvoP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXwH/9k=");return Be=t.width===2&&t.height===3,!Be},di=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]},Bi=async n=>{var g;const t=await ai(n),e=await ie(t),[A,a]=di(e);if(!await gi()){const d=Bt(A,a);return(g=d.getContext("2d"))==null||g.drawImage(e,0,0,A,a),d}const s=await li(n),[o,r]=s>4?[a,A]:[A,a],c=Bt(o,r),l=c.getContext("2d");switch(s){case 2:l.translate(o,0),l.scale(-1,1);break;case 3:l.translate(o,r),l.rotate(Math.PI);break;case 4:l.translate(0,r),l.scale(1,-1);break;case 5:l.rotate(-.5*Math.PI),l.scale(-1,1);break;case 6:l.rotate(-.5*Math.PI),l.translate(-o,0);break;case 7:l.rotate(-.5*Math.PI),l.translate(-o,r),l.scale(1,-1);break;case 8:l.rotate(.5*Math.PI),l.translate(0,-r);break}return l.drawImage(e,0,0,o,r),c},se=async n=>{const t=await Bi(n);return ne(n)==="image/jpeg"?{dataUrl:t.toDataURL("image/jpeg",1),height:t.height,width:t.width}:{dataUrl:t.toDataURL(),height:t.height,width:t.width}},hi=D.gql`
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const D=require("@apollo/client/core"),Gn=require("@apollo/client/link/context"),Tn=require("@apollo/client/link/error"),Jn=require("preact-render-to-string"),On=require("@apollo/client/link/remove-typename"),Ln=require("exifreader"),dA=require("pith"),sa=require("lodash.debounce"),oa=require("lodash.isequal"),zn=require("data-uri-to-buffer"),jn=require("css"),Kn=require("fuse.js"),xt=require("lodash.clonedeep"),S=require("preact/jsx-runtime"),Xe=require("opentype.js"),ra=require("qrcode"),qe=require("unicode-default-word-boundary"),BA=require("svg-path-bbox"),LA=require("lodash.chunk");var Xt=(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))(Xt||{}),st=(n=>(n.FileUpload="FileUpload",n.Option="Option",n.ColorOption="ColorOption",n.Text="Text",n))(st||{}),M=(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))(M||{}),ca=(n=>(n.Color="Color",n.Colors="Colors",n.Selection="Selection",n.Selections="Selections",n.Text="Text",n.Upload="Upload",n))(ca||{}),Pt=(n=>(n.ThreeD="ThreeD",n.FreeDesign="FreeDesign",n.Print="Print",n))(Pt||{}),k=(n=>(n.Frame="frame",n.Group="group",n.Image="image",n.Pattern="pattern",n.Illustration="illustration",n.Textbox="textbox",n))(k||{}),la=(n=>(n.Hyperlink="Hyperlink",n.Edit="Edit",n.Approve="Approve",n))(la||{}),ga=(n=>(n.Hub="Hub",n.Shopify="Shopify",n))(ga||{}),Me=(n=>(n.BackgroundRemover="BackgroundRemover",n.ConversionAccelerator="Conversion Accelerator",n.ProcessBuilder="ProcessBuilder",n))(Me||{}),da=(n=>(n[n.Orbit=0]="Orbit",n[n.Pan=1]="Pan",n))(da||{}),Ba=(n=>(n.Manual="Manual",n.OnStart="OnStart",n.OnQuit="OnQuit",n.OnEnd="OnEnd",n))(Ba||{}),ha=(n=>(n.Email="Email",n.FirstName="FirstName",n.LastName="LastName",n.Phone="Phone",n))(ha||{}),qt=(n=>(n.Owner="Owner",n.Approver="Approver",n.Editor="Editor",n.Viewer="Viewer",n))(qt||{}),Qt=(n=>(n.Autosize="Autosize",n.Traditional="Traditional",n))(Qt||{}),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||{}),Ca=(n=>(n.Pixel="px",n.Millimeter="mm",n.Centimeter="cm",n))(Ca||{});class wa extends Error{constructor(t){super(t),this.name=this.constructor.name}}class ee extends wa{constructor(t){super(`ConfigurationError - ${t}`)}}class Zt extends ee{constructor(t){super(`Option not Configured: ${t.stepTitle}`),this.optionId=(t==null?void 0:t.optionId)||"N/A"}}class X extends ee{constructor(t){super(`Panel not Found: ${t.panelId}`),this.panelId=(t==null?void 0:t.panelId)||"N/A"}}class dt extends ee{constructor(t){super(`Asset not found for variant: ${t.name}`),this.variant=t}}class vt extends ee{constructor(t){super(`Resource not found for asset: ${t.name}`),this.asset=t}}class $t extends ee{constructor(t,e){super(`Workflow Misconfiguration: ${t.stepName} - ${e}`),this.step=t}}class Se extends wa{constructor(t){super(`ImplementationError - ${t}`)}}class O extends Se{constructor(t){super(`Unhandled Behavior Encountered: ${t}`)}}class yt extends Se{constructor(t){super(`Parsing Error: ${t}`)}}class U extends Se{constructor(t){super(`Client Error: ${t}`)}}class xe extends Se{constructor(t){super(`Resource Generation Failed: ${t}`)}}class Vn{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 zA{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 Wn=()=>{try{return localStorage?new Vn:new zA}catch{return console.warn("Local storage was unavilable due to browser security settings. Using in-memory storage instead."),new zA}},Y=Wn();class Xn{constructor(){this.defaultServerUrl="https://api.spiff.com.au",this.defaultServicesApiUrl="https://services.spiff.com.au",this.defaultHubUrl="https://hub.spiff.com.au",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 nt=new Xn;let Ze,$e;function qn(n){Ze=n}function Zn(n){$e=n}function Ye(){if(!Ze)throw new Error("DOM constructor is not registered. Please register it before calling this function.");return new Ze}function rt(n,t){if(!$e){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 $e(n,t)}const ua=new Map,jA=new Map,KA=new Map,Ea=async n=>{const t=jA.get(n);if(t)return t;const A=(async()=>{var i;const a=await rt(n);return ua.set(n,((i=a.headers)==null?void 0:i.get("content-type"))||""),await a.arrayBuffer()})();return jA.set(n,A),A},$n=async n=>{const t=KA.get(n);if(t)return t;const A=(async()=>await(await rt(n)).text())();return KA.set(n,A),A},Ae=n=>n.every(t=>t!=="undefined"),de=n=>Ae([typeof document])?document.createElement(n):Ye().window.document.createElement(n),_n=(n,t)=>{if(Ae([typeof document]))return document.createElementNS(n,t);const A=Ye().window.document.createElement(t);return A.setAttribute("xmlns",n),A},wt=()=>{if(Ae([typeof DOMParser]))return new DOMParser;const n=Ye();return new n.window.DOMParser},Pe=(n,t)=>new Promise((e,A)=>{t?Ea(n).then(e).catch(A):rt(n).then(a=>{a.arrayBuffer().then(e).catch(A)}).catch(a=>{A(a)})}),tt=(n,t)=>new Promise((e,A)=>{t?$n(n).then(e).catch(A):rt(n).then(a=>{a.text().then(e).catch(A)}).catch(A)}),ma=n=>Jn.renderToStaticMarkup(n),be=new Map,ti=async(n,t)=>{if(Ae([typeof FontFace])){if(be.has(t))return be.get(t);const e=n.names.fullName.en,A=new FontFace(e,`url(${t})`);document.fonts.add(A);const a=A.load();return be.set(t,a),a}},ae=()=>{if(Ae([typeof XMLSerializer]))return new XMLSerializer;const n=Ye();return new n.window.XMLSerializer},VA=n=>btoa(n),ne=n=>{function t(){const A=new Uint8Array(n),a=4;if(A.length>=a){const i=new Array(a);for(let r=0;r<a;r++)i[r]=new Uint8Array(n)[r].toString(16);const s=i.join("").toUpperCase();switch(s){case"89504E47":return"image/png";case"47494638":return"image/gif";case"25504446":return"application/pdf";case"504B0304":return"application/zip"}switch(s.slice(0,4)){case"FFD8":return"image/jpeg"}}return null}const e=t();return e||"image/svg+xml"},ei=async n=>{const t=await Ea(n),e=ua.get(n)||ne(t);return await ni(new Blob([t],{type:e}))},Ai=n=>{let t="";const e=n.byteLength;for(let A=0;A<e;A++)t+=String.fromCharCode(n[A]);return t},ai=async n=>{const t=ne(n),e=new Uint8Array(n),A=Ai(e),a=btoa(A);return`data:${t};base64,${a}`},hA=n=>`data:image/svg+xml;base64,${btoa(n)}`,fa=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 a=!1;for(let s=1;s<A.length;s++)A[s]==="base64"&&(a=!0);const i=decodeURI(t.substring(e+1));return a?new Uint8Array(atob(i).split("").map(o=>o.charCodeAt(0))).buffer:new Uint8Array(i.split("").map(o=>o.charCodeAt(0))).buffer},ni=n=>new Promise((t,e)=>{const A=new FileReader;A.onload=function(a){const i=a.target;!i||!i.result?e():t(i.result.toString())},A.readAsDataURL(n)});let Qa;const WA=n=>{Qa=n};let CA;const ii=n=>{CA=n},si=()=>CA;let pa;const Ia=n=>{pa=n},oi=()=>new Promise(n=>{const t=nt.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))}),ri=async()=>{const n={applicationKey:CA,customerToken:Qa,bearer:pa};return typeof window<"u"&&(window.location.href.includes("/workflows/product/")||window.location.href.includes("hub=true"))?{...await oi(),...n}:n};class ci{constructor(){this.shadowGraphqlClient=this.constructShadowGraphqlClient(),nt.addServerUrlCallback(()=>{this.shadowGraphqlClient=this.constructShadowGraphqlClient()})}getShadowGraphqlClient(){return this.shadowGraphqlClient}constructShadowGraphqlClient(){const t=D.createHttpLink({uri:`${nt.getServerUrl()}/graphql`,fetch:rt}),e=Gn.setContext(async(i,s)=>{const{headers:o}=s,r=o||{},c=await ri(),l=s.bearer??c.bearer,g=s.partnerId??c.partnerId,d=s.activeIntegration??c.activeIntegration,B=s.transactionOwnerId,h=s.customerToken??c.customerToken,C=s.applicationKey??c.applicationKey,w=s.bundleOwnerId;try{if(window&&window.__SENTRY__){const u=window.__SENTRY__.hub;if(u){const E=u.traceHeaders();Object.entries(E).forEach(([m,f])=>{r[m]=f})}}}catch{}return l&&(r.Authorization=`Bearer ${l}`),g&&(r.partnerId=g),d&&(r.activeIntegration=d),B&&(r.transactionOwnerId=B),h&&(r.customerToken=h),C&&(r["X-Application-Key"]=C),w&&(r.bundleOwnerId=w),{headers:r}}),A=Tn.onError(({operation:i,graphQLErrors:s,networkError:o})=>{const r=s||[];o&&console.log("GraphQL Network error"),r.forEach(()=>console.log("GraphQL Error: "+i.operationName))}),a=On.removeTypenameFromVariables();return new D.ApolloClient({link:D.from([a,A,e,t]),cache:new D.InMemoryCache,name:"Core"})}}const P=new ci;let _e,tA;const Bt=(n,t,e)=>{if(_e!==void 0)return _e(n,t,e);try{const A=Da(!0);return wA(A),A.createCanvas(n,t,e)}catch{throw new Error("Canvas module not set")}},ie=(n,t)=>{if(tA!==void 0)return tA(n,t);try{const e=Da(!0);return wA(e),e.loadImage(n,t)}catch{throw new Error("Canvas module not set")}};function wA(n){_e=n==null?void 0:n.createCanvas,tA=n==null?void 0:n.loadImage}function Da(n){try{if(document.createElement("canvas").getContext("2d"))return{createCanvas:(e,A,a)=>{const i=document.createElement("canvas");return e!=null&&(i.width=e),A!=null&&(i.height=A),i},loadImage:(e,A)=>new Promise((a,i)=>{const s=document.createElement("img");A!==!1&&(s.crossOrigin="Anonymous"),s.onload=()=>{a(s)},s.onerror=i,s.src=e})}}catch(t){if(n)throw t}}let Ue;function uA(){return Ue===void 0&&(Ue=DOMParser),Ue}let Be=null;const li=n=>new Promise(t=>{var a;if(ne(n)!=="image/jpeg")return t(1);const A=(a=Ln.load(n).Orientation)==null?void 0:a.value;return t(A?Number(A):1)}),gi=async()=>{if(Be!==null)return!Be;const t=await ie("data:image/jpeg;base64,/9j/4QAiRXhpZgAATU0AKgAAAAgAAQESAAMAAAABAAYAAAAAAAD/2wCEAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAf/AABEIAAIAAwMBEQACEQEDEQH/xABRAAEAAAAAAAAAAAAAAAAAAAAKEAEBAQADAQEAAAAAAAAAAAAGBQQDCAkCBwEBAAAAAAAAAAAAAAAAAAAAABEBAAAAAAAAAAAAAAAAAAAAAP/aAAwDAQACEQMRAD8AG8T9NfSMEVMhQvoP3fFiRZ+MTHDifa/95OFSZU5OzRzxkyejv8ciEfhSceSXGjS8eSdLnZc2HDm4M3BxcXwH/9k=");return Be=t.width===2&&t.height===3,!Be},di=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]},Bi=async n=>{var g;const t=await ai(n),e=await ie(t),[A,a]=di(e);if(!await gi()){const d=Bt(A,a);return(g=d.getContext("2d"))==null||g.drawImage(e,0,0,A,a),d}const s=await li(n),[o,r]=s>4?[a,A]:[A,a],c=Bt(o,r),l=c.getContext("2d");switch(s){case 2:l.translate(o,0),l.scale(-1,1);break;case 3:l.translate(o,r),l.rotate(Math.PI);break;case 4:l.translate(0,r),l.scale(1,-1);break;case 5:l.rotate(-.5*Math.PI),l.scale(-1,1);break;case 6:l.rotate(-.5*Math.PI),l.translate(-o,0);break;case 7:l.rotate(-.5*Math.PI),l.translate(-o,r),l.scale(1,-1);break;case 8:l.rotate(.5*Math.PI),l.translate(0,-r);break}return l.drawImage(e,0,0,o,r),c},se=async n=>{const t=await Bi(n);return ne(n)==="image/jpeg"?{dataUrl:t.toDataURL("image/jpeg",1),height:t.height,width:t.width}:{dataUrl:t.toDataURL(),height:t.height,width:t.width}},hi=D.gql`
2
2
  fragment AssetMetadataFields on Asset {
3
3
  metadata {
4
4
  key
@@ -102,7 +102,7 @@
102
102
  ...AssetFields
103
103
  }
104
104
  }
105
- `,eA=async n=>(await P.getShadowGraphqlClient().query({query:Ci,errorPolicy:"all",fetchPolicy:"no-cache",variables:{keys:n}})).data.assets,mi=async n=>(await P.getShadowGraphqlClient().query({query:wi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:n}})).data.materials,fi=async(n,t,e,A,a)=>{var s;return(s=(await P.getShadowGraphqlClient().mutate({mutation:ui,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:n,type:t,mimeType:e,anonymous:A,temporary:a}})).data)==null?void 0:s.assetCreate};class Qi{constructor(){this.cache=new Map,this.bgrmProcessCache=new Map,this.materialCache=new Map,this.loadImageAsFileInfo=async t=>{const e=await t.arrayBuffer(),A=await se(e),a=(i,s)=>{const o=atob(i.split(",")[1]),r=[];for(let c=0;c<o.length;c++)r.push(o.charCodeAt(c));return new Blob([new Uint8Array(r)],{type:s})};return{name:t.name.substring(t.name.lastIndexOf("/")+1),blob:a(A.dataUrl,t.type)}}}async getLocalOrFromServer(t){if(this.cache.has(t)){const a=this.cache.get(t);if(!a)throw new O("Failed to get asset from cache!");return a}const A=(async()=>(await eA([t]))[0])();return this.cache.set(t,A),A}async getFromServer(t){const A=(async()=>(await eA([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==null?void 0:e.split("?")[0]}cacheAsset(t){if(!t.key)throw new O("Asset has no key!");this.cache.has(t.key)||this.cache.set(t.key,Promise.resolve(t))}cacheMaterial(t){if(!t.id)throw new O("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 mi([t]))[0])();return this.materialCache.set(t,A),A}async uploadAssetWithProgress(t,e,A,a,i){const s=await this.dispatchCreateAssetRequest(t,e,a,i);if(!s)throw new Error("Failed to create asset.");return await new Promise((o,r)=>{const c=new XMLHttpRequest;c.open("PUT",s.assetResponse.uploadUrl,!0),c.setRequestHeader("Content-Type",s.mimeType),c.setRequestHeader("Cache-Control","public,max-age=31536000,immutable"),c.upload.onprogress=l=>{l.lengthComputable&&A(l.loaded*100/l.total)},c.onload=()=>{const l=s.assetResponse.asset;pt.add(s.assetResponse.asset),o(l)},c.onerror=r,c.send(t.blob)}),this.cacheAsset(s.assetResponse.asset),s.assetResponse.asset}async uploadAsset(t,e,A,a){return this.uploadAssetWithProgress(t,e,()=>{},A,a)}async uploadFile(t,e){const A=!(t.type==="image/svg+xml"||t.type==="application/pdf"||t.type==="application/postscript"),a=A?Xt.Image:Xt.Illustration;if(A){const i=await this.loadImageAsFileInfo(t);return await this.uploadAssetWithProgress(i,a,e,!0)}else{const i={name:t.name,blob:new Blob([t],{type:t.type})};return await this.uploadAssetWithProgress(i,a,e,!0)}}async removeBackgroundFromAsset(t){const e=t.key;if(this.bgrmProcessCache.has(e))return this.bgrmProcessCache.get(e);if(Z.has(e)){const i=this.getLocalOrFromServer(Z.get(e));return this.bgrmProcessCache.set(e,i),i}const a=(async()=>{var s,o;const i=await P.getShadowGraphqlClient().mutate({mutation:Ei,fetchPolicy:"no-cache",errorPolicy:"all",variables:{key:e}});if(this.bgrmProcessCache.delete(e),!((o=(s=i.data)==null?void 0:s.assetRemoveBackground)!=null&&o.key))throw new Error("Failed to remove background from image");return pt.add(i.data.assetRemoveBackground),Z.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,a),a}removePersistedAsset(t){pt.remove(t),Z.delete(t),Z.deleteForBgRemovedKey(t)}getPersistedAssets(){return pt.list()}registerPersistedAssetListener(t){pt.addCallback(t)}unRegisterPersistedAssetListener(t){pt.removeCallback(t)}async dispatchCreateAssetRequest(t,e,A,a){const i=t.blob.type?t.blob.type:this.guessMIME(t.name),s=await fi(t.name,e,i,A,a);if(s)return{assetResponse:s,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 O("Unexpected mimetype: "+e)}}}const Ut="persistentAssets",Fa=class ut{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=Y.getMap(Ut);A&&A.forEach((a,i)=>{e.set(i,a)}),Y.setMap(Ut,e),ut.executeCallbacks()}static remove(t){const e=Y.getMap(Ut);if(!e)return;const A=Array.from(e.entries()).find(a=>a[0]===t);A&&(e.delete(A[0]),Y.setMap(Ut,e),ut.executeCallbacks())}static list(){const t=Y.getMap(Ut);return t?Array.from(t.entries()).map(e=>({assetKey:e[0],src:e[1]})):[]}static addCallback(t){ut.callbacks.push(t)}static removeCallback(t){ut.callbacks=ut.callbacks.filter(e=>e!==t)}static executeCallbacks(){ut.callbacks.forEach(t=>t())}};Fa.callbacks=[];let pt=Fa;const XA="bgrmPersistentAssets";class Z{static has(t){return Z.getMap().has(t)}static get(t){return Z.getMap().get(t)}static keys(){return Z.getMap().keys()}static values(){return Z.getMap().values()}static add(t,e){const A=Z.getMap();A.set(t,e),Z.setMap(A)}static delete(t){const e=Z.getMap();e.delete(t),Z.setMap(e)}static deleteForBgRemovedKey(t){const e=Z.getMap(),A=Array.from(e.keys()).find(a=>e.get(a)===t);A&&(e.delete(A),Z.setMap(e))}static getMap(){return Y.getMap(XA)||new Map}static setMap(t){Y.setMap(XA,t)}}const T=new Qi;class pi{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 Nt=new pi,ya=D.gql`
105
+ `,eA=async n=>(await P.getShadowGraphqlClient().query({query:Ci,errorPolicy:"all",variables:{keys:n}})).data.assets,mi=async n=>(await P.getShadowGraphqlClient().query({query:wi,errorPolicy:"all",variables:{ids:n}})).data.materials,fi=async(n,t,e,A,a)=>{var s;return(s=(await P.getShadowGraphqlClient().mutate({mutation:ui,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:n,type:t,mimeType:e,anonymous:A,temporary:a}})).data)==null?void 0:s.assetCreate};class Qi{constructor(){this.cache=new Map,this.bgrmProcessCache=new Map,this.materialCache=new Map,this.loadImageAsFileInfo=async t=>{const e=await t.arrayBuffer(),A=await se(e),a=(i,s)=>{const o=atob(i.split(",")[1]),r=[];for(let c=0;c<o.length;c++)r.push(o.charCodeAt(c));return new Blob([new Uint8Array(r)],{type:s})};return{name:t.name.substring(t.name.lastIndexOf("/")+1),blob:a(A.dataUrl,t.type)}}}async getLocalOrFromServer(t){if(this.cache.has(t)){const a=this.cache.get(t);if(!a)throw new O("Failed to get asset from cache!");return a}const A=(async()=>(await eA([t]))[0])();return this.cache.set(t,A),A}async getFromServer(t){const A=(async()=>(await eA([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==null?void 0:e.split("?")[0]}cacheAsset(t){if(!t.key)throw new O("Asset has no key!");this.cache.has(t.key)||this.cache.set(t.key,Promise.resolve(t))}cacheMaterial(t){if(!t.id)throw new O("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 mi([t]))[0])();return this.materialCache.set(t,A),A}async uploadAssetWithProgress(t,e,A,a,i){const s=await this.dispatchCreateAssetRequest(t,e,a,i);if(!s)throw new Error("Failed to create asset.");return await new Promise((o,r)=>{const c=new XMLHttpRequest;c.open("PUT",s.assetResponse.uploadUrl,!0),c.setRequestHeader("Content-Type",s.mimeType),c.setRequestHeader("Cache-Control","public,max-age=31536000,immutable"),c.upload.onprogress=l=>{l.lengthComputable&&A(l.loaded*100/l.total)},c.onload=()=>{const l=s.assetResponse.asset;pt.add(s.assetResponse.asset),o(l)},c.onerror=r,c.send(t.blob)}),this.cacheAsset(s.assetResponse.asset),s.assetResponse.asset}async uploadAsset(t,e,A,a){return this.uploadAssetWithProgress(t,e,()=>{},A,a)}async uploadFile(t,e){const A=!(t.type==="image/svg+xml"||t.type==="application/pdf"||t.type==="application/postscript"),a=A?Xt.Image:Xt.Illustration;if(A){const i=await this.loadImageAsFileInfo(t);return await this.uploadAssetWithProgress(i,a,e,!0)}else{const i={name:t.name,blob:new Blob([t],{type:t.type})};return await this.uploadAssetWithProgress(i,a,e,!0)}}async removeBackgroundFromAsset(t){const e=t.key;if(this.bgrmProcessCache.has(e))return this.bgrmProcessCache.get(e);if(Z.has(e)){const i=this.getLocalOrFromServer(Z.get(e));return this.bgrmProcessCache.set(e,i),i}const a=(async()=>{var s,o;const i=await P.getShadowGraphqlClient().mutate({mutation:Ei,fetchPolicy:"no-cache",errorPolicy:"all",variables:{key:e}});if(this.bgrmProcessCache.delete(e),!((o=(s=i.data)==null?void 0:s.assetRemoveBackground)!=null&&o.key))throw new Error("Failed to remove background from image");return pt.add(i.data.assetRemoveBackground),Z.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,a),a}removePersistedAsset(t){pt.remove(t),Z.delete(t),Z.deleteForBgRemovedKey(t)}getPersistedAssets(){return pt.list()}registerPersistedAssetListener(t){pt.addCallback(t)}unRegisterPersistedAssetListener(t){pt.removeCallback(t)}async dispatchCreateAssetRequest(t,e,A,a){const i=t.blob.type?t.blob.type:this.guessMIME(t.name),s=await fi(t.name,e,i,A,a);if(s)return{assetResponse:s,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 O("Unexpected mimetype: "+e)}}}const Ut="persistentAssets",Fa=class ut{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=Y.getMap(Ut);A&&A.forEach((a,i)=>{e.set(i,a)}),Y.setMap(Ut,e),ut.executeCallbacks()}static remove(t){const e=Y.getMap(Ut);if(!e)return;const A=Array.from(e.entries()).find(a=>a[0]===t);A&&(e.delete(A[0]),Y.setMap(Ut,e),ut.executeCallbacks())}static list(){const t=Y.getMap(Ut);return t?Array.from(t.entries()).map(e=>({assetKey:e[0],src:e[1]})):[]}static addCallback(t){ut.callbacks.push(t)}static removeCallback(t){ut.callbacks=ut.callbacks.filter(e=>e!==t)}static executeCallbacks(){ut.callbacks.forEach(t=>t())}};Fa.callbacks=[];let pt=Fa;const XA="bgrmPersistentAssets";class Z{static has(t){return Z.getMap().has(t)}static get(t){return Z.getMap().get(t)}static keys(){return Z.getMap().keys()}static values(){return Z.getMap().values()}static add(t,e){const A=Z.getMap();A.set(t,e),Z.setMap(A)}static delete(t){const e=Z.getMap();e.delete(t),Z.setMap(e)}static deleteForBgRemovedKey(t){const e=Z.getMap(),A=Array.from(e.keys()).find(a=>e.get(a)===t);A&&(e.delete(A),Z.setMap(e))}static getMap(){return Y.getMap(XA)||new Map}static setMap(t){Y.setMap(XA,t)}}const T=new Qi;class pi{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 Nt=new pi,ya=D.gql`
106
106
  fragment OptionFields on Option {
107
107
  id
108
108
  name
@@ -148,7 +148,7 @@
148
148
  ...OptionFields
149
149
  }
150
150
  }
151
- `,Di=async n=>{const t=await P.getShadowGraphqlClient().query({query:Ii,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:n}});return t.data.options.forEach(e=>{var A,a;(A=e.defaultVariant)!=null&&A.asset&&T.cacheAsset(e.defaultVariant.asset),e.colorProfile&&T.cacheAsset(e.colorProfile),(a=e.variants)==null||a.forEach(i=>{i.asset&&T.cacheAsset(i.asset),i.thumbnail&&T.cacheAsset(i.thumbnail),i.material&&T.cacheMaterial(i.material)})}),t.data.options},Fi=async(n,t)=>(await t).find(A=>A.id===n),yi=async n=>{const t=n.map(s=>Nt.get({id:s})),e=n.filter((s,o)=>t[o]===void 0);if(e.length===0)return Promise.all(t);const A=Di(e),a=e.map(s=>Nt.set({id:s},Fi(s,A))),i=t.filter(s=>s!==void 0);return await Promise.all(i.concat(a))};class Mi{constructor(){this.getSelectedVariant=(t,e)=>{var A;if(!(!t||e.length===0))return(A=t.variants)==null?void 0:A.find(a=>a.id===e[0])}}async getOption(t){return(async()=>{const a=(await yi([t]))[0];if(a)return a})()}async getAssetTileImageForVariant(t){var a,i;const e=t.thumbnail;if(e){const s=(a=e.versions)==null?void 0:a.find(r=>r.name==="thumbnail"),o=e.fileLink;return(s==null?void 0:s.link)||o}const A=t.asset;if(A){const s=(i=A.versions)==null?void 0:i.find(r=>r.name==="thumbnail"),o=A.fileLink;return(s==null?void 0:s.link)||o}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=>{var a;return A.id===((a=t.defaultVariant)==null?void 0:a.id)})}}}const _=new Mi,Ma=D.gql`
151
+ `,Di=async n=>{const t=await P.getShadowGraphqlClient().query({query:Ii,errorPolicy:"all",variables:{ids:n}});return t.data.options.forEach(e=>{var A,a;(A=e.defaultVariant)!=null&&A.asset&&T.cacheAsset(e.defaultVariant.asset),e.colorProfile&&T.cacheAsset(e.colorProfile),(a=e.variants)==null||a.forEach(i=>{i.asset&&T.cacheAsset(i.asset),i.thumbnail&&T.cacheAsset(i.thumbnail),i.material&&T.cacheMaterial(i.material)})}),t.data.options},Fi=async(n,t)=>(await t).find(A=>A.id===n),yi=async n=>{const t=n.map(s=>Nt.get({id:s})),e=n.filter((s,o)=>t[o]===void 0);if(e.length===0)return Promise.all(t);const A=Di(e),a=e.map(s=>Nt.set({id:s},Fi(s,A))),i=t.filter(s=>s!==void 0);return await Promise.all(i.concat(a))};class Mi{constructor(){this.getSelectedVariant=(t,e)=>{var A;if(!(!t||e.length===0))return(A=t.variants)==null?void 0:A.find(a=>a.id===e[0])}}async getOption(t){return(async()=>{const a=(await yi([t]))[0];if(a)return a})()}async getAssetTileImageForVariant(t){var a,i;const e=t.thumbnail;if(e){const s=(a=e.versions)==null?void 0:a.find(r=>r.name==="thumbnail"),o=e.fileLink;return(s==null?void 0:s.link)||o}const A=t.asset;if(A){const s=(i=A.versions)==null?void 0:i.find(r=>r.name==="thumbnail"),o=A.fileLink;return(s==null?void 0:s.link)||o}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=>{var a;return A.id===((a=t.defaultVariant)==null?void 0:a.id)})}}}const _=new Mi,Ma=D.gql`
152
152
  fragment ActiveIntegrationFields on Integration {
153
153
  id
154
154
  logo
@@ -2702,7 +2702,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
2702
2702
  }
2703
2703
  }
2704
2704
  }
2705
- `;class Ar{constructor(t,e,A,a,i){this.bundleId=t,this.bundleOwnerId=e,this.configuration=A,this.bundleOptions=i,this.initPromise=this.getOrCreateGlobalPropertyState().then(s=>{this.globalPropertyState=s}),this.onGlobalPropertyStateChange=a}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=xt(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find(A=>A.name===t);if(e)return e.value}getAspectStorage(t){var e;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(e=this.globalPropertyState.aspects.find(A=>A.name===t))==null?void 0:e.storage}async setAspect(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 a=this.configuration.aspects.find(o=>o.name===t);if(!a)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=xt(this.globalPropertyState),s=this.globalPropertyState.aspects.find(o=>o.name===t);s?(s.value=e,s.type=a.type,A!==void 0&&(s.storage=A!==null?A:void 0)):this.globalPropertyState.aspects.push({name:t,value:e,type:a.type,storage:A!==null?A:void 0}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async setAspectStorage(t,e){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 A=this.configuration.aspects.find(s=>s.name===t);if(!A)throw new Error(`Failed to find configuration aspect with name: ${t}`);const a=xt(this.globalPropertyState),i=this.globalPropertyState.aspects.find(s=>s.name===t);i?(i.storage=e!==null?e:void 0,i.type=A.type):this.globalPropertyState.aspects.push({name:t,value:"",type:A.type,storage:e!==null?e:void 0}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(a,this.globalPropertyState)}async updateGlobalPropertyState(){var e,A;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await P.getShadowGraphqlClient().mutate({mutation:tr,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(a=>{let i=a.type&&a.storage?{}:void 0;if(i)switch(a.type){case st.FileUpload:{i.fileUpload=a.storage;break}case st.Option:{i.option=a.storage;break}case st.ColorOption:{i=a.storage;break}}return{name:a.name,value:a.value,type:a.type,storage:i}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((A=t.data)!=null&&A.globalPropertyStateUpdate)this.globalPropertyState=t.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async getOrCreateGlobalPropertyState(){var A,a,i;const t=await P.getShadowGraphqlClient().query({query:er,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(A=this.bundleOptions)==null?void 0:A.additionalHeaders}}});if(t.data.globalPropertyState&&t.data.globalPropertyState.id)return t.data.globalPropertyState;const e=await P.getShadowGraphqlClient().mutate({mutation:_o,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(a=this.bundleOptions)==null?void 0:a.additionalHeaders}}});if((i=e.data)!=null&&i.globalPropertyStateCreate&&e.data.globalPropertyStateCreate.id)return e.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class ar{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){var s;if(!this.state||!((s=t==null?void 0:t.getWorkflowManager())!=null&&s.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 a=this.flipTransform(A,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=a.position,i.rotation=a.rotation,i.scale=a.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,A){const a=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(s=>s.transactionId===a);i?(i.transforms||(i.transforms={}),i.transforms[e]=A):this.state.transactions.push({transactionId:a,activeTransform:e,transforms:{[e]:A}})}activateWorkflowExperienceTransform(t,e){var r,c;if(!((r=t==null?void 0:t.getWorkflowManager())!=null&&r.getModelContainer())||!this.state)return;const A=t.getWorkflowManager().getTransaction().id,a=this.state.transactions.find(l=>l.transactionId===A),i=(c=a==null?void 0:a.transforms)==null?void 0:c[e];if(!i)return;const s=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),o=t.getWorkflowManager().getModelContainer();o.position=s.position,o.rotation=s.rotation,o.scale=s.scale,a.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 JSON.stringify(this.state)}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}}}class Yn{constructor(t){this.fullFetched=!1,this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getDescription(){return this.collection.description||""}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.map(t=>new Qe(t))}async fetchProducts(t){if(this.fullFetched)return this.collection.productCollectionProducts.map(A=>new Qe(A));const e=await P.getShadowGraphqlClient().query({query:bo,variables:{id:this.getId(),productIds:t},errorPolicy:"all",fetchPolicy:"no-cache"});return t||(this.fullFetched=!0),this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.map(A=>new Qe(A))}getTransformCollection(){if(this.collection.transformCollection)return new Pn(this.collection.transformCollection)}getResource(){return this.collection}}class Qe{constructor(t){this.product=t.product,this.productResource=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t,e){const a=(this.product.integrationProducts||[]).find(i=>{var c,l,g;const s=(c=i.integration)==null?void 0:c.type,o=((l=i.integration)==null?void 0:l.type)===t,r=e?((g=i.integration)==null?void 0:g.externalIntegrationId)===e:!0;return s&&o&&r});if(!a)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return a}getCurrentIntegration(){const e=(this.product.integrationProducts||[]).find(A=>{var a;return(a=A.integration)==null?void 0:a.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 U("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(t.length===0)throw new U("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(a=>a.workflowName===e);if(A)return new Yt(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 Yt(t[0]);throw new U("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 U("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 Yt(e))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(t){var a,i,s,o;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=(a=this.product.integrationProducts)==null?void 0:a.find(r=>{var c;return((c=r.integration)==null?void 0:c.id)===t.integrationId}):t.externalId?A=(i=this.product.integrationProducts)==null?void 0:i.find(r=>{var c;return((c=r.integration)==null?void 0:c.externalIntegrationId)===t.externalId}):A=(s=this.product.integrationProducts)==null?void 0:s.find(r=>{var c;return((c=r.integration)==null?void 0:c.type)===t.integrationType}),(o=A==null?void 0:A.additionalIntegrationProduct)!=null&&o.product?e+(A.additionalIntegrationProduct.product.basePrice||0):e}}class Yt{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class Pn{constructor(t){this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(t=>new vn(t))}}class vn{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}}}class Ve{constructor(t,e,A,a,i,s){var o,r,c;this.eventListeners=new Map,this.workflowExperiences=[],this.client=t,this.id=e.id,this.name=e.name||"",this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(((o=e.metadata)==null?void 0:o.map(l=>[l.key,l.value]))||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new ar(e.bundleStateData),this.globalPropertyStateManager=new Ar(this.id,this.ownerId,(r=this.productCollection)==null?void 0:r.globalPropertyConfiguration,this.checkConditionalHandlesChanged.bind(this),s),this.globalPropertyHandleService=new $o(this),this.setPreviewService(A),this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(((c=e.transactions)==null?void 0:c.map(l=>l.id))||[],a),this.globalPropertyStateManager.getInitializationPromise()]),this.initializationPromise.catch(l=>{console.error(`Bundle initialization failed: ${l}`)})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const A=this.eventListeners.get(t)||[],a=A.indexOf(e);a>-1&&A.splice(a,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=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(){var t;return!!((t=this.productCollection)!=null&&t.globalPropertyConfiguration)}getGlobalPropertyConfiguration(){var t;return(t=this.productCollection)==null?void 0:t.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(A=>A.getType()===st.Option).map(A=>{var a;return((a=A.getCurrentVariant())==null?void 0:a.getPrice())||0}).reduce((A,a)=>A+a,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new Yn(this.productCollection):void 0}async addWorkflowExperience(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])}async addWorkflowExperiences(t){const e=t.map(o=>o.getWorkflowManager().getTransaction().id),A=e.map(o=>this.workflowExperiences.find(r=>r.getWorkflowManager().getTransaction().id===o));if(A.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+A.filter(o=>!!o).map(o=>o==null?void 0:o.getWorkflowManager().getTransaction().id).join(", "));const a=Y.getMap("transactionOwnerIds")||new Map,i=e.map(o=>a.get(o));await P.getShadowGraphqlClient().mutate({mutation:Oo,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...t);const s=async()=>{for(const r of t)r.setBundle(this),await this.injectExperienceIntoPreviewService(r);await Promise.all(t.map(r=>r.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const r of o)await r.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),s()]),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges())}async appendWorkflowExperience(t,e=!0){const A=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===A))throw new Error("Unable to add transaction to bundle - Already Exists!");const s=(Y.getMap("transactionOwnerIds")||new Map).get(A);await P.getShadowGraphqlClient().mutate({mutation:Jo,variables:{id:this.id,transactionId:A},context:{bundleOwnerId:this.ownerId,transactionOwnerId:s}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}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 a=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);a.setBundle(void 0),this.previewService&&a.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await P.getShadowGraphqlClient().mutate({mutation:Lo,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,s])=>({key:i,value:s})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),A&&(this.workflowExperiences.splice(t,1),this.workflowExperiences.forEach(i=>i.checkForPriceBreakChanges()),a.checkForPriceBreakChanges(),await this.updateTransactionOrder())}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(a=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===a.id));if(e.some(a=>a===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((a,i)=>e[i]===-1).map(a=>a.id).join(", "));const A=t.map(a=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===a.id),1)[0]);A.forEach(a=>a.setBundle(void 0)),[...this.workflowExperiences,...A].forEach(a=>a.checkForPriceBreakChanges()),this.previewService&&A.forEach(a=>a.getWorkflowManager().ejectFromPreviewService()),t.forEach(a=>this.bundleStateManager.removeStateForTransaction(a.id)),await P.getShadowGraphqlClient().mutate({mutation:zo,variables:{id:this.id,transactionIds:t.map(a=>a.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,i])=>({key:a,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),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(a=>a.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 a=await this.getGlobalProperties();await Promise.all(a.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){var i;const A=await P.getShadowGraphqlClient().mutate({mutation:jo,variables:{id:this.id,details:t,type:e||qt.Owner},context:{bundleOwnerId:this.ownerId}});if(!((i=A.data)!=null&&i.bundleAddStakeholder))throw new Error("Bundle not found!");const a=A.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async removeStakeholder(t){var A;if(!((A=(await P.getShadowGraphqlClient().mutate({mutation:Ko,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data)!=null&&A.bundleRemoveStakeholder))throw new Error("Bundle not found!")}async updateStakeholders(t){var a;const e=await P.getShadowGraphqlClient().mutate({mutation:Vo,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!((a=e.data)!=null&&a.bundleUpdateStakeholders))throw new Error("Bundle not found!");const A=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(A)}async getAllStakeholders(){const t=await P.getShadowGraphqlClient().query({query:ia,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 P.getShadowGraphqlClient().query({query:ia,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){if(this.completed)return await P.getShadowGraphqlClient().mutate({mutation:Zo,variables:{bundleId:this.id}}),{bundleId:this.id,items:[],bundleOwnerId:this.ownerId};const A=await Co(this.workflowExperiences.map(a=>({workflowManager:a.getWorkflowManager(),workflow:a.getWorkflowManager().getWorkflow(),layouts:a.getWorkflowManager().getLayouts(),getReducerState:()=>a.getCommandContext().getState(),product:a.getWorkflowManager().getProduct(),transaction:a.getWorkflowManager().getTransaction(),workflowSelections:a.getWorkflowManager().getWorkflowSelections(),designName:a.getWorkflowManager().getWorkflow().name,workflowMetadata:a.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(a,i)=>{const s=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===i);return s?e(s):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,items:A,bundleOwnerId:this.ownerId}}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 assignProductCollection(t){var A,a;const e=await P.getShadowGraphqlClient().mutate({mutation:Xo(((A=this.globalPropertyStateManager.getBundleOptions())==null?void 0:A.eagerFetchProducts)??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});(a=e.data)!=null&&a.bundleAssignProductCollection.productCollection&&(this.productCollection=e.data.bundleAssignProductCollection.productCollection,this.globalPropertyStateManager.setConfiguration(e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration))}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 a=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===a.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(a=>({type:"transaction",transactionId:a})),e);if(A.forEach(a=>a.setBundle(this)),A.forEach(a=>a.checkForPriceBreakChanges()),this.workflowExperiences=A,this.previewService)for(const a of A)await this.injectExperienceIntoPreviewService(a)}async updateBundle(){var e;if(!((e=(await P.getShadowGraphqlClient().mutate({mutation:To,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([A,a])=>({key:A,value:a})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}})).data)!=null&&e.bundleUpdate))throw new Error("Bundle not found!")}async updateTransactionOrder(){await P.getShadowGraphqlClient().mutate({mutation:Wo,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async checkConditionalHandlesChanged(t,e){const A=await this.globalPropertyHandleService.getHandles(),a=this.globalPropertyHandleService.applyConditionsFromState(A,t),i=this.globalPropertyHandleService.applyConditionsFromState(A,e);if((()=>{if(a.length!==i.length)return!0;for(let o=0;o<a.length;o++)if(a[o].getName()!==i[o].getName())return!0;return!1})()){this.fireEvent("conditional-global-properties-changed",{globalProperties:i});const o=i.filter(r=>!a.includes(r));await Promise.all(o.map(r=>r.applyGlobalState()))}}fireEvent(t,e){(this.eventListeners.get(t)||[]).forEach(a=>a({bundle:this,event:t,data:e}))}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}}const nr=D.gql`
2705
+ `;class Ar{constructor(t,e,A,a,i){this.bundleId=t,this.bundleOwnerId=e,this.configuration=A,this.bundleOptions=i,this.initPromise=this.getOrCreateGlobalPropertyState().then(s=>{this.globalPropertyState=s}),this.onGlobalPropertyStateChange=a}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=xt(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find(A=>A.name===t);if(e)return e.value}getAspectStorage(t){var e;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(e=this.globalPropertyState.aspects.find(A=>A.name===t))==null?void 0:e.storage}async setAspect(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 a=this.configuration.aspects.find(o=>o.name===t);if(!a)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=xt(this.globalPropertyState),s=this.globalPropertyState.aspects.find(o=>o.name===t);s?(s.value=e,s.type=a.type,A!==void 0&&(s.storage=A!==null?A:void 0)):this.globalPropertyState.aspects.push({name:t,value:e,type:a.type,storage:A!==null?A:void 0}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async setAspectStorage(t,e){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 A=this.configuration.aspects.find(s=>s.name===t);if(!A)throw new Error(`Failed to find configuration aspect with name: ${t}`);const a=xt(this.globalPropertyState),i=this.globalPropertyState.aspects.find(s=>s.name===t);i?(i.storage=e!==null?e:void 0,i.type=A.type):this.globalPropertyState.aspects.push({name:t,value:"",type:A.type,storage:e!==null?e:void 0}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(a,this.globalPropertyState)}async updateGlobalPropertyState(){var e,A;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await P.getShadowGraphqlClient().mutate({mutation:tr,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(a=>{let i=a.type&&a.storage?{}:void 0;if(i)switch(a.type){case st.FileUpload:{i.fileUpload=a.storage;break}case st.Option:{i.option=a.storage;break}case st.ColorOption:{i=a.storage;break}}return{name:a.name,value:a.value,type:a.type,storage:i}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((A=t.data)!=null&&A.globalPropertyStateUpdate)this.globalPropertyState=t.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async getOrCreateGlobalPropertyState(){var e,A,a;if(!((e=this.bundleOptions)!=null&&e.createNewGlobalState)){const i=await this._getGlobalPropertyState();if(i.data.globalPropertyState&&i.data.globalPropertyState.id)return i.data.globalPropertyState}const t=await P.getShadowGraphqlClient().mutate({mutation:_o,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(A=this.bundleOptions)==null?void 0:A.additionalHeaders}}});if((a=t.data)!=null&&a.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}async _getGlobalPropertyState(){var e;return await P.getShadowGraphqlClient().query({query:er,errorPolicy:"all",fetchPolicy:"no-cache",variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}})}}class ar{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){var s;if(!this.state||!((s=t==null?void 0:t.getWorkflowManager())!=null&&s.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 a=this.flipTransform(A,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=a.position,i.rotation=a.rotation,i.scale=a.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,A){const a=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(s=>s.transactionId===a);i?(i.transforms||(i.transforms={}),i.transforms[e]=A):this.state.transactions.push({transactionId:a,activeTransform:e,transforms:{[e]:A}})}activateWorkflowExperienceTransform(t,e){var r,c;if(!((r=t==null?void 0:t.getWorkflowManager())!=null&&r.getModelContainer())||!this.state)return;const A=t.getWorkflowManager().getTransaction().id,a=this.state.transactions.find(l=>l.transactionId===A),i=(c=a==null?void 0:a.transforms)==null?void 0:c[e];if(!i)return;const s=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),o=t.getWorkflowManager().getModelContainer();o.position=s.position,o.rotation=s.rotation,o.scale=s.scale,a.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 JSON.stringify(this.state)}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}}}class Yn{constructor(t){this.fullFetched=!1,this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getDescription(){return this.collection.description||""}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.map(t=>new Qe(t))}async fetchProducts(t){if(this.fullFetched)return this.collection.productCollectionProducts.map(A=>new Qe(A));const e=await P.getShadowGraphqlClient().query({query:bo,variables:{id:this.getId(),productIds:t},errorPolicy:"all"});return t||(this.fullFetched=!0),this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.map(A=>new Qe(A))}getTransformCollection(){if(this.collection.transformCollection)return new Pn(this.collection.transformCollection)}getResource(){return this.collection}}class Qe{constructor(t){this.product=t.product,this.productResource=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t,e){const a=(this.product.integrationProducts||[]).find(i=>{var c,l,g;const s=(c=i.integration)==null?void 0:c.type,o=((l=i.integration)==null?void 0:l.type)===t,r=e?((g=i.integration)==null?void 0:g.externalIntegrationId)===e:!0;return s&&o&&r});if(!a)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return a}getCurrentIntegration(){const e=(this.product.integrationProducts||[]).find(A=>{var a;return(a=A.integration)==null?void 0:a.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 U("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(t.length===0)throw new U("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(a=>a.workflowName===e);if(A)return new Yt(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 Yt(t[0]);throw new U("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 U("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 Yt(e))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(t){var a,i,s,o;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=(a=this.product.integrationProducts)==null?void 0:a.find(r=>{var c;return((c=r.integration)==null?void 0:c.id)===t.integrationId}):t.externalId?A=(i=this.product.integrationProducts)==null?void 0:i.find(r=>{var c;return((c=r.integration)==null?void 0:c.externalIntegrationId)===t.externalId}):A=(s=this.product.integrationProducts)==null?void 0:s.find(r=>{var c;return((c=r.integration)==null?void 0:c.type)===t.integrationType}),(o=A==null?void 0:A.additionalIntegrationProduct)!=null&&o.product?e+(A.additionalIntegrationProduct.product.basePrice||0):e}}class Yt{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class Pn{constructor(t){this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(t=>new vn(t))}}class vn{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}}}class Ve{constructor(t,e,A,a,i,s){var o,r,c;this.eventListeners=new Map,this.workflowExperiences=[],this.client=t,this.id=e.id,this.name=e.name||"",this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(((o=e.metadata)==null?void 0:o.map(l=>[l.key,l.value]))||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new ar(e.bundleStateData),this.globalPropertyStateManager=new Ar(this.id,this.ownerId,(r=this.productCollection)==null?void 0:r.globalPropertyConfiguration,this.checkConditionalHandlesChanged.bind(this),s),this.globalPropertyHandleService=new $o(this),this.setPreviewService(A),this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(((c=e.transactions)==null?void 0:c.map(l=>l.id))||[],a),this.globalPropertyStateManager.getInitializationPromise()]),this.initializationPromise.catch(l=>{console.error(`Bundle initialization failed: ${l}`)})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const A=this.eventListeners.get(t)||[],a=A.indexOf(e);a>-1&&A.splice(a,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=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(){var t;return!!((t=this.productCollection)!=null&&t.globalPropertyConfiguration)}getGlobalPropertyConfiguration(){var t;return(t=this.productCollection)==null?void 0:t.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(A=>A.getType()===st.Option).map(A=>{var a;return((a=A.getCurrentVariant())==null?void 0:a.getPrice())||0}).reduce((A,a)=>A+a,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new Yn(this.productCollection):void 0}async addWorkflowExperience(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])}async addWorkflowExperiences(t){const e=t.map(o=>o.getWorkflowManager().getTransaction().id),A=e.map(o=>this.workflowExperiences.find(r=>r.getWorkflowManager().getTransaction().id===o));if(A.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+A.filter(o=>!!o).map(o=>o==null?void 0:o.getWorkflowManager().getTransaction().id).join(", "));const a=Y.getMap("transactionOwnerIds")||new Map,i=e.map(o=>a.get(o));await P.getShadowGraphqlClient().mutate({mutation:Oo,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...t);const s=async()=>{for(const r of t)r.setBundle(this),await this.injectExperienceIntoPreviewService(r);await Promise.all(t.map(r=>r.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const r of o)await r.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),s()]),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges())}async appendWorkflowExperience(t,e=!0){const A=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===A))throw new Error("Unable to add transaction to bundle - Already Exists!");const s=(Y.getMap("transactionOwnerIds")||new Map).get(A);await P.getShadowGraphqlClient().mutate({mutation:Jo,variables:{id:this.id,transactionId:A},context:{bundleOwnerId:this.ownerId,transactionOwnerId:s}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}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 a=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);a.setBundle(void 0),this.previewService&&a.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await P.getShadowGraphqlClient().mutate({mutation:Lo,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,s])=>({key:i,value:s})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),A&&(this.workflowExperiences.splice(t,1),this.workflowExperiences.forEach(i=>i.checkForPriceBreakChanges()),a.checkForPriceBreakChanges(),await this.updateTransactionOrder())}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(a=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===a.id));if(e.some(a=>a===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((a,i)=>e[i]===-1).map(a=>a.id).join(", "));const A=t.map(a=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===a.id),1)[0]);A.forEach(a=>a.setBundle(void 0)),[...this.workflowExperiences,...A].forEach(a=>a.checkForPriceBreakChanges()),this.previewService&&A.forEach(a=>a.getWorkflowManager().ejectFromPreviewService()),t.forEach(a=>this.bundleStateManager.removeStateForTransaction(a.id)),await P.getShadowGraphqlClient().mutate({mutation:zo,variables:{id:this.id,transactionIds:t.map(a=>a.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,i])=>({key:a,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),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(a=>a.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 a=await this.getGlobalProperties();await Promise.all(a.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){var i;const A=await P.getShadowGraphqlClient().mutate({mutation:jo,variables:{id:this.id,details:t,type:e||qt.Owner},context:{bundleOwnerId:this.ownerId}});if(!((i=A.data)!=null&&i.bundleAddStakeholder))throw new Error("Bundle not found!");const a=A.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async removeStakeholder(t){var A;if(!((A=(await P.getShadowGraphqlClient().mutate({mutation:Ko,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data)!=null&&A.bundleRemoveStakeholder))throw new Error("Bundle not found!")}async updateStakeholders(t){var a;const e=await P.getShadowGraphqlClient().mutate({mutation:Vo,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!((a=e.data)!=null&&a.bundleUpdateStakeholders))throw new Error("Bundle not found!");const A=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(A)}async getAllStakeholders(){const t=await P.getShadowGraphqlClient().query({query:ia,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 P.getShadowGraphqlClient().query({query:ia,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){if(this.completed)return await P.getShadowGraphqlClient().mutate({mutation:Zo,variables:{bundleId:this.id}}),{bundleId:this.id,items:[],bundleOwnerId:this.ownerId};const A=await Co(this.workflowExperiences.map(a=>({workflowManager:a.getWorkflowManager(),workflow:a.getWorkflowManager().getWorkflow(),layouts:a.getWorkflowManager().getLayouts(),getReducerState:()=>a.getCommandContext().getState(),product:a.getWorkflowManager().getProduct(),transaction:a.getWorkflowManager().getTransaction(),workflowSelections:a.getWorkflowManager().getWorkflowSelections(),designName:a.getWorkflowManager().getWorkflow().name,workflowMetadata:a.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(a,i)=>{const s=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===i);return s?e(s):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,items:A,bundleOwnerId:this.ownerId}}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 assignProductCollection(t){var A,a;const e=await P.getShadowGraphqlClient().mutate({mutation:Xo(((A=this.globalPropertyStateManager.getBundleOptions())==null?void 0:A.eagerFetchProducts)??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});(a=e.data)!=null&&a.bundleAssignProductCollection.productCollection&&(this.productCollection=e.data.bundleAssignProductCollection.productCollection,this.globalPropertyStateManager.setConfiguration(e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration))}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 a=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===a.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(a=>({type:"transaction",transactionId:a})),e);if(A.forEach(a=>a.setBundle(this)),A.forEach(a=>a.checkForPriceBreakChanges()),this.workflowExperiences=A,this.previewService)for(const a of A)await this.injectExperienceIntoPreviewService(a)}async updateBundle(){var e;if(!((e=(await P.getShadowGraphqlClient().mutate({mutation:To,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([A,a])=>({key:A,value:a})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}})).data)!=null&&e.bundleUpdate))throw new Error("Bundle not found!")}async updateTransactionOrder(){await P.getShadowGraphqlClient().mutate({mutation:Wo,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async checkConditionalHandlesChanged(t,e){const A=await this.globalPropertyHandleService.getHandles(),a=this.globalPropertyHandleService.applyConditionsFromState(A,t),i=this.globalPropertyHandleService.applyConditionsFromState(A,e);if((()=>{if(a.length!==i.length)return!0;for(let o=0;o<a.length;o++)if(a[o].getName()!==i[o].getName())return!0;return!1})()){this.fireEvent("conditional-global-properties-changed",{globalProperties:i});const o=i.filter(r=>!a.includes(r));await Promise.all(o.map(r=>r.applyGlobalState()))}}fireEvent(t,e){(this.eventListeners.get(t)||[]).forEach(a=>a({bundle:this,event:t,data:e}))}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}}const nr=D.gql`
2706
2706
  mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
2707
2707
  processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
2708
2708
  id
@@ -3377,4 +3377,4 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
3377
3377
  }
3378
3378
  }
3379
3379
  }
3380
- `,Dt=async n=>{var t;for(const e in n.layouts){const A=n.layouts[e].elements.filter(i=>i.type===k.Illustration);for(let i=0;i<A.length;++i){const s=A[i];s.src&&s.svg&&(s.cachedObjectURL=await te(s.svg))}const a=n.layouts[e].elements.filter(i=>i.type===k.Textbox);for(let i=0;i<a.length;++i){const s=a[i];(t=s.fontData)!=null&&t.assetUrl&&await bt(s.fontData.assetUrl)}}},fr=async(n,t)=>{var a;const e=await P.getShadowGraphqlClient().query({query:ur(((a=t==null?void 0:t.assets)==null?void 0:a.metadata)||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),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(i=>{i.steps.forEach(s=>{var o,r,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((r=s.option.defaultVariant)!=null&&r.asset&&T.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&T.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(l=>{l.asset&&T.cacheAsset(l.asset),l.thumbnail&&T.cacheAsset(l.thumbnail),l.material&&T.cacheMaterial(l.material)}),Nt.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.partner.termsMarkdown}),A},Qr=async(n,t)=>{const A=(await t).find(a=>a.id===n);if(!A)throw new Error(`Workflow not found: ${n}`);return A},OA=async(n,t)=>{const e=n.map(o=>Nt.get({id:o,options:t})),A=n.filter((o,r)=>e[r]===void 0);if(A.length===0)return Promise.all(e);const a=fr(A,t),i=A.map(o=>Nt.set({id:o,options:t},Qr(o,a))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},Kt=async(n,t)=>(await OA([n],t))[0],pr=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:R(),panelId:t.name,name:t.name,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})),We=(n,t)=>{const e=n.workflowState,A=e?JSON.parse(e):void 0;return A?Object.values(A.layouts).map(a=>a.layout):pr(t.panels)};class Hn{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return P.getShadowGraphqlClient().mutate({...e,mutation:Pi})}catch(A){throw console.error(A),new U("Critical - Unable to synchronize workflow state with server.")}},this.initialized=!1,this.options=t,this.options.applicationKey&&ii(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 25.0.8"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configureUrls(t,e,A){nt.setHubUrl(t),nt.setServerUrl(e),nt.setServicesApiUrl(A),this.options.applicationKey&&this.getIntegration()}configure(t){nt.setHubUrl(t.hubUrl),nt.setServerUrl(t.serverUrl),nt.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,t.bearerAuthenticationToken&&Ia(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return T}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!si())throw new Error("Application key required to use Flow Service.");return new Nn}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");const t=async()=>(await P.getShadowGraphqlClient().query({query:Si,errorPolicy:"all",fetchPolicy:"no-cache"})).data.currentIntegration;return this.activeIntegration=t(),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(A){return console.error(A),!1}}async authenticateBundleFromLocalStorage(t){var a,i;const e=Y.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:qt.Owner});const A=Y.getMap("bundlePartnerIds")||new Map;if(A.has(t)){const s=A.get(t),r=(Y.getMap("partnerCustomerIds")||new Map).get(s);if(r&&await this.authenticateCustomerId(r)){const l=(i=(a=this.customer)==null?void 0:a.bundleStakeholders)==null?void 0:i.find(g=>{var d;return((d=g.bundle)==null?void 0:d.id)===t});if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var l,g,d,B,h,C;const e=P.getShadowGraphqlClient(),A=await e.query({query:Er,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 a=A.data.transactions[0];if(!((g=(l=a.product)==null?void 0:l.partner)==null?void 0:g.id))throw new Error(`Unable to read transaction: ${t}`);if(a.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=Y.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:qt.Owner});const o=Y.getMap("transactionCustomerIds");if(o!=null&&o.has(t)){const w=o.get(t);if(w&&await this.authenticateCustomerId(w)){const E=((B=(d=this.customer)==null?void 0:d.bundleStakeholders)==null?void 0:B.find(m=>{var f,p;return(p=(f=m.bundle)==null?void 0:f.transactions)==null?void 0:p.some(I=>I.id===t)}))||((C=(h=this.customer)==null?void 0:h.stakeholders)==null?void 0:C.find(m=>{var f;return((f=m.transaction)==null?void 0:f.id)===t}));if(E)return Promise.resolve({success:!0,stakeholderType:E.type})}}const c=(await e.query({query:mr,errorPolicy:"all",variables:{id:a.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${a.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:a.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Y.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),Y.setMap("transactionCustomerIds",e))}getStakeholderTypeForTransaction(t){var A,a;const e=(a=(A=this.customer)==null?void 0:A.stakeholders)==null?void 0:a.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=P.getShadowGraphqlClient(),a=(await e.query({query:or,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!a.id){const r=(s=(await e.mutate({mutation:rr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!r)throw new Error("Unable to create customer.");return this.storeCustomer(r),this.customer=r,{customer:r,isAuthenticated:!1}}this.storeCustomer(a);const i=await this.authenticateCustomerId(a.id);return{customer:this.customer||a,isAuthenticated:i}}getCustomer(){return this.customer}async authenticateCustomerId(t){var o;const e=P.getShadowGraphqlClient(),A=Y.getMap("customerTokens");if(!(A!=null&&A.has(t)))return!1;const a=A.get(t);if(!a)return!1;const s=(o=(await e.mutate({mutation:cr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:a}})).data)==null?void 0:o.customerAuthenticate;return s?(this.storeCustomer(s),WA(a),this.customer=s,!0):!1}async generateVerificationCode(t){await P.getShadowGraphqlClient().mutate({mutation:lr,variables:{emailAddress:t}})}async verifyCode(t,e){var i,s;const a=(i=(await P.getShadowGraphqlClient().mutate({mutation:gr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data)==null?void 0:i.customerVerifyCode;if(a!=null&&a.loginToken){if(!((s=a.partner)!=null&&s.id))throw new Error(`Unable to find customer: ${t}`);const o=Y.getMap("customerTokens")||new Map;return o.set(a.id,a.loginToken),Y.setMap("customerTokens",o),this.storeCustomer(a),WA(a.loginToken),this.customer={...a,loginToken:void 0},!0}return!1}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await P.getShadowGraphqlClient().query({query:dr,fetchPolicy:"no-cache",variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,A){var c,l,g,d,B;const i=(g=(await P.getShadowGraphqlClient().mutate({mutation:Uo(((l=(c=A==null?void 0:A.graphql)==null?void 0:c.productCollection)==null?void 0:l.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((h,C)=>({key:h[0],value:h[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:g.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=Y.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),Y.setMap("bundlePartnerIds",s);const o=Y.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),Y.setMap("bundleOwnerIds",o);const r=new Ve(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(B=(d=A==null?void 0:A.graphql)==null?void 0:d.productCollection)==null?void 0:B.eagerFetchProducts});return await r.getInitializationPromise(),r}async getExistingBundle(t,e,A,a){var w,u,E,m,f,p,I,Q,F,y,x;const i=Y.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),r=((w=Object.entries(localStorage).find(([v,N])=>v.startsWith("CognitoIdentityServiceProvider")&&v.endsWith("idToken")))==null?void 0:w[0])||"",c=localStorage.getItem(r),l={};c&&!ye(c)&&(l.Authorization=`Bearer ${c}`);const g={bundleOwnerId:s,...l,...(u=a==null?void 0:a.graphql)==null?void 0:u.additionalHeaders},d=await P.getShadowGraphqlClient().query({query:Ro(((m=(E=a==null?void 0:a.graphql)==null?void 0:E.productCollection)==null?void 0:m.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:g}});if(!((f=d.data)!=null&&f.bundles)||((p=d.data)==null?void 0:p.bundles.length)===0||!((I=d.data)!=null&&I.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const B=(Q=d.data)==null?void 0:Q.bundles[0],h=Y.getMap("bundlePartnerIds")||new Map;h.set(B.id,B.partner.id),Y.setMap("bundlePartnerIds",h);const C=new Ve(this,B,e,A,s,{additionalHeaders:(F=a==null?void 0:a.graphql)==null?void 0:F.additionalHeaders,eagerFetchProducts:(x=(y=a==null?void 0:a.graphql)==null?void 0:y.productCollection)==null?void 0:x.eagerFetchProducts});return await C.getInitializationPromise(),C}async duplicateBundle(t,e,A,a){var w,u,E,m,f,p,I,Q;const i=(w=Y.getMap("bundleOwnerIds"))==null?void 0:w.get(t),o=((u=Object.entries(localStorage).find(([F,y])=>F.startsWith("CognitoIdentityServiceProvider")&&F.endsWith("idToken")))==null?void 0:u[0])||"",r=localStorage.getItem(o),c={};r&&!ye(r)&&(c.Authorization=`Bearer ${r}`);const l={bundleOwnerId:i,...c,...(E=a==null?void 0:a.graphql)==null?void 0:E.additionalHeaders},d=(p=(await P.getShadowGraphqlClient().mutate({mutation:Go(((f=(m=a==null?void 0:a.graphql)==null?void 0:m.productCollection)==null?void 0:f.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:A},context:{headers:l},fetchPolicy:"no-cache"})).data)==null?void 0:p.bundleDuplicate;if(!(d!=null&&d.id))throw new Error("Unable to duplicate bundle");const B=Y.getMap("bundlePartnerIds")||new Map;B.set(d.id,d.partner.id),Y.setMap("bundlePartnerIds",B);const h=Y.getMap("bundleOwnerIds")||new Map;h.set(d.id,d.bundleOwnerId),Y.setMap("bundleOwnerIds",h);const C=new Ve(this,d,void 0,void 0,d.bundleOwnerId,{eagerFetchProducts:(Q=(I=a==null?void 0:a.graphql)==null?void 0:I.productCollection)==null?void 0:Q.eagerFetchProducts});return await C.getInitializationPromise(),C}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...A}=t;return(await P.getShadowGraphqlClient().query({query:qo(e??!1),variables:{...A,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){var i;if(!this.customer)throw new Error("Customer not authenticated.");const t=await P.getShadowGraphqlClient().query({query:Ho,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const A=t.data.customers[0].bundleStakeholders||[],a=Y.getMap("bundlePartnerIds")||new Map;return A.forEach(s=>{var o,r;(o=s.bundle)!=null&&o.id&&((r=s.bundle.partner)!=null&&r.id)&&a.set(s.bundle.id,s.bundle.partner.id)}),Y.setMap("bundlePartnerIds",a),A}async getWorkflowExperience(t,e,A,a){var g,d,B,h,C;if(!a)return await this.getWorkflowExperienceDeprecated(t,e,A);const i=async()=>{var u,E,m;const w=P.getShadowGraphqlClient();if(a.type==="transaction"){const{transactionId:f,readOnly:p}=a,I=await w.query({query:he,variables:{ids:[f]},errorPolicy:"all",fetchPolicy:"no-cache"});if(!((u=I.data)!=null&&u.transactions)||I.data.transactions.length===0)throw new U("Existing transaction not found.");const Q=(E=I.data)==null?void 0:E.transactions[0];if(!Q.workflowId)throw new U("Existing transaction has no workflow ID.");const F=await Kt(Q.workflowId);if(!Q.product)throw new U("Failed to load transaction, product not available.");return!this.activeIntegration&&((m=Q.integrationProduct)!=null&&m.integration)&&(this.activeIntegration=Promise.resolve(Q.integrationProduct.integration)),{transaction:Q,workflow:F,readOnly:p}}if(a.type==="integration"||a.type==="external"){const f=async()=>{const F=a.type==="integration"?{integrationProductId:a.integrationProductId}:{externalIntegrationId:a.externalIntegrationId,externalProductId:a.externalProductId},y=await w.mutate({mutation:qA,variables:{...F,workflowId:a.workflowId,designName:a.designName,claim:!0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!y.data||!y.data.transactionCreate)throw new U("Failed to create transaction!");const x=y.data.transactionCreate;if(!x.product)throw new U("Failed to create transaction, product not available.");return x},p=Kt(a.workflowId,a==null?void 0:a.graphql),[I,Q]=await Promise.all([f(),p]);return{transaction:I,workflow:Q}}throw new U("No workflow ID provided.")},{transaction:s,workflow:o,readOnly:r}=await i();this.currencyCode=(g=s.product.partner)==null?void 0:g.currencyCode;const c={product:s.product,transaction:s,layouts:[],singleVariantsRenderable:(d=a==null?void 0:a.workflowConfiguration)==null?void 0:d.singleVariantsRenderable,stateMutationFunc:r?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async w=>{const E=(Y.getMap("transactionOwnerIds")||new Map).get(s.id)||void 0;return this.updateTransactionState({...w,context:{transactionOwnerId:E}})},readOnly:r,workflow:o};if(a.type==="transaction"&&s.workflowState){const w=JSON.parse(s.workflowState);c.layouts=Object.values(w.layouts).map(u=>u.layout),await Et(w),await Dt(w),c.reloadedState=w}else if(!r&&a.workflowState){const w=JSON.parse(a.workflowState);c.layouts=Object.values(w.layouts).map(u=>u.layout),await Et(w),await Dt(w),c.reloadedState=w}else c.layouts=We(c.transaction,c.workflow);if(c.renderableContextService=new Ee(c.layouts),a.previewService?(c.previewService=a.previewService,(B=c.product)!=null&&B.modelUrl&&(c.modelContainer=c.previewService.loadModel({model:c.product.modelUrl,contextService:c.renderableContextService}))):(c.previewService=A&&A(o),(h=c.product)!=null&&h.modelUrl&&(c.modelContainer=(C=c.previewService)==null?void 0:C.loadModel({model:c.product.modelUrl,contextService:c.renderableContextService}))),a.type!=="transaction"){const w=Y.getMap("transactionOwnerIds")||new Map;w.set(s.id,s.transactionOwnerId),Y.setMap("transactionOwnerIds",w)}else c.isReloadedTransaction=!0;this.initialized=!0,this.experienceOptions=c;const l=new zt(this,c);return await l.getWorkflowManager().getInitializationPromise(),a.type!=="transaction"&&this.customer&&await l.attachCustomerDetails({email:this.customer.emailAddress}),l}async getWorkflowExperiences(t,e){if(t.length===0)throw new U("No options provided!");const A=P.getShadowGraphqlClient(),a=async p=>{var y,x,v;if(p.length===0)return[];const I=p.map(N=>N.option.transactionId),Q=await A.query({query:he,variables:{ids:I},errorPolicy:"all",fetchPolicy:"no-cache"}),F=Q.data.transactions;if(F.length!==p.length){const N=((x=(y=Q.errors)==null?void 0:y[0])==null?void 0:x.message)||"Unknown error";throw new U(`Not all transactions were found: ${N}`)}return!this.activeIntegration&&((v=F[0].integrationProduct)!=null&&v.integration)&&(this.activeIntegration=Promise.resolve(F[0].integrationProduct.integration)),F.map((N,H)=>{var V;return{transaction:N,workflowId:N.workflowId,readOnly:((V=p.find(z=>z.option.transactionId===N.id))==null?void 0:V.option.readOnly)??!1,index:p[H].index}})},i=async p=>{var F,y,x;if(p.length===0)return[];const I=await A.mutate({mutation:xi,variables:{inputs:p.map(v=>({integrationProductId:v.option.type==="integration"?v.option.integrationProductId:void 0,externalIntegrationId:v.option.type==="external"?v.option.externalIntegrationId:void 0,externalProductId:v.option.type==="external"?v.option.externalProductId:void 0,workflowId:v.option.workflowId,designName:v.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),Q=(F=I.data)==null?void 0:F.transactionCreateMany;if(!Q||Q.length===0){const v=((x=(y=I.errors)==null?void 0:y[0])==null?void 0:x.message)||"Unknown error";throw new U(`Failed to create transactions: ${v}`)}return Q.map((v,N)=>({transaction:v,workflowId:v.workflowId,readOnly:!1,index:p[N].index}))},s=t.map((p,I)=>({option:p,index:I})),o=s.filter(p=>p.option.type==="transaction"),r=s.filter(p=>p.option.type==="integration"||p.option.type==="external"),c=LA(o,10),l=LA(r,10),g=(await Promise.all([...c.map(a),...l.map(i)])).flat(),d=[...new Set(g.map(p=>p.workflowId))],B=await OA(d,e),h=new Map(B.map(p=>[p.id,p])),C=Y.getMap("transactionOwnerIds")||new Map,w=g.map(async p=>{var V;const{transaction:I,workflowId:Q,readOnly:F,index:y}=p,x=h.get(Q),v=t[y];!C.get(I.id)&&I.transactionOwnerId&&C.set(I.id,I.transactionOwnerId);const N=C.get(I.id)||void 0,H={product:I.product,transaction:I,layouts:[],singleVariantsRenderable:(V=v==null?void 0:v.workflowConfiguration)==null?void 0:V.singleVariantsRenderable,stateMutationFunc:F?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async z=>this.updateTransactionState({...z,context:{transactionOwnerId:N}}),readOnly:F,workflow:x,isReloadedTransaction:v.type==="transaction"};if(v.type==="transaction"&&I.workflowState){const z=JSON.parse(I.workflowState);H.layouts=Object.values(z.layouts||{}).map(at=>at.layout),await Et(z),await Dt(z),H.reloadedState=z}else if(!F&&v.workflowState){const z=JSON.parse(v.workflowState);H.layouts=Object.values(z.layouts||{}).map(at=>at.layout),await Et(z),await Dt(z),H.reloadedState=z}else H.layouts=We(H.transaction,H.workflow);return H.renderableContextService=new Ee(H.layouts),H.delayWorkflowStateSync=!0,this.initialized=!0,this.experienceOptions=H,{experienceOptions:H,index:y,options:v}}),u=await Promise.all(w);Y.setMap("transactionOwnerIds",C);const m=u.sort((p,I)=>p.index-I.index).map(async p=>{const{experienceOptions:I,options:Q}=p,F=new zt(this,I);return await F.getWorkflowManager().getInitializationPromise(),Q.type!=="transaction"&&this.customer&&await F.attachCustomerDetails({email:this.customer.emailAddress}),F}),f=await Promise.all(m);return f.forEach(p=>p.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),f}async initFromIntegrationProduct(t){var s;if(t==="")throw new U("No integration product ID provided.");const A=await P.getShadowGraphqlClient().mutate({mutation:qA,variables:{integrationProductId:t,claim:!0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new U("Failed to create transaction!");const a=A.data.transactionCreate;if(!a.product)throw new U("Failed to create transaction, product not available.");this.currencyCode=(s=a.product.partner)==null?void 0:s.currencyCode;const i=Y.getMap("transactionOwnerIds")||new Map;i.set(a.id,a.transactionOwnerId),Y.setMap("transactionOwnerIds",i),this.experienceOptions={product:a.product,transaction:a,layouts:[],stateMutationFunc:async o=>this.updateTransactionState({...o,context:{transactionOwnerId:a.transactionOwnerId}})},this.initialized=!0}async initFromTransaction(t,e=!1){var o,r,c,l;if(t==="")throw new U("No transaction ID provided.");const A=P.getShadowGraphqlClient(),a=async()=>{var B,h;const d=(B=(await A.query({query:he,variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:B.transactions[0];if(!d)throw new U("Failed to read transaction.");if(!d.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(h=d.product.partner)==null?void 0:h.currencyCode,this.experienceOptions={product:d.product,transaction:d,layouts:[],stateMutationFunc:async()=>{throw new O("State mutation is forbidden in read only mode!")},readOnly:e},this.initialized=!0};if(e)return await a();const i=Y.getMap("transactionOwnerIds")||new Map,s=i.get(t);if(s){const d=(o=(await A.query({query:he,variables:{ids:[t]},errorPolicy:"all"})).data)==null?void 0:o.transactions[0];if(!d)throw new U("Failed to read transaction.");if(!d.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(r=d.product.partner)==null?void 0:r.currencyCode,this.experienceOptions={product:d.product,transaction:d,layouts:[],stateMutationFunc:async B=>this.updateTransactionState({...B,context:{transactionOwnerId:s}}),readOnly:e},this.initialized=!0;return}try{const d=(c=(await A.mutate({mutation:Yi,variables:{id:t},errorPolicy:"all"})).data)==null?void 0:c.transactionClaim;if(!d)throw new U("Failed to read transaction.");if(!d.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(l=d.product.partner)==null?void 0:l.currencyCode,d.transactionOwnerId&&(i.set(d.id,d.transactionOwnerId),Y.setMap("transactionOwnerIds",i)),this.experienceOptions={product:d.product,transaction:d,layouts:[],stateMutationFunc:async B=>this.updateTransactionState({...B,context:{transactionOwnerId:d.transactionOwnerId}}),readOnly:e},this.initialized=!0}catch{throw new U("Attempted to access a transaction that isn't available.")}}async getWorkflowExperienceDeprecated(t,e,A){var a,i,s,o;if(!this.initialized||!this.experienceOptions)throw new U("Cannot launch experience: Not initialized.");if(this.experienceOptions.transaction.workflowId){const r=await Kt(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=r,this.experienceOptions.transaction.workflowState){const l=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(l.layouts).map(g=>g.layout),await Et(l),await Dt(l),this.experienceOptions.reloadedState=l}this.experienceOptions.previewService=A&&A(r),this.experienceOptions.renderableContextService=new Ee(this.experienceOptions.layouts),(a=this.experienceOptions.product)!=null&&a.modelUrl&&(this.experienceOptions.modelContainer=(i=this.experienceOptions.previewService)==null?void 0:i.loadModel({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}));const c=new zt(this,this.experienceOptions);return await c.getWorkflowManager().getInitializationPromise(),c}if(t){const c=(Y.getMap("transactionOwnerIds")||new Map).get(this.experienceOptions.transaction.id),l=P.getShadowGraphqlClient().mutate({mutation:vi,variables:{workflowId:t,id:this.experienceOptions.transaction.id},context:{transactionOwnerId:c}}),g=Kt(t);if(await Promise.all([l,g]),this.experienceOptions.workflow=await g,e){const B=JSON.parse(e);this.experienceOptions.layouts=Object.values(B.layouts).map(h=>h.layout),await Et(B),await Dt(B),this.experienceOptions.reloadedState=B}else this.experienceOptions.layouts=We(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await g),this.experienceOptions.renderableContextService=new Ee(this.experienceOptions.layouts),(s=this.experienceOptions.product)!=null&&s.modelUrl&&(this.experienceOptions.modelContainer=(o=this.experienceOptions.previewService)==null?void 0:o.loadModel({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}));const d=new zt(this,this.experienceOptions);return await d.getWorkflowManager().getInitializationPromise(),d}throw new U("No workflow ID provided.")}getPreviewService(){var t;return(t=this.experienceOptions)==null?void 0:t.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new U("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new U("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}storeCustomer(t){const e=Y.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Y.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t){var i,s;const a=(i=(await P.getShadowGraphqlClient().query({query:Ri,variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:i.integrationProducts;if(!a||a.length===0||!((s=a[0])!=null&&s.id))throw new Error("Integration product not found.");return new gA(a[0])}async getIntegrationProductFromExternalIds(t,e){var s;const i=(s=(await P.getShadowGraphqlClient().query({query:Hi,variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProductFromExternalIds;if(!(i!=null&&i.id))throw new Error("Integration product not found.");return new gA(i)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const A=(Y.getMap("transactionOwnerIds")||new Map).get(t)||void 0,a=await P.getShadowGraphqlClient().query({query:ki,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:A}});if(!a.data.transactions||a.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return a.data.transactions[0].transactionShareActions}}class Ir{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 bn=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(bn||{});class Un extends At{constructor(t,e,A){var a;super(t,e,A),this.frameService=(a=this.manager.getStepSpecificServices(this.getId()))==null?void 0:a.frameService}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ct.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){var a;if(await ct.selectImage(this.step,t,this.manager,A),e){const i=((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Me.BackgroundRemover)}async canRemoveBackground(){var t,e,A,a;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((a=(A=this.frameService)==null?void 0:A.getImageData())!=null&&a.svg)}async removeBackgroundFromImageSelection(t=!0){var i;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 T.removeBackgroundFromAsset(e);t&&await ct.selectImage(this.step,A,this.manager,!1);const a=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,backgroundRemovedAssetKey:A.key,useOriginalAsset:!t}}),A}changeColors(t){ct.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?ct.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ct.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,A,a){return a&&a.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(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.originalAssetKey;if(t)return T.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.backgroundRemovedAssetKey;if(t)return T.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var a;const e=((a=this.getFrameStepStorage())==null?void 0:a.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 i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}exports.AddonHandle=Me;exports.ArrayInput=sr;exports.AspectType=st;exports.AssetNotFoundError=dt;exports.AssetType=Xt;exports.BringForwardCommand=Rs;exports.BringToBackCommand=ks;exports.BringToFrontCommand=Ns;exports.CanvasCommand=J;exports.CollectionProduct=Qe;exports.ColorOptionGlobalPropertyHandle=lA;exports.CommandContext=Ka;exports.ConversionDataType=ha;exports.ConversionLocation=Ba;exports.CreateElementCommand=j;exports.CreateLayoutCommand=MA;exports.DeleteElementCommand=Ct;exports.DigitalContentStepHandle=mn;exports.FileUploadGlobalPropertyHandle=Sn;exports.FlowExecutionNodeResult=jt;exports.FlowExecutionResult=kn;exports.FlowService=Nn;exports.FontAlignmentCommand=qa;exports.FontColorCommand=Wa;exports.FontSizeCommand=Xa;exports.FontSourceCommand=sA;exports.FrameService=_a;exports.FrameStep=bn;exports.FrameStepHandle=Un;exports.GlobalPropertyHandle=Re;exports.GroupCommand=G;exports.IllustrationStepHandle=gn;exports.InformationMessageType=ge;exports.InformationStepHandle=En;exports.IntegrationProduct=gA;exports.IntegrationType=ga;exports.LayoutElementFactory=bs;exports.LayoutElementType=k;exports.LayoutNotFoundError=X;exports.LayoutRenderingPurpose=Pt;exports.MaterialStepHandle=dn;exports.MisconfigurationError=$t;exports.MockWorkflowManager=Ir;exports.ModelStepHandle=Bn;exports.ModuleStepHandle=fn;exports.MoveCommand=ys;exports.ObjectInput=JA;exports.ObjectInputType=Rn;exports.OptionGlobalPropertyHandle=UA;exports.OptionNotFoundError=Zt;exports.ParseError=yt;exports.PictureStepHandle=hn;exports.ProductCameraRig=da;exports.ProductCollection=Yn;exports.ProductWorkflow=Yt;exports.PromiseCache=Nt;exports.PromiseQueue=fA;exports.QuestionStepHandle=Cn;exports.QueueablePromise=mA;exports.ResizeCommand=Ss;exports.ResourceNotFoundError=vt;exports.RotateCommand=Ms;exports.ScaleAxis=W;exports.SendBackwardsCommand=Hs;exports.ShapeStepHandle=wn;exports.ShareActionType=la;exports.SpiffCommerceClient=Hn;exports.StakeholderType=qt;exports.StepAspectType=ca;exports.StepHandle=At;exports.StepType=M;exports.TextAlgorithm=Qt;exports.TextChangeCommand=Za;exports.TextGlobalPropertyHandle=xn;exports.TextInput=ir;exports.TextStepHandle=un;exports.Transform=vn;exports.TransformCollection=Pn;exports.UnhandledBehaviorError=O;exports.UnitOfMeasurement=Ca;exports.UpdateImageSourceCommand=Ps;exports.Variant=it;exports.WorkflowExperienceEventType=Fn;exports.WorkflowExperienceImpl=zt;exports.assetService=T;exports.browserColorToHex=Ra;exports.cmPerPixel=ds;exports.createDesign=Dn;exports.currentDirection=cs;exports.dataUrlFromExternalUrl=ei;exports.designService=fe;exports.determineCorrectFontSizeAndLines=Wt;exports.digitalContentStepService=SA;exports.fetchAsString=tt;exports.findAngle=As;exports.findElement=L;exports.findPmsColors=Wi;exports.frameDataCache=Mt;exports.frameStepService=ct;exports.generate=R;exports.generateCommands=yn;exports.generateSVGWithUnknownColors=ot;exports.generateStateFromDesignInputSteps=No;exports.getAttributesFromArrayBuffer=se;exports.getAxisAlignedBoundingBox=es;exports.getBoundedOffsets=$a;exports.getElementVertices=ls;exports.getFrameData=ce;exports.getNEPoint=os;exports.getNWPoint=ss;exports.getPointOfRotation=is;exports.getSEPoint=rs;exports.getSvgElement=Ne;exports.getTrueCoordinates=ns;exports.getWorkflow=Kt;exports.getWorkflows=OA;exports.graphQlManager=P;exports.illustrationStepService=Vt;exports.isCloseToValue=as;exports.loadFont=bt;exports.matchHexToPms=ji;exports.materialStepService=xA;exports.mmPerPixel=gs;exports.modelStepService=YA;exports.moduleStepService=PA;exports.optionService=_;exports.patternImageDataCache=lt;exports.persistenceService=Y;exports.pictureStepService=vA;exports.pmsToRgb=zi;exports.questionStepService=NA;exports.registerFetchImplementation=Zn;exports.registerWindowImplementation=qn;exports.rehydrateSerializedLayout=Et;exports.rgbToPms=ka;exports.rotateAroundPoint=Lt;exports.sanitizeSvgTree=ve;exports.setBearerAuthenticationToken=Ia;exports.setCanvasModule=wA;exports.shapeStepService=St;exports.shortenUrl=en;exports.spiffCoreConfiguration=nt;exports.stepAspectValuesToDesignInputSteps=vo;exports.svgColorValueToDefinition=nA;exports.svgStringDimensions=pA;exports.svgToDataUrl=hA;exports.textStepService=q;exports.toast=an;exports.xmlSerializer=ae;
3380
+ `,Dt=async n=>{var t;for(const e in n.layouts){const A=n.layouts[e].elements.filter(i=>i.type===k.Illustration);for(let i=0;i<A.length;++i){const s=A[i];s.src&&s.svg&&(s.cachedObjectURL=await te(s.svg))}const a=n.layouts[e].elements.filter(i=>i.type===k.Textbox);for(let i=0;i<a.length;++i){const s=a[i];(t=s.fontData)!=null&&t.assetUrl&&await bt(s.fontData.assetUrl)}}},fr=async(n,t)=>{var a;const e=await P.getShadowGraphqlClient().query({query:ur(((a=t==null?void 0:t.assets)==null?void 0:a.metadata)||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),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(i=>{i.steps.forEach(s=>{var o,r,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((r=s.option.defaultVariant)!=null&&r.asset&&T.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&T.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(l=>{l.asset&&T.cacheAsset(l.asset),l.thumbnail&&T.cacheAsset(l.thumbnail),l.material&&T.cacheMaterial(l.material)}),Nt.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.partner.termsMarkdown}),A},Qr=async(n,t)=>{const A=(await t).find(a=>a.id===n);if(!A)throw new Error(`Workflow not found: ${n}`);return A},OA=async(n,t)=>{const e=n.map(o=>Nt.get({id:o,options:t})),A=n.filter((o,r)=>e[r]===void 0);if(A.length===0)return Promise.all(e);const a=fr(A,t),i=A.map(o=>Nt.set({id:o,options:t},Qr(o,a))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},Kt=async(n,t)=>(await OA([n],t))[0],pr=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:R(),panelId:t.name,name:t.name,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})),We=(n,t)=>{const e=n.workflowState,A=e?JSON.parse(e):void 0;return A?Object.values(A.layouts).map(a=>a.layout):pr(t.panels)};class Hn{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return P.getShadowGraphqlClient().mutate({...e,mutation:Pi})}catch(A){throw console.error(A),new U("Critical - Unable to synchronize workflow state with server.")}},this.initialized=!1,this.options=t,this.options.applicationKey&&ii(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 25.0.9"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configureUrls(t,e,A){nt.setHubUrl(t),nt.setServerUrl(e),nt.setServicesApiUrl(A),this.options.applicationKey&&this.getIntegration()}configure(t){nt.setHubUrl(t.hubUrl),nt.setServerUrl(t.serverUrl),nt.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,t.bearerAuthenticationToken&&Ia(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return T}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!si())throw new Error("Application key required to use Flow Service.");return new Nn}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");const t=async()=>(await P.getShadowGraphqlClient().query({query:Si,errorPolicy:"all",fetchPolicy:"no-cache"})).data.currentIntegration;return this.activeIntegration=t(),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(A){return console.error(A),!1}}async authenticateBundleFromLocalStorage(t){var a,i;const e=Y.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:qt.Owner});const A=Y.getMap("bundlePartnerIds")||new Map;if(A.has(t)){const s=A.get(t),r=(Y.getMap("partnerCustomerIds")||new Map).get(s);if(r&&await this.authenticateCustomerId(r)){const l=(i=(a=this.customer)==null?void 0:a.bundleStakeholders)==null?void 0:i.find(g=>{var d;return((d=g.bundle)==null?void 0:d.id)===t});if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var l,g,d,B,h,C;const e=P.getShadowGraphqlClient(),A=await e.query({query:Er,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 a=A.data.transactions[0];if(!((g=(l=a.product)==null?void 0:l.partner)==null?void 0:g.id))throw new Error(`Unable to read transaction: ${t}`);if(a.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=Y.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:qt.Owner});const o=Y.getMap("transactionCustomerIds");if(o!=null&&o.has(t)){const w=o.get(t);if(w&&await this.authenticateCustomerId(w)){const E=((B=(d=this.customer)==null?void 0:d.bundleStakeholders)==null?void 0:B.find(m=>{var f,p;return(p=(f=m.bundle)==null?void 0:f.transactions)==null?void 0:p.some(I=>I.id===t)}))||((C=(h=this.customer)==null?void 0:h.stakeholders)==null?void 0:C.find(m=>{var f;return((f=m.transaction)==null?void 0:f.id)===t}));if(E)return Promise.resolve({success:!0,stakeholderType:E.type})}}const c=(await e.query({query:mr,errorPolicy:"all",variables:{id:a.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${a.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:a.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Y.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),Y.setMap("transactionCustomerIds",e))}getStakeholderTypeForTransaction(t){var A,a;const e=(a=(A=this.customer)==null?void 0:A.stakeholders)==null?void 0:a.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=P.getShadowGraphqlClient(),a=(await e.query({query:or,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!a.id){const r=(s=(await e.mutate({mutation:rr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!r)throw new Error("Unable to create customer.");return this.storeCustomer(r),this.customer=r,{customer:r,isAuthenticated:!1}}this.storeCustomer(a);const i=await this.authenticateCustomerId(a.id);return{customer:this.customer||a,isAuthenticated:i}}getCustomer(){return this.customer}async authenticateCustomerId(t){var o;const e=P.getShadowGraphqlClient(),A=Y.getMap("customerTokens");if(!(A!=null&&A.has(t)))return!1;const a=A.get(t);if(!a)return!1;const s=(o=(await e.mutate({mutation:cr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:a}})).data)==null?void 0:o.customerAuthenticate;return s?(this.storeCustomer(s),WA(a),this.customer=s,!0):!1}async generateVerificationCode(t){await P.getShadowGraphqlClient().mutate({mutation:lr,variables:{emailAddress:t}})}async verifyCode(t,e){var i,s;const a=(i=(await P.getShadowGraphqlClient().mutate({mutation:gr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data)==null?void 0:i.customerVerifyCode;if(a!=null&&a.loginToken){if(!((s=a.partner)!=null&&s.id))throw new Error(`Unable to find customer: ${t}`);const o=Y.getMap("customerTokens")||new Map;return o.set(a.id,a.loginToken),Y.setMap("customerTokens",o),this.storeCustomer(a),WA(a.loginToken),this.customer={...a,loginToken:void 0},!0}return!1}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await P.getShadowGraphqlClient().query({query:dr,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,A){var c,l,g,d,B;const i=(g=(await P.getShadowGraphqlClient().mutate({mutation:Uo(((l=(c=A==null?void 0:A.graphql)==null?void 0:c.productCollection)==null?void 0:l.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((h,C)=>({key:h[0],value:h[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:g.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=Y.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),Y.setMap("bundlePartnerIds",s);const o=Y.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),Y.setMap("bundleOwnerIds",o);const r=new Ve(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(B=(d=A==null?void 0:A.graphql)==null?void 0:d.productCollection)==null?void 0:B.eagerFetchProducts,createNewGlobalState:!0});return await r.getInitializationPromise(),r}async getExistingBundle(t,e,A,a){var w,u,E,m,f,p,I,Q,F,y,x;const i=Y.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),r=((w=Object.entries(localStorage).find(([v,N])=>v.startsWith("CognitoIdentityServiceProvider")&&v.endsWith("idToken")))==null?void 0:w[0])||"",c=localStorage.getItem(r),l={};c&&!ye(c)&&(l.Authorization=`Bearer ${c}`);const g={bundleOwnerId:s,...l,...(u=a==null?void 0:a.graphql)==null?void 0:u.additionalHeaders},d=await P.getShadowGraphqlClient().query({query:Ro(((m=(E=a==null?void 0:a.graphql)==null?void 0:E.productCollection)==null?void 0:m.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:g}});if(!((f=d.data)!=null&&f.bundles)||((p=d.data)==null?void 0:p.bundles.length)===0||!((I=d.data)!=null&&I.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const B=(Q=d.data)==null?void 0:Q.bundles[0],h=Y.getMap("bundlePartnerIds")||new Map;h.set(B.id,B.partner.id),Y.setMap("bundlePartnerIds",h);const C=new Ve(this,B,e,A,s,{additionalHeaders:(F=a==null?void 0:a.graphql)==null?void 0:F.additionalHeaders,eagerFetchProducts:(x=(y=a==null?void 0:a.graphql)==null?void 0:y.productCollection)==null?void 0:x.eagerFetchProducts});return await C.getInitializationPromise(),C}async duplicateBundle(t,e,A,a){var w,u,E,m,f,p,I,Q;const i=(w=Y.getMap("bundleOwnerIds"))==null?void 0:w.get(t),o=((u=Object.entries(localStorage).find(([F,y])=>F.startsWith("CognitoIdentityServiceProvider")&&F.endsWith("idToken")))==null?void 0:u[0])||"",r=localStorage.getItem(o),c={};r&&!ye(r)&&(c.Authorization=`Bearer ${r}`);const l={bundleOwnerId:i,...c,...(E=a==null?void 0:a.graphql)==null?void 0:E.additionalHeaders},d=(p=(await P.getShadowGraphqlClient().mutate({mutation:Go(((f=(m=a==null?void 0:a.graphql)==null?void 0:m.productCollection)==null?void 0:f.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:A},context:{headers:l},fetchPolicy:"no-cache"})).data)==null?void 0:p.bundleDuplicate;if(!(d!=null&&d.id))throw new Error("Unable to duplicate bundle");const B=Y.getMap("bundlePartnerIds")||new Map;B.set(d.id,d.partner.id),Y.setMap("bundlePartnerIds",B);const h=Y.getMap("bundleOwnerIds")||new Map;h.set(d.id,d.bundleOwnerId),Y.setMap("bundleOwnerIds",h);const C=new Ve(this,d,void 0,void 0,d.bundleOwnerId,{eagerFetchProducts:(Q=(I=a==null?void 0:a.graphql)==null?void 0:I.productCollection)==null?void 0:Q.eagerFetchProducts});return await C.getInitializationPromise(),C}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...A}=t;return(await P.getShadowGraphqlClient().query({query:qo(e??!1),variables:{...A,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){var i;if(!this.customer)throw new Error("Customer not authenticated.");const t=await P.getShadowGraphqlClient().query({query:Ho,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const A=t.data.customers[0].bundleStakeholders||[],a=Y.getMap("bundlePartnerIds")||new Map;return A.forEach(s=>{var o,r;(o=s.bundle)!=null&&o.id&&((r=s.bundle.partner)!=null&&r.id)&&a.set(s.bundle.id,s.bundle.partner.id)}),Y.setMap("bundlePartnerIds",a),A}async getWorkflowExperience(t,e,A,a){var g,d,B,h,C;if(!a)return await this.getWorkflowExperienceDeprecated(t,e,A);const i=async()=>{var u,E,m;const w=P.getShadowGraphqlClient();if(a.type==="transaction"){const{transactionId:f,readOnly:p}=a,I=await w.query({query:he,variables:{ids:[f]},errorPolicy:"all",fetchPolicy:"no-cache"});if(!((u=I.data)!=null&&u.transactions)||I.data.transactions.length===0)throw new U("Existing transaction not found.");const Q=(E=I.data)==null?void 0:E.transactions[0];if(!Q.workflowId)throw new U("Existing transaction has no workflow ID.");const F=await Kt(Q.workflowId);if(!Q.product)throw new U("Failed to load transaction, product not available.");return!this.activeIntegration&&((m=Q.integrationProduct)!=null&&m.integration)&&(this.activeIntegration=Promise.resolve(Q.integrationProduct.integration)),{transaction:Q,workflow:F,readOnly:p}}if(a.type==="integration"||a.type==="external"){const f=async()=>{const F=a.type==="integration"?{integrationProductId:a.integrationProductId}:{externalIntegrationId:a.externalIntegrationId,externalProductId:a.externalProductId},y=await w.mutate({mutation:qA,variables:{...F,workflowId:a.workflowId,designName:a.designName,claim:!0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!y.data||!y.data.transactionCreate)throw new U("Failed to create transaction!");const x=y.data.transactionCreate;if(!x.product)throw new U("Failed to create transaction, product not available.");return x},p=Kt(a.workflowId,a==null?void 0:a.graphql),[I,Q]=await Promise.all([f(),p]);return{transaction:I,workflow:Q}}throw new U("No workflow ID provided.")},{transaction:s,workflow:o,readOnly:r}=await i();this.currencyCode=(g=s.product.partner)==null?void 0:g.currencyCode;const c={product:s.product,transaction:s,layouts:[],singleVariantsRenderable:(d=a==null?void 0:a.workflowConfiguration)==null?void 0:d.singleVariantsRenderable,stateMutationFunc:r?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async w=>{const E=(Y.getMap("transactionOwnerIds")||new Map).get(s.id)||void 0;return this.updateTransactionState({...w,context:{transactionOwnerId:E}})},readOnly:r,workflow:o};if(a.type==="transaction"&&s.workflowState){const w=JSON.parse(s.workflowState);c.layouts=Object.values(w.layouts).map(u=>u.layout),await Et(w),await Dt(w),c.reloadedState=w}else if(!r&&a.workflowState){const w=JSON.parse(a.workflowState);c.layouts=Object.values(w.layouts).map(u=>u.layout),await Et(w),await Dt(w),c.reloadedState=w}else c.layouts=We(c.transaction,c.workflow);if(c.renderableContextService=new Ee(c.layouts),a.previewService?(c.previewService=a.previewService,(B=c.product)!=null&&B.modelUrl&&(c.modelContainer=c.previewService.loadModel({model:c.product.modelUrl,contextService:c.renderableContextService}))):(c.previewService=A&&A(o),(h=c.product)!=null&&h.modelUrl&&(c.modelContainer=(C=c.previewService)==null?void 0:C.loadModel({model:c.product.modelUrl,contextService:c.renderableContextService}))),a.type!=="transaction"){const w=Y.getMap("transactionOwnerIds")||new Map;w.set(s.id,s.transactionOwnerId),Y.setMap("transactionOwnerIds",w)}else c.isReloadedTransaction=!0;this.initialized=!0,this.experienceOptions=c;const l=new zt(this,c);return await l.getWorkflowManager().getInitializationPromise(),a.type!=="transaction"&&this.customer&&await l.attachCustomerDetails({email:this.customer.emailAddress}),l}async getWorkflowExperiences(t,e){if(t.length===0)throw new U("No options provided!");const A=P.getShadowGraphqlClient(),a=async p=>{var y,x,v;if(p.length===0)return[];const I=p.map(N=>N.option.transactionId),Q=await A.query({query:he,variables:{ids:I},errorPolicy:"all",fetchPolicy:"no-cache"}),F=Q.data.transactions;if(F.length!==p.length){const N=((x=(y=Q.errors)==null?void 0:y[0])==null?void 0:x.message)||"Unknown error";throw new U(`Not all transactions were found: ${N}`)}return!this.activeIntegration&&((v=F[0].integrationProduct)!=null&&v.integration)&&(this.activeIntegration=Promise.resolve(F[0].integrationProduct.integration)),F.map((N,H)=>{var V;return{transaction:N,workflowId:N.workflowId,readOnly:((V=p.find(z=>z.option.transactionId===N.id))==null?void 0:V.option.readOnly)??!1,index:p[H].index}})},i=async p=>{var F,y,x;if(p.length===0)return[];const I=await A.mutate({mutation:xi,variables:{inputs:p.map(v=>({integrationProductId:v.option.type==="integration"?v.option.integrationProductId:void 0,externalIntegrationId:v.option.type==="external"?v.option.externalIntegrationId:void 0,externalProductId:v.option.type==="external"?v.option.externalProductId:void 0,workflowId:v.option.workflowId,designName:v.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),Q=(F=I.data)==null?void 0:F.transactionCreateMany;if(!Q||Q.length===0){const v=((x=(y=I.errors)==null?void 0:y[0])==null?void 0:x.message)||"Unknown error";throw new U(`Failed to create transactions: ${v}`)}return Q.map((v,N)=>({transaction:v,workflowId:v.workflowId,readOnly:!1,index:p[N].index}))},s=t.map((p,I)=>({option:p,index:I})),o=s.filter(p=>p.option.type==="transaction"),r=s.filter(p=>p.option.type==="integration"||p.option.type==="external"),c=LA(o,10),l=LA(r,10),g=(await Promise.all([...c.map(a),...l.map(i)])).flat(),d=[...new Set(g.map(p=>p.workflowId))],B=await OA(d,e),h=new Map(B.map(p=>[p.id,p])),C=Y.getMap("transactionOwnerIds")||new Map,w=g.map(async p=>{var V;const{transaction:I,workflowId:Q,readOnly:F,index:y}=p,x=h.get(Q),v=t[y];!C.get(I.id)&&I.transactionOwnerId&&C.set(I.id,I.transactionOwnerId);const N=C.get(I.id)||void 0,H={product:I.product,transaction:I,layouts:[],singleVariantsRenderable:(V=v==null?void 0:v.workflowConfiguration)==null?void 0:V.singleVariantsRenderable,stateMutationFunc:F?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async z=>this.updateTransactionState({...z,context:{transactionOwnerId:N}}),readOnly:F,workflow:x,isReloadedTransaction:v.type==="transaction"};if(v.type==="transaction"&&I.workflowState){const z=JSON.parse(I.workflowState);H.layouts=Object.values(z.layouts||{}).map(at=>at.layout),await Et(z),await Dt(z),H.reloadedState=z}else if(!F&&v.workflowState){const z=JSON.parse(v.workflowState);H.layouts=Object.values(z.layouts||{}).map(at=>at.layout),await Et(z),await Dt(z),H.reloadedState=z}else H.layouts=We(H.transaction,H.workflow);return H.renderableContextService=new Ee(H.layouts),H.delayWorkflowStateSync=!0,this.initialized=!0,this.experienceOptions=H,{experienceOptions:H,index:y,options:v}}),u=await Promise.all(w);Y.setMap("transactionOwnerIds",C);const m=u.sort((p,I)=>p.index-I.index).map(async p=>{const{experienceOptions:I,options:Q}=p,F=new zt(this,I);return await F.getWorkflowManager().getInitializationPromise(),Q.type!=="transaction"&&this.customer&&await F.attachCustomerDetails({email:this.customer.emailAddress}),F}),f=await Promise.all(m);return f.forEach(p=>p.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),f}async initFromIntegrationProduct(t){var s;if(t==="")throw new U("No integration product ID provided.");const A=await P.getShadowGraphqlClient().mutate({mutation:qA,variables:{integrationProductId:t,claim:!0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new U("Failed to create transaction!");const a=A.data.transactionCreate;if(!a.product)throw new U("Failed to create transaction, product not available.");this.currencyCode=(s=a.product.partner)==null?void 0:s.currencyCode;const i=Y.getMap("transactionOwnerIds")||new Map;i.set(a.id,a.transactionOwnerId),Y.setMap("transactionOwnerIds",i),this.experienceOptions={product:a.product,transaction:a,layouts:[],stateMutationFunc:async o=>this.updateTransactionState({...o,context:{transactionOwnerId:a.transactionOwnerId}})},this.initialized=!0}async initFromTransaction(t,e=!1){var o,r,c,l;if(t==="")throw new U("No transaction ID provided.");const A=P.getShadowGraphqlClient(),a=async()=>{var B,h;const d=(B=(await A.query({query:he,variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:B.transactions[0];if(!d)throw new U("Failed to read transaction.");if(!d.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(h=d.product.partner)==null?void 0:h.currencyCode,this.experienceOptions={product:d.product,transaction:d,layouts:[],stateMutationFunc:async()=>{throw new O("State mutation is forbidden in read only mode!")},readOnly:e},this.initialized=!0};if(e)return await a();const i=Y.getMap("transactionOwnerIds")||new Map,s=i.get(t);if(s){const d=(o=(await A.query({query:he,variables:{ids:[t]},errorPolicy:"all"})).data)==null?void 0:o.transactions[0];if(!d)throw new U("Failed to read transaction.");if(!d.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(r=d.product.partner)==null?void 0:r.currencyCode,this.experienceOptions={product:d.product,transaction:d,layouts:[],stateMutationFunc:async B=>this.updateTransactionState({...B,context:{transactionOwnerId:s}}),readOnly:e},this.initialized=!0;return}try{const d=(c=(await A.mutate({mutation:Yi,variables:{id:t},errorPolicy:"all"})).data)==null?void 0:c.transactionClaim;if(!d)throw new U("Failed to read transaction.");if(!d.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(l=d.product.partner)==null?void 0:l.currencyCode,d.transactionOwnerId&&(i.set(d.id,d.transactionOwnerId),Y.setMap("transactionOwnerIds",i)),this.experienceOptions={product:d.product,transaction:d,layouts:[],stateMutationFunc:async B=>this.updateTransactionState({...B,context:{transactionOwnerId:d.transactionOwnerId}}),readOnly:e},this.initialized=!0}catch{throw new U("Attempted to access a transaction that isn't available.")}}async getWorkflowExperienceDeprecated(t,e,A){var a,i,s,o;if(!this.initialized||!this.experienceOptions)throw new U("Cannot launch experience: Not initialized.");if(this.experienceOptions.transaction.workflowId){const r=await Kt(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=r,this.experienceOptions.transaction.workflowState){const l=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(l.layouts).map(g=>g.layout),await Et(l),await Dt(l),this.experienceOptions.reloadedState=l}this.experienceOptions.previewService=A&&A(r),this.experienceOptions.renderableContextService=new Ee(this.experienceOptions.layouts),(a=this.experienceOptions.product)!=null&&a.modelUrl&&(this.experienceOptions.modelContainer=(i=this.experienceOptions.previewService)==null?void 0:i.loadModel({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}));const c=new zt(this,this.experienceOptions);return await c.getWorkflowManager().getInitializationPromise(),c}if(t){const c=(Y.getMap("transactionOwnerIds")||new Map).get(this.experienceOptions.transaction.id),l=P.getShadowGraphqlClient().mutate({mutation:vi,variables:{workflowId:t,id:this.experienceOptions.transaction.id},context:{transactionOwnerId:c}}),g=Kt(t);if(await Promise.all([l,g]),this.experienceOptions.workflow=await g,e){const B=JSON.parse(e);this.experienceOptions.layouts=Object.values(B.layouts).map(h=>h.layout),await Et(B),await Dt(B),this.experienceOptions.reloadedState=B}else this.experienceOptions.layouts=We(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await g),this.experienceOptions.renderableContextService=new Ee(this.experienceOptions.layouts),(s=this.experienceOptions.product)!=null&&s.modelUrl&&(this.experienceOptions.modelContainer=(o=this.experienceOptions.previewService)==null?void 0:o.loadModel({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}));const d=new zt(this,this.experienceOptions);return await d.getWorkflowManager().getInitializationPromise(),d}throw new U("No workflow ID provided.")}getPreviewService(){var t;return(t=this.experienceOptions)==null?void 0:t.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new U("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new U("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}storeCustomer(t){const e=Y.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Y.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t){var i,s;const a=(i=(await P.getShadowGraphqlClient().query({query:Ri,variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:i.integrationProducts;if(!a||a.length===0||!((s=a[0])!=null&&s.id))throw new Error("Integration product not found.");return new gA(a[0])}async getIntegrationProductFromExternalIds(t,e){var s;const i=(s=(await P.getShadowGraphqlClient().query({query:Hi,variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProductFromExternalIds;if(!(i!=null&&i.id))throw new Error("Integration product not found.");return new gA(i)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const A=(Y.getMap("transactionOwnerIds")||new Map).get(t)||void 0,a=await P.getShadowGraphqlClient().query({query:ki,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:A}});if(!a.data.transactions||a.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return a.data.transactions[0].transactionShareActions}}class Ir{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 bn=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(bn||{});class Un extends At{constructor(t,e,A){var a;super(t,e,A),this.frameService=(a=this.manager.getStepSpecificServices(this.getId()))==null?void 0:a.frameService}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ct.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){var a;if(await ct.selectImage(this.step,t,this.manager,A),e){const i=((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Me.BackgroundRemover)}async canRemoveBackground(){var t,e,A,a;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((a=(A=this.frameService)==null?void 0:A.getImageData())!=null&&a.svg)}async removeBackgroundFromImageSelection(t=!0){var i;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 T.removeBackgroundFromAsset(e);t&&await ct.selectImage(this.step,A,this.manager,!1);const a=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,backgroundRemovedAssetKey:A.key,useOriginalAsset:!t}}),A}changeColors(t){ct.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?ct.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ct.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,A,a){return a&&a.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(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.originalAssetKey;if(t)return T.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.backgroundRemovedAssetKey;if(t)return T.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var a;const e=((a=this.getFrameStepStorage())==null?void 0:a.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 i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}exports.AddonHandle=Me;exports.ArrayInput=sr;exports.AspectType=st;exports.AssetNotFoundError=dt;exports.AssetType=Xt;exports.BringForwardCommand=Rs;exports.BringToBackCommand=ks;exports.BringToFrontCommand=Ns;exports.CanvasCommand=J;exports.CollectionProduct=Qe;exports.ColorOptionGlobalPropertyHandle=lA;exports.CommandContext=Ka;exports.ConversionDataType=ha;exports.ConversionLocation=Ba;exports.CreateElementCommand=j;exports.CreateLayoutCommand=MA;exports.DeleteElementCommand=Ct;exports.DigitalContentStepHandle=mn;exports.FileUploadGlobalPropertyHandle=Sn;exports.FlowExecutionNodeResult=jt;exports.FlowExecutionResult=kn;exports.FlowService=Nn;exports.FontAlignmentCommand=qa;exports.FontColorCommand=Wa;exports.FontSizeCommand=Xa;exports.FontSourceCommand=sA;exports.FrameService=_a;exports.FrameStep=bn;exports.FrameStepHandle=Un;exports.GlobalPropertyHandle=Re;exports.GroupCommand=G;exports.IllustrationStepHandle=gn;exports.InformationMessageType=ge;exports.InformationStepHandle=En;exports.IntegrationProduct=gA;exports.IntegrationType=ga;exports.LayoutElementFactory=bs;exports.LayoutElementType=k;exports.LayoutNotFoundError=X;exports.LayoutRenderingPurpose=Pt;exports.MaterialStepHandle=dn;exports.MisconfigurationError=$t;exports.MockWorkflowManager=Ir;exports.ModelStepHandle=Bn;exports.ModuleStepHandle=fn;exports.MoveCommand=ys;exports.ObjectInput=JA;exports.ObjectInputType=Rn;exports.OptionGlobalPropertyHandle=UA;exports.OptionNotFoundError=Zt;exports.ParseError=yt;exports.PictureStepHandle=hn;exports.ProductCameraRig=da;exports.ProductCollection=Yn;exports.ProductWorkflow=Yt;exports.PromiseCache=Nt;exports.PromiseQueue=fA;exports.QuestionStepHandle=Cn;exports.QueueablePromise=mA;exports.ResizeCommand=Ss;exports.ResourceNotFoundError=vt;exports.RotateCommand=Ms;exports.ScaleAxis=W;exports.SendBackwardsCommand=Hs;exports.ShapeStepHandle=wn;exports.ShareActionType=la;exports.SpiffCommerceClient=Hn;exports.StakeholderType=qt;exports.StepAspectType=ca;exports.StepHandle=At;exports.StepType=M;exports.TextAlgorithm=Qt;exports.TextChangeCommand=Za;exports.TextGlobalPropertyHandle=xn;exports.TextInput=ir;exports.TextStepHandle=un;exports.Transform=vn;exports.TransformCollection=Pn;exports.UnhandledBehaviorError=O;exports.UnitOfMeasurement=Ca;exports.UpdateImageSourceCommand=Ps;exports.Variant=it;exports.WorkflowExperienceEventType=Fn;exports.WorkflowExperienceImpl=zt;exports.assetService=T;exports.browserColorToHex=Ra;exports.cmPerPixel=ds;exports.createDesign=Dn;exports.currentDirection=cs;exports.dataUrlFromExternalUrl=ei;exports.designService=fe;exports.determineCorrectFontSizeAndLines=Wt;exports.digitalContentStepService=SA;exports.fetchAsString=tt;exports.findAngle=As;exports.findElement=L;exports.findPmsColors=Wi;exports.frameDataCache=Mt;exports.frameStepService=ct;exports.generate=R;exports.generateCommands=yn;exports.generateSVGWithUnknownColors=ot;exports.generateStateFromDesignInputSteps=No;exports.getAttributesFromArrayBuffer=se;exports.getAxisAlignedBoundingBox=es;exports.getBoundedOffsets=$a;exports.getElementVertices=ls;exports.getFrameData=ce;exports.getNEPoint=os;exports.getNWPoint=ss;exports.getPointOfRotation=is;exports.getSEPoint=rs;exports.getSvgElement=Ne;exports.getTrueCoordinates=ns;exports.getWorkflow=Kt;exports.getWorkflows=OA;exports.graphQlManager=P;exports.illustrationStepService=Vt;exports.isCloseToValue=as;exports.loadFont=bt;exports.matchHexToPms=ji;exports.materialStepService=xA;exports.mmPerPixel=gs;exports.modelStepService=YA;exports.moduleStepService=PA;exports.optionService=_;exports.patternImageDataCache=lt;exports.persistenceService=Y;exports.pictureStepService=vA;exports.pmsToRgb=zi;exports.questionStepService=NA;exports.registerFetchImplementation=Zn;exports.registerWindowImplementation=qn;exports.rehydrateSerializedLayout=Et;exports.rgbToPms=ka;exports.rotateAroundPoint=Lt;exports.sanitizeSvgTree=ve;exports.setBearerAuthenticationToken=Ia;exports.setCanvasModule=wA;exports.shapeStepService=St;exports.shortenUrl=en;exports.spiffCoreConfiguration=nt;exports.stepAspectValuesToDesignInputSteps=vo;exports.svgColorValueToDefinition=nA;exports.svgStringDimensions=pA;exports.svgToDataUrl=hA;exports.textStepService=q;exports.toast=an;exports.xmlSerializer=ae;
package/dist/index.mjs CHANGED
@@ -63,7 +63,7 @@ class O extends Ie {
63
63
  super(`Unhandled Behavior Encountered: ${t}`);
64
64
  }
65
65
  }
66
- class Ht extends Ie {
66
+ class bt extends Ie {
67
67
  constructor(t) {
68
68
  super(`Parsing Error: ${t}`);
69
69
  }
@@ -346,10 +346,7 @@ class Yi {
346
346
  return new $a({
347
347
  link: _a([a, A, e, t]),
348
348
  cache: new ti(),
349
- name: "Core",
350
- devtools: {
351
- enabled: !0
352
- }
349
+ name: "Core"
353
350
  });
354
351
  }
355
352
  }
@@ -481,7 +478,7 @@ const Pi = (i) => new Promise((t) => {
481
478
  }
482
479
  ${i && "...AssetMetadataFields" || ""}
483
480
  }
484
- `, Hi = F`
481
+ `, bi = F`
485
482
  ${qt(!1)}
486
483
  query GetAssets($keys: [String]!) {
487
484
  assets(keys: $keys) {
@@ -535,7 +532,7 @@ const Pi = (i) => new Promise((t) => {
535
532
  fileLink
536
533
  }
537
534
  }
538
- `, bi = F`
535
+ `, Hi = F`
539
536
  ${gA}
540
537
  query GetMaterials($ids: [String]) {
541
538
  materials(id: $ids) {
@@ -564,16 +561,14 @@ const Pi = (i) => new Promise((t) => {
564
561
  }
565
562
  }
566
563
  `, _e = async (i) => (await Y.getShadowGraphqlClient().query({
567
- query: Hi,
564
+ query: bi,
568
565
  errorPolicy: "all",
569
- fetchPolicy: "no-cache",
570
566
  variables: {
571
567
  keys: i
572
568
  }
573
569
  })).data.assets, Ji = async (i) => (await Y.getShadowGraphqlClient().query({
574
- query: bi,
570
+ query: Hi,
575
571
  errorPolicy: "all",
576
- fetchPolicy: "no-cache",
577
572
  variables: {
578
573
  ids: i
579
574
  }
@@ -931,7 +926,6 @@ const Lt = new Li(), oa = F`
931
926
  const t = await Y.getShadowGraphqlClient().query({
932
927
  query: zi,
933
928
  errorPolicy: "all",
934
- fetchPolicy: "no-cache",
935
929
  variables: {
936
930
  ids: i
937
931
  }
@@ -1808,7 +1802,7 @@ const Zt = (i) => {
1808
1802
  if (i.defaultVariant !== void 0)
1809
1803
  return t.find((e) => e.id === i.defaultVariant);
1810
1804
  }
1811
- }, wt = /* @__PURE__ */ new Map(), bt = /* @__PURE__ */ new Map(), Re = /* @__PURE__ */ new Map(), Ca = async (i, t) => {
1805
+ }, wt = /* @__PURE__ */ new Map(), Ht = /* @__PURE__ */ new Map(), Re = /* @__PURE__ */ new Map(), Ca = async (i, t) => {
1812
1806
  if (!t) {
1813
1807
  if (!i)
1814
1808
  throw new Error("No region or src supplied. Cannot construct frame!");
@@ -1835,8 +1829,8 @@ const Zt = (i) => {
1835
1829
  if (Re.has(i))
1836
1830
  return Re.get(i);
1837
1831
  const e = (async () => {
1838
- if (bt.has(i))
1839
- return bt.get(i);
1832
+ if (Ht.has(i))
1833
+ return Ht.get(i);
1840
1834
  await new Promise((d) => setTimeout(d, 0));
1841
1835
  const a = Bt().parseFromString(i, "image/svg+xml"), n = a.querySelector("svg");
1842
1836
  if (!n)
@@ -1854,7 +1848,7 @@ const Zt = (i) => {
1854
1848
  width: c,
1855
1849
  height: r
1856
1850
  };
1857
- return bt.set(d, B), B;
1851
+ return Ht.set(d, B), B;
1858
1852
  }
1859
1853
  if (g) {
1860
1854
  const d = g.getAttribute("d");
@@ -1865,7 +1859,7 @@ const Zt = (i) => {
1865
1859
  width: c,
1866
1860
  height: r
1867
1861
  };
1868
- return bt.set(d, B), B;
1862
+ return Ht.set(d, B), B;
1869
1863
  }
1870
1864
  throw new Error("Malformed frame SVG");
1871
1865
  })();
@@ -4612,7 +4606,7 @@ const Zt = (i) => {
4612
4606
  "3E2B2E",
4613
4607
  "101820",
4614
4608
  "3D3935"
4615
- ], He = Mt.map((i) => [
4609
+ ], be = Mt.map((i) => [
4616
4610
  parseInt(i.substring(0, 2), 16),
4617
4611
  parseInt(i.substring(2, 4), 16),
4618
4612
  parseInt(i.substring(4, 6), 16)
@@ -4635,7 +4629,7 @@ function Qr(i, t = 64) {
4635
4629
  const n = parseInt(i.substring(0, 2), 16), s = parseInt(i.substring(2, 4), 16), o = parseInt(i.substring(4, 6), 16);
4636
4630
  let r, c, l;
4637
4631
  for (let g = 0; g < Mt.length; g++) {
4638
- r = He[g][0], c = He[g][1], l = He[g][2];
4632
+ r = be[g][0], c = be[g][1], l = be[g][2];
4639
4633
  const d = Math.sqrt(Math.pow(n - r, 2) + Math.pow(s - c, 2) + Math.pow(o - l, 2));
4640
4634
  A.push(d);
4641
4635
  }
@@ -4674,7 +4668,7 @@ const ae = (i) => {
4674
4668
  return `icc-named-color(${t.slice(e + 1).slice(0, -4)}, ${i.namedColor})`;
4675
4669
  }
4676
4670
  return `icc-named-color(${i.profileName}, ${i.namedColor})`;
4677
- }, HA = (i) => {
4671
+ }, bA = (i) => {
4678
4672
  const t = i.split(/[ ](?=[^)]*?(?:\(|$))/);
4679
4673
  if (t.length === 0)
4680
4674
  return { browserValue: "#000000" };
@@ -4813,12 +4807,12 @@ const ae = (i) => {
4813
4807
  wn.includes(s.tagName) && !s.attributes.getNamedItem("fill") && s.setAttribute("fill", "black");
4814
4808
  const o = s.attributes.getNamedItem("fill");
4815
4809
  if (o && o.value !== "none" && !o.value.startsWith("url(")) {
4816
- const c = HA(o.value), l = c.browserValue.replace(/\W/g, ""), g = `spiff-fill-${l}`;
4810
+ const c = bA(o.value), l = c.browserValue.replace(/\W/g, ""), g = `spiff-fill-${l}`;
4817
4811
  s.setAttribute("fill", c.browserValue), s.classList.add(g), A[l] = c;
4818
4812
  }
4819
4813
  const r = s.attributes.getNamedItem("stroke");
4820
4814
  if (r && r.value !== "none" && !r.value.startsWith("url(")) {
4821
- const c = HA(r.value), l = c.browserValue.replace(/\W/g, ""), g = `spiff-stroke-${l}`;
4815
+ const c = bA(r.value), l = c.browserValue.replace(/\W/g, ""), g = `spiff-stroke-${l}`;
4822
4816
  s.classList.add(g), s.setAttribute("stroke", c.browserValue), A[l] = c;
4823
4817
  }
4824
4818
  });
@@ -5206,9 +5200,9 @@ class In {
5206
5200
  }), A - a;
5207
5201
  }
5208
5202
  }
5209
- const Dn = (i) => i.substring(0, 5).toLowerCase().trim() === "data:", be = /* @__PURE__ */ new Map(), $t = async (i) => {
5210
- if (be.has(i))
5211
- return be.get(i);
5203
+ const Dn = (i) => i.substring(0, 5).toLowerCase().trim() === "data:", He = /* @__PURE__ */ new Map(), $t = async (i) => {
5204
+ if (He.has(i))
5205
+ return He.get(i);
5212
5206
  const e = (async () => {
5213
5207
  try {
5214
5208
  return mt(i).getFont();
@@ -5222,7 +5216,7 @@ const Dn = (i) => i.substring(0, 5).toLowerCase().trim() === "data:", be = /* @_
5222
5216
  }
5223
5217
  }
5224
5218
  })();
5225
- return be.set(i, e), e;
5219
+ return He.set(i, e), e;
5226
5220
  }, CA = (i) => {
5227
5221
  const t = ea(i), e = Ve.parse(t);
5228
5222
  return AA(i, e), e;
@@ -5235,7 +5229,7 @@ const Dn = (i) => i.substring(0, 5).toLowerCase().trim() === "data:", be = /* @_
5235
5229
  const e = new In(t);
5236
5230
  return Fa.set(i, e), e;
5237
5231
  }, Ee = (i, t, e, A) => Math.max(Sn(i.join(`
5238
- `), e, A), t), bA = (i, t, e, A, a, n) => {
5232
+ `), e, A), t), HA = (i, t, e, A, a, n) => {
5239
5233
  const s = (n || wA) * a.getApproximateHeight(), o = t.split(`
5240
5234
  `);
5241
5235
  try {
@@ -5293,7 +5287,7 @@ const Dn = (i) => i.substring(0, 5).toLowerCase().trim() === "data:", be = /* @_
5293
5287
  var c;
5294
5288
  const a = mt(t.fontData.assetUrl), n = a.getFont(), s = t.fontSize / n.unitsPerEm;
5295
5289
  if (!e)
5296
- return bA(t, i, t.fontSize, s, a, A);
5290
+ return HA(t, i, t.fontSize, s, a, A);
5297
5291
  let o;
5298
5292
  if (t.text ? o = t.text.split(`
5299
5293
  `) : o = ((c = t.input) == null ? void 0 : c.split(`
@@ -5310,7 +5304,7 @@ const Dn = (i) => i.substring(0, 5).toLowerCase().trim() === "data:", be = /* @_
5310
5304
  requiredHeight: t.height,
5311
5305
  requiredWidth: Ee(o, t.width, s, a),
5312
5306
  fontSize: Fn(o, a, n, t.width, t.height, A)
5313
- } : bA(t, i, t.fontSize, s, a, A);
5307
+ } : HA(t, i, t.fontSize, s, a, A);
5314
5308
  }, Mn = (i, t, e, A, a) => {
5315
5309
  const s = mt(t.assetUrl).getFont();
5316
5310
  let o = { ...i };
@@ -5752,7 +5746,7 @@ class Rr extends T {
5752
5746
  };
5753
5747
  }
5754
5748
  }
5755
- class Hr extends T {
5749
+ class br extends T {
5756
5750
  constructor(t, e) {
5757
5751
  super(), this.id = t, this.angle = e;
5758
5752
  }
@@ -5774,7 +5768,7 @@ class Hr extends T {
5774
5768
  };
5775
5769
  }
5776
5770
  }
5777
- class br extends T {
5771
+ class Hr extends T {
5778
5772
  constructor(t, e, A) {
5779
5773
  super(), this.id = t, this.width = Math.abs(e), this.height = Math.abs(A);
5780
5774
  }
@@ -5913,7 +5907,7 @@ class ft extends T {
5913
5907
  };
5914
5908
  }
5915
5909
  }
5916
- class Hn extends T {
5910
+ class bn extends T {
5917
5911
  constructor(t, e, A) {
5918
5912
  super(), this.id = t, this.color = e, this.textFillSpotColor = A;
5919
5913
  }
@@ -5959,7 +5953,7 @@ class Ge extends T {
5959
5953
  };
5960
5954
  }
5961
5955
  }
5962
- class bn extends T {
5956
+ class Hn extends T {
5963
5957
  constructor(t, e) {
5964
5958
  super(), this.id = t, this.size = e;
5965
5959
  }
@@ -6362,7 +6356,7 @@ class zn {
6362
6356
  return;
6363
6357
  }
6364
6358
  t.forEach((e, A) => {
6365
- const a = bt.get(e);
6359
+ const a = Ht.get(e);
6366
6360
  a && (this.frameData || (this.frameData = new Array(t.length)), this.frameData[A] = a);
6367
6361
  });
6368
6362
  }
@@ -7962,7 +7956,7 @@ class $n {
7962
7956
  };
7963
7957
  }
7964
7958
  }
7965
- const Ha = new $n();
7959
+ const ba = new $n();
7966
7960
  class _n {
7967
7961
  async init(t, e, A) {
7968
7962
  const a = t.option;
@@ -8021,7 +8015,7 @@ class _n {
8021
8015
  };
8022
8016
  }
8023
8017
  }
8024
- const ba = new _n();
8018
+ const Ha = new _n();
8025
8019
  class ts {
8026
8020
  constructor() {
8027
8021
  this.shapeFillId = "spiff-fill-shape";
@@ -8399,7 +8393,7 @@ class is {
8399
8393
  for (const c of A) {
8400
8394
  if (!e.fill)
8401
8395
  throw new Error("Fill not set on new color selection!");
8402
- const l = new Hn(c.id, e.fill, o);
8396
+ const l = new bn(c.id, e.fill, o);
8403
8397
  n(l);
8404
8398
  }
8405
8399
  }
@@ -8643,9 +8637,9 @@ class is {
8643
8637
  const w = A.colorOption;
8644
8638
  let u;
8645
8639
  if (w && w.variants) {
8646
- const v = w.variants.find((H) => {
8640
+ const v = w.variants.find((b) => {
8647
8641
  var V;
8648
- return H.id === ((V = w.defaultVariant) == null ? void 0 : V.id);
8642
+ return b.id === ((V = w.defaultVariant) == null ? void 0 : V.id);
8649
8643
  }) || w.variants[0];
8650
8644
  u = this.createTextFillSpotColor(w, v), s.updateStorage(t, {
8651
8645
  colorProfileAssetKey: (C = w.colorProfile) == null ? void 0 : C.key
@@ -8727,7 +8721,7 @@ class is {
8727
8721
  generateTextChangeCommandsForRegion(t, e, A, a) {
8728
8722
  const n = [], s = new Tn(A, a);
8729
8723
  if (n.push(s), !e.size) {
8730
- const r = new bn(A, t);
8724
+ const r = new Hn(A, t);
8731
8725
  n.push(r);
8732
8726
  }
8733
8727
  return new G(n);
@@ -10050,14 +10044,14 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
10050
10044
  </g>
10051
10045
  </svg>
10052
10046
 
10053
- `, b = (i) => fi("http://www.w3.org/2000/svg", i), fA = (i, t) => {
10054
- const e = b("rect");
10047
+ `, H = (i) => fi("http://www.w3.org/2000/svg", i), fA = (i, t) => {
10048
+ const e = H("rect");
10055
10049
  return e.setAttribute("height", `${i}`), e.setAttribute("width", `${t}`), e;
10056
10050
  }, os = () => {
10057
- const i = b("svg");
10051
+ const i = H("svg");
10058
10052
  return i.setAttribute("xmlns", "http://www.w3.org/2000/svg"), i.setAttribute("xmlns:xlink", "http://www.w3.org/1999/xlink"), i.setAttribute("version", "1.1"), i;
10059
10053
  }, rs = (i) => {
10060
- const t = b("use");
10054
+ const t = H("use");
10061
10055
  return t.setAttribute("xlink:href", i), t.setAttribute("href", i), t;
10062
10056
  };
10063
10057
  function Ua(i) {
@@ -10065,7 +10059,7 @@ function Ua(i) {
10065
10059
  return t.setAttribute("height", `${a}`), t.setAttribute("width", `${A}`), [t, a, A];
10066
10060
  }
10067
10061
  const cs = (i, t, e) => {
10068
- const A = b("g");
10062
+ const A = H("g");
10069
10063
  i.appendChild(A), A.setAttribute("id", e), A.innerHTML = t;
10070
10064
  };
10071
10065
  function Ga(i, t, e) {
@@ -10144,7 +10138,7 @@ class pA {
10144
10138
  d = (g * 100 | 0) / 100;
10145
10139
  break;
10146
10140
  default:
10147
- throw new Ht("Failed to encode path.");
10141
+ throw new bt("Failed to encode path.");
10148
10142
  }
10149
10143
  r || s.push(" "), s.push(d), r = !1;
10150
10144
  }
@@ -10158,12 +10152,12 @@ class pA {
10158
10152
  for (e.lastIndex = 0; n = e.exec(t); ) {
10159
10153
  const s = n[1].toLowerCase(), o = (n[2].match(A) || []).map(parseFloat), r = s === n[1], c = OA[s];
10160
10154
  if (o.length < c.length)
10161
- throw new Ht(
10155
+ throw new bt(
10162
10156
  `Path type "${s}" given ${o.length} arguments, expected ${c.length}.`
10163
10157
  );
10164
10158
  if (c.length > 0) {
10165
10159
  if (o.length % c.length !== 0)
10166
- throw new Ht(
10160
+ throw new bt(
10167
10161
  `Path type "${s}" given ${o.length} arguments, not divisible by ${c.length}`
10168
10162
  );
10169
10163
  for (let l = 0; l < o.length / c.length; l++) {
@@ -10188,7 +10182,7 @@ class pA {
10188
10182
  if (o in n && r in n) {
10189
10183
  const c = [n[o], n[r]], l = e(c);
10190
10184
  if (l.length < 2)
10191
- throw new Ht("Transformer must return at least 2 points.");
10185
+ throw new bt("Transformer must return at least 2 points.");
10192
10186
  n[o] = l[0], n[r] = l[1];
10193
10187
  }
10194
10188
  }
@@ -10227,26 +10221,26 @@ class gs extends mA {
10227
10221
  }
10228
10222
  brandSvg(t, e) {
10229
10223
  const A = t.toSVG(2), a = t.getBoundingBox(), n = a.x2 - a.x1, s = t.toPathData(3), o = () => {
10230
- const p = b("g"), I = b("defs");
10224
+ const p = H("g"), I = H("defs");
10231
10225
  p.appendChild(I), I.appendChild(Ja(3, 7, 4, "shadow"));
10232
- const Q = b("g");
10226
+ const Q = H("g");
10233
10227
  p.appendChild(Q), Q.setAttribute("filter", "url(#shadow)"), Q.innerHTML = A;
10234
- const D = b("g");
10228
+ const D = H("g");
10235
10229
  p.appendChild(D), D.setAttribute("fill", "red"), D.setAttribute("stroke", "red"), D.setAttribute("stroke-width", "9"), D.innerHTML = A;
10236
- const y = b("g");
10230
+ const y = H("g");
10237
10231
  p.appendChild(y), y.setAttribute("fill", "#9d2621"), y.setAttribute("transform", "translate(1,1)"), y.innerHTML = A;
10238
- const S = b("g");
10239
- return p.appendChild(S), S.setAttribute("fill", "yellow"), S.innerHTML = A, new pA(p).transform(([v, H]) => [v, H + (n / 2 - v) ** 2 / (n * 2.9)]), p;
10232
+ const S = H("g");
10233
+ return p.appendChild(S), S.setAttribute("fill", "yellow"), S.innerHTML = A, new pA(p).transform(([v, b]) => [v, b + (n / 2 - v) ** 2 / (n * 2.9)]), p;
10240
10234
  }, [r, c, l] = Ua(e);
10241
10235
  if (!r)
10242
10236
  return "";
10243
- const g = b("defs");
10237
+ const g = H("defs");
10244
10238
  r.appendChild(g), Ga(r, g, e);
10245
- const d = c * 0.23, B = l * 0.94, h = l * 0.04, C = c * 0.53, w = b("g");
10239
+ const d = c * 0.23, B = l * 0.94, h = l * 0.04, C = c * 0.53, w = H("g");
10246
10240
  r.appendChild(w), w.setAttribute("transform", `translate(${h} ${C}) rotate(-21)`);
10247
10241
  const u = fA(d, B);
10248
10242
  u.setAttribute("opacity", "0"), w.appendChild(u);
10249
- const E = b("g");
10243
+ const E = H("g");
10250
10244
  w.appendChild(E);
10251
10245
  const m = o();
10252
10246
  E.appendChild(m);
@@ -10271,29 +10265,29 @@ class Bs extends mA {
10271
10265
  }
10272
10266
  brandSvg(t, e, A) {
10273
10267
  const a = t.toSVG(2), n = t.getBoundingBox(), s = n.y2 - n.y1, o = n.x2 - n.x1, r = t.toPathData(3), c = () => {
10274
- const Q = b("g"), D = b("g");
10268
+ const Q = H("g"), D = H("g");
10275
10269
  Q.appendChild(D), D.setAttribute("stroke", "#5C1A0D"), D.setAttribute("stroke-width", "4"), D.setAttribute("transform", "translate(1,1)"), D.innerHTML = a;
10276
- const y = b("g");
10270
+ const y = H("g");
10277
10271
  Q.appendChild(y), y.setAttribute("fill", "#FFE386"), y.setAttribute("transform", "translate(1,1)"), y.innerHTML = a;
10278
- const S = b("g");
10272
+ const S = H("g");
10279
10273
  Q.appendChild(S), S.setAttribute("fill", "white"), S.innerHTML = a;
10280
10274
  const P = new pA(Q);
10281
- return P.transform(([v, H]) => [v, H + ((o - v) * H) ** 2 / (o * 5e4)]), P.transform(([v, H]) => [
10275
+ return P.transform(([v, b]) => [v, b + ((o - v) * b) ** 2 / (o * 5e4)]), P.transform(([v, b]) => [
10282
10276
  v,
10283
- H + (o / 3 - v) ** 2 / o * this.indicator(v < o / 3)
10284
- ]), P.transform(([v, H]) => [v - (s - H) * (o - v) / 800, H]), Q;
10277
+ b + (o / 3 - v) ** 2 / o * this.indicator(v < o / 3)
10278
+ ]), P.transform(([v, b]) => [v - (s - b) * (o - v) / 800, b]), Q;
10285
10279
  }, [l, g, d] = Ua(e);
10286
10280
  if (!l)
10287
10281
  return "";
10288
- const B = b("defs");
10282
+ const B = H("defs");
10289
10283
  l.appendChild(B), Ga(l, B, e);
10290
10284
  let h, C, w, u;
10291
10285
  A ? (h = g * 0.25 * (1 + 0.1), C = d / 2 * (1 + 0.1), w = d * 0.22, u = g * 0.32) : (h = g * 0.22 * (1 + 0.1), C = d * 0.8, w = d * 0.067, u = g * 0.33);
10292
- const E = b("g");
10286
+ const E = H("g");
10293
10287
  l.appendChild(E), E.setAttribute("transform", `translate(${w} ${u}) rotate(-10)`);
10294
10288
  const m = fA(h, C);
10295
10289
  m.setAttribute("opacity", "0"), E.appendChild(m);
10296
- const f = b("g");
10290
+ const f = H("g");
10297
10291
  E.appendChild(f);
10298
10292
  const p = c();
10299
10293
  f.appendChild(p);
@@ -10315,29 +10309,29 @@ class Cs extends mA {
10315
10309
  }
10316
10310
  svgElement(t, e) {
10317
10311
  const A = CA(hs), n = t !== "" ? ((m) => m.charAt(0).toUpperCase() + m.substr(1).toLowerCase())(t) : "", s = A.getPath(n, 0, 72, 72), o = s.toSVG(2), r = s.getBoundingBox(), c = r.x2 - r.x1, l = s.toPathData(3), g = () => {
10318
- const m = b("g");
10312
+ const m = H("g");
10319
10313
  m.classList.add("module-text-group");
10320
- const f = b("defs");
10314
+ const f = H("defs");
10321
10315
  m.appendChild(f), f.appendChild(Ja(0, 2, 2, "shadow"));
10322
- const p = b("path");
10316
+ const p = H("path");
10323
10317
  p.setAttribute("d", l), p.setAttribute("stroke", "black"), p.setAttribute("stroke-width", "3"), f.appendChild(p);
10324
- const I = b("g");
10318
+ const I = H("g");
10325
10319
  I.classList.add("module-layer0"), m.appendChild(I), I.setAttribute("filter", "url(#shadow)"), I.innerHTML = p.outerHTML;
10326
- const Q = b("g");
10320
+ const Q = H("g");
10327
10321
  Q.classList.add("module-layer1"), m.appendChild(Q), Q.setAttribute("stroke-width", "3"), Q.setAttribute("stroke", "rgb(45,41,38)"), Q.setAttribute("fill", "rgb(45,41,38)"), Q.setAttribute("transform", "translate(0.5,0)"), Q.innerHTML = o;
10328
- const D = b("g");
10322
+ const D = H("g");
10329
10323
  D.classList.add("module-layer2"), m.appendChild(D), D.setAttribute("fill", "rgb(255,209,0)"), D.setAttribute("transform", "translate(1,-0.1)"), D.innerHTML = o;
10330
- const y = b("g");
10324
+ const y = H("g");
10331
10325
  return y.classList.add("module-layer3"), m.appendChild(y), y.setAttribute("fill", "white"), y.innerHTML = o, new pA(m).transform(([P, v]) => [P, v + (c / 2 - P) ** 2 / (c * 6)]), m;
10332
- }, d = b("g");
10326
+ }, d = H("g");
10333
10327
  d.classList.add("module-root");
10334
- const B = b("defs");
10328
+ const B = H("defs");
10335
10329
  d.appendChild(B);
10336
- const h = b("g");
10330
+ const h = H("g");
10337
10331
  h.classList.add("module-bounds"), d.appendChild(h);
10338
10332
  const C = fA(e.height, e.width);
10339
10333
  C.setAttribute("opacity", "0"), h.appendChild(C);
10340
- const w = b("g");
10334
+ const w = H("g");
10341
10335
  w.classList.add("module-text-enclosure"), d.appendChild(w);
10342
10336
  const u = g();
10343
10337
  w.appendChild(u);
@@ -10923,12 +10917,12 @@ class us {
10923
10917
  break;
10924
10918
  case M.Picture:
10925
10919
  A.push(
10926
- Ha.init(r, this, this.reloadedState)
10920
+ ba.init(r, this, this.reloadedState)
10927
10921
  );
10928
10922
  break;
10929
10923
  case M.Question:
10930
10924
  A.push(
10931
- ba.init(r, this, this.reloadedState)
10925
+ Ha.init(r, this, this.reloadedState)
10932
10926
  );
10933
10927
  break;
10934
10928
  case M.Shape:
@@ -11305,7 +11299,7 @@ class Qs extends at {
11305
11299
  * @returns A promise that can be awaited to ensure the new image asset has been updated on the design.
11306
11300
  */
11307
11301
  selectVariant(t) {
11308
- return Ha.selectVariant(
11302
+ return ba.selectVariant(
11309
11303
  this.step,
11310
11304
  t.getResource(),
11311
11305
  this.manager,
@@ -11320,7 +11314,7 @@ class ps extends at {
11320
11314
  async selectVariant(t) {
11321
11315
  if (!t.getId())
11322
11316
  throw new Error("Unable to select variant with a null ID");
11323
- await ba.selectVariant(this.step, t.getId(), this.manager);
11317
+ await Ha.selectVariant(this.step, t.getId(), this.manager);
11324
11318
  }
11325
11319
  /**
11326
11320
  * The way that this step expects to be rendered.
@@ -11896,19 +11890,19 @@ const Ys = async (i) => {
11896
11890
  context: {
11897
11891
  transactionOwnerId: S
11898
11892
  }
11899
- }), H = (V = v.data) == null ? void 0 : V.transactions[0].workflowState;
11893
+ }), b = (V = v.data) == null ? void 0 : V.transactions[0].workflowState;
11900
11894
  return v.errors ? (v.errors.forEach((L) => {
11901
11895
  v.errors && console.log("Server Error:", L.message);
11902
- }), null) : H ?? null;
11896
+ }), null) : b ?? null;
11903
11897
  })() || (console.warn("State mismatch detected. Uploading known state explicitly"), console.warn("State Object:", JSON.stringify(A())), await i.updateStateWithServerImmediate(A), console.log("Server state is undefined @ Workflow completion"));
11904
11898
  const d = i.getPreviewService(), B = (D = t == null ? void 0 : t.finalizeStepConfig) == null ? void 0 : D.lookAtAnimation, h = d && t.showModelOnFinishStep && !!B, C = r && nA(r, t, !0), w = r && nA(r, t, !1), u = async (y) => {
11905
11899
  const S = {};
11906
11900
  let P = 0;
11907
11901
  if (Object.keys(n).length > 0)
11908
11902
  for (const v of Object.keys(n)) {
11909
- const H = n[v], V = t.steps.find((L) => L.stepName === v);
11910
- for (let L = 0; L < H.selections.length; ++L) {
11911
- const At = H.selections[L];
11903
+ const b = n[v], V = t.steps.find((L) => L.stepName === v);
11904
+ for (let L = 0; L < b.selections.length; ++L) {
11905
+ const At = b.selections[L];
11912
11906
  if (V && (!y || V.option && (V.option.variants || []).length > 1 && !V.data.hideSelectionInCart && !V.data.hideSelectionsInCart)) {
11913
11907
  const ve = V.stepTitle;
11914
11908
  S[ve] ? S[ve].push({
@@ -12123,7 +12117,7 @@ class Rs {
12123
12117
  throw new O("Unexpected storage method requested");
12124
12118
  }
12125
12119
  }
12126
- const Le = new Rs(), Hs = F`
12120
+ const Le = new Rs(), bs = F`
12127
12121
  mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
12128
12122
  transactionAddStakeholder(id: $id, details: $details, type: $type) {
12129
12123
  id
@@ -12138,7 +12132,7 @@ const Le = new Rs(), Hs = F`
12138
12132
  }
12139
12133
  }
12140
12134
  `;
12141
- var bs = /* @__PURE__ */ ((i) => (i.QuantityChanged = "QuantityChanged", i.PriceBreakChanged = "PriceBreakChanged", i))(bs || {});
12135
+ var Hs = /* @__PURE__ */ ((i) => (i.QuantityChanged = "QuantityChanged", i.PriceBreakChanged = "PriceBreakChanged", i))(Hs || {});
12142
12136
  class oe {
12143
12137
  constructor(t, e) {
12144
12138
  var a;
@@ -12391,7 +12385,7 @@ class oe {
12391
12385
  async assignCustomerDetails(t) {
12392
12386
  var s, o, r;
12393
12387
  const A = (x.getMap("transactionOwnerIds") || /* @__PURE__ */ new Map()).get(this.getWorkflowManager().getTransaction().id), n = (r = (o = (s = (await Y.getShadowGraphqlClient().mutate({
12394
- mutation: Hs,
12388
+ mutation: bs,
12395
12389
  variables: {
12396
12390
  id: this.getWorkflowManager().getTransaction().id,
12397
12391
  details: t,
@@ -12875,7 +12869,7 @@ const Us = [
12875
12869
  const c = await tt(n, !0), l = (g) => {
12876
12870
  const d = /<svg.*?<\/svg>/s, B = g.match(d) || [], h = (B == null ? void 0 : B.length) > 0 ? B[0] : "", u = Bt().parseFromString(h, "image/svg+xml").firstElementChild;
12877
12871
  if (!u)
12878
- throw new Ht("Failed to read SVG.");
12872
+ throw new bt("Failed to read SVG.");
12879
12873
  return BA(u), Me().serializeToString(u);
12880
12874
  };
12881
12875
  r.forEach((g) => {
@@ -14228,11 +14222,14 @@ class Do {
14228
14222
  throw new Error("Unable to update global property state");
14229
14223
  }
14230
14224
  async getOrCreateGlobalPropertyState() {
14231
- var A, a, n;
14232
- const t = await Y.getShadowGraphqlClient().query({
14233
- query: Io,
14234
- errorPolicy: "all",
14235
- fetchPolicy: "no-cache",
14225
+ var e, A, a;
14226
+ if (!((e = this.bundleOptions) != null && e.createNewGlobalState)) {
14227
+ const n = await this._getGlobalPropertyState();
14228
+ if (n.data.globalPropertyState && n.data.globalPropertyState.id)
14229
+ return n.data.globalPropertyState;
14230
+ }
14231
+ const t = await Y.getShadowGraphqlClient().mutate({
14232
+ mutation: Qo,
14236
14233
  variables: {
14237
14234
  bundleId: this.bundleId
14238
14235
  },
@@ -14243,23 +14240,26 @@ class Do {
14243
14240
  }
14244
14241
  }
14245
14242
  });
14246
- if (t.data.globalPropertyState && t.data.globalPropertyState.id)
14247
- return t.data.globalPropertyState;
14248
- const e = await Y.getShadowGraphqlClient().mutate({
14249
- mutation: Qo,
14243
+ if ((a = t.data) != null && a.globalPropertyStateCreate && t.data.globalPropertyStateCreate.id)
14244
+ return t.data.globalPropertyStateCreate;
14245
+ throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`);
14246
+ }
14247
+ async _getGlobalPropertyState() {
14248
+ var e;
14249
+ return await Y.getShadowGraphqlClient().query({
14250
+ query: Io,
14251
+ errorPolicy: "all",
14252
+ fetchPolicy: "no-cache",
14250
14253
  variables: {
14251
14254
  bundleId: this.bundleId
14252
14255
  },
14253
14256
  context: {
14254
14257
  headers: {
14255
14258
  bundleOwnerId: this.bundleOwnerId,
14256
- ...(a = this.bundleOptions) == null ? void 0 : a.additionalHeaders
14259
+ ...(e = this.bundleOptions) == null ? void 0 : e.additionalHeaders
14257
14260
  }
14258
14261
  }
14259
14262
  });
14260
- if ((n = e.data) != null && n.globalPropertyStateCreate && e.data.globalPropertyStateCreate.id)
14261
- return e.data.globalPropertyStateCreate;
14262
- throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`);
14263
14263
  }
14264
14264
  }
14265
14265
  class Fo {
@@ -14393,8 +14393,7 @@ class yo {
14393
14393
  id: this.getId(),
14394
14394
  productIds: t
14395
14395
  },
14396
- errorPolicy: "all",
14397
- fetchPolicy: "no-cache"
14396
+ errorPolicy: "all"
14398
14397
  });
14399
14398
  return t || (this.fullFetched = !0), this.collection.productCollectionProducts = e.data.productCollections[0].productCollectionProducts || [], this.collection.productCollectionProducts.map((A) => new ze(A));
14400
14399
  }
@@ -15394,11 +15393,11 @@ const No = F`
15394
15393
  }
15395
15394
  }
15396
15395
  }
15397
- `, Ho = F`
15396
+ `, bo = F`
15398
15397
  mutation CustomerGenerateVerificationCode($emailAddress: String!) {
15399
15398
  customerGenerateVerificationCode(emailAddress: $emailAddress)
15400
15399
  }
15401
- `, bo = F`
15400
+ `, Ho = F`
15402
15401
  mutation CustomerVerifyCode($emailAddress: String!, $verificationCode: String!) {
15403
15402
  customerVerifyCode(emailAddress: $emailAddress, verificationCode: $verificationCode) {
15404
15403
  id
@@ -16081,7 +16080,7 @@ class Xo {
16081
16080
  } catch (A) {
16082
16081
  throw console.error(A), new U("Critical - Unable to synchronize workflow state with server.");
16083
16082
  }
16084
- }, this.initialized = !1, this.options = t, this.options.applicationKey && Fi(this.options.applicationKey), console.debug("------------------------"), console.debug("Spiff Commerce Core SDK"), console.debug("Version: 25.0.8"), console.debug(`Application Key Provided: ${!!this.options.applicationKey}`), console.debug("------------------------");
16083
+ }, this.initialized = !1, this.options = t, this.options.applicationKey && Fi(this.options.applicationKey), console.debug("------------------------"), console.debug("Spiff Commerce Core SDK"), console.debug("Version: 25.0.9"), console.debug(`Application Key Provided: ${!!this.options.applicationKey}`), console.debug("------------------------");
16085
16084
  }
16086
16085
  /** @deprecated Use `configure` instead */
16087
16086
  configureUrls(t, e, A) {
@@ -16305,7 +16304,7 @@ class Xo {
16305
16304
  */
16306
16305
  async generateVerificationCode(t) {
16307
16306
  await Y.getShadowGraphqlClient().mutate({
16308
- mutation: Ho,
16307
+ mutation: bo,
16309
16308
  variables: {
16310
16309
  emailAddress: t
16311
16310
  }
@@ -16320,7 +16319,7 @@ class Xo {
16320
16319
  async verifyCode(t, e) {
16321
16320
  var n, s;
16322
16321
  const a = (n = (await Y.getShadowGraphqlClient().mutate({
16323
- mutation: bo,
16322
+ mutation: Ho,
16324
16323
  errorPolicy: "all",
16325
16324
  fetchPolicy: "no-cache",
16326
16325
  variables: {
@@ -16345,7 +16344,6 @@ class Xo {
16345
16344
  throw new Error("Customer must be logged in before calling this function.");
16346
16345
  return (await Y.getShadowGraphqlClient().query({
16347
16346
  query: Uo,
16348
- fetchPolicy: "no-cache",
16349
16347
  variables: {
16350
16348
  id: this.customer.id
16351
16349
  }
@@ -16374,7 +16372,8 @@ class Xo {
16374
16372
  const o = x.getMap("bundleOwnerIds") || /* @__PURE__ */ new Map();
16375
16373
  o.set(n.id, n.bundleOwnerId), x.setMap("bundleOwnerIds", o);
16376
16374
  const r = new je(this, n, void 0, void 0, n.bundleOwnerId, {
16377
- eagerFetchProducts: (B = (d = A == null ? void 0 : A.graphql) == null ? void 0 : d.productCollection) == null ? void 0 : B.eagerFetchProducts
16375
+ eagerFetchProducts: (B = (d = A == null ? void 0 : A.graphql) == null ? void 0 : d.productCollection) == null ? void 0 : B.eagerFetchProducts,
16376
+ createNewGlobalState: !0
16378
16377
  });
16379
16378
  return await r.getInitializationPromise(), r;
16380
16379
  }
@@ -16632,13 +16631,13 @@ class Xo {
16632
16631
  const v = ((S = (y = Q.errors) == null ? void 0 : y[0]) == null ? void 0 : S.message) || "Unknown error";
16633
16632
  throw new U(`Not all transactions were found: ${v}`);
16634
16633
  }
16635
- return !this.activeIntegration && ((P = D[0].integrationProduct) != null && P.integration) && (this.activeIntegration = Promise.resolve(D[0].integrationProduct.integration)), D.map((v, H) => {
16634
+ return !this.activeIntegration && ((P = D[0].integrationProduct) != null && P.integration) && (this.activeIntegration = Promise.resolve(D[0].integrationProduct.integration)), D.map((v, b) => {
16636
16635
  var V;
16637
16636
  return {
16638
16637
  transaction: v,
16639
16638
  workflowId: v.workflowId,
16640
16639
  readOnly: ((V = p.find((L) => L.option.transactionId === v.id)) == null ? void 0 : V.option.readOnly) ?? !1,
16641
- index: p[H].index
16640
+ index: p[b].index
16642
16641
  };
16643
16642
  });
16644
16643
  }, n = async (p) => {
@@ -16681,7 +16680,7 @@ class Xo {
16681
16680
  var V;
16682
16681
  const { transaction: I, workflowId: Q, readOnly: D, index: y } = p, S = h.get(Q), P = t[y];
16683
16682
  !C.get(I.id) && I.transactionOwnerId && C.set(I.id, I.transactionOwnerId);
16684
- const v = C.get(I.id) || void 0, H = {
16683
+ const v = C.get(I.id) || void 0, b = {
16685
16684
  product: I.product,
16686
16685
  transaction: I,
16687
16686
  layouts: [],
@@ -16695,18 +16694,18 @@ class Xo {
16695
16694
  };
16696
16695
  if (P.type === "transaction" && I.workflowState) {
16697
16696
  const L = JSON.parse(I.workflowState);
16698
- H.layouts = Object.values(L.layouts || {}).map((At) => At.layout), await It(L), await Dt(L), H.reloadedState = L;
16697
+ b.layouts = Object.values(L.layouts || {}).map((At) => At.layout), await It(L), await Dt(L), b.reloadedState = L;
16699
16698
  } else if (!D && P.workflowState) {
16700
16699
  const L = JSON.parse(P.workflowState);
16701
- H.layouts = Object.values(L.layouts || {}).map((At) => At.layout), await It(L), await Dt(L), H.reloadedState = L;
16700
+ b.layouts = Object.values(L.layouts || {}).map((At) => At.layout), await It(L), await Dt(L), b.reloadedState = L;
16702
16701
  } else
16703
- H.layouts = Ke(
16704
- H.transaction,
16705
- H.workflow
16702
+ b.layouts = Ke(
16703
+ b.transaction,
16704
+ b.workflow
16706
16705
  );
16707
- return H.renderableContextService = new re(
16708
- H.layouts
16709
- ), H.delayWorkflowStateSync = !0, this.initialized = !0, this.experienceOptions = H, { experienceOptions: H, index: y, options: P };
16706
+ return b.renderableContextService = new re(
16707
+ b.layouts
16708
+ ), b.delayWorkflowStateSync = !0, this.initialized = !0, this.experienceOptions = b, { experienceOptions: b, index: y, options: P };
16710
16709
  }), u = await Promise.all(w);
16711
16710
  x.setMap("transactionOwnerIds", C);
16712
16711
  const m = u.sort((p, I) => p.index - I.index).map(async (p) => {
@@ -17311,8 +17310,8 @@ export {
17311
17310
  Po as FlowExecutionResult,
17312
17311
  Yo as FlowService,
17313
17312
  Un as FontAlignmentCommand,
17314
- Hn as FontColorCommand,
17315
- bn as FontSizeCommand,
17313
+ bn as FontColorCommand,
17314
+ Hn as FontSizeCommand,
17316
17315
  JA as FontSourceCommand,
17317
17316
  zn as FrameService,
17318
17317
  qo as FrameStep,
@@ -17338,7 +17337,7 @@ export {
17338
17337
  vo as ObjectInputType,
17339
17338
  Wa as OptionGlobalPropertyHandle,
17340
17339
  we as OptionNotFoundError,
17341
- Ht as ParseError,
17340
+ bt as ParseError,
17342
17341
  Qs as PictureStepHandle,
17343
17342
  di as ProductCameraRig,
17344
17343
  yo as ProductCollection,
@@ -17347,9 +17346,9 @@ export {
17347
17346
  ha as PromiseQueue,
17348
17347
  ps as QuestionStepHandle,
17349
17348
  Ba as QueueablePromise,
17350
- br as ResizeCommand,
17349
+ Hr as ResizeCommand,
17351
17350
  Ot as ResourceNotFoundError,
17352
- Hr as RotateCommand,
17351
+ br as RotateCommand,
17353
17352
  W as ScaleAxis,
17354
17353
  Or as SendBackwardsCommand,
17355
17354
  Is as ShapeStepHandle,
@@ -17370,7 +17369,7 @@ export {
17370
17369
  Ci as UnitOfMeasurement,
17371
17370
  Ur as UpdateImageSourceCommand,
17372
17371
  nt as Variant,
17373
- bs as WorkflowExperienceEventType,
17372
+ Hs as WorkflowExperienceEventType,
17374
17373
  oe as WorkflowExperienceImpl,
17375
17374
  J as assetService,
17376
17375
  Cn as browserColorToHex,
@@ -17385,7 +17384,7 @@ export {
17385
17384
  Dr as findAngle,
17386
17385
  z as findElement,
17387
17386
  pr as findPmsColors,
17388
- bt as frameDataCache,
17387
+ Ht as frameDataCache,
17389
17388
  Ct as frameStepService,
17390
17389
  R as generate,
17391
17390
  Ws as generateCommands,
@@ -17416,9 +17415,9 @@ export {
17416
17415
  _ as optionService,
17417
17416
  wt as patternImageDataCache,
17418
17417
  x as persistenceService,
17419
- Ha as pictureStepService,
17418
+ ba as pictureStepService,
17420
17419
  fr as pmsToRgb,
17421
- ba as questionStepService,
17420
+ Ha as questionStepService,
17422
17421
  Er as registerFetchImplementation,
17423
17422
  ur as registerWindowImplementation,
17424
17423
  It as rehydrateSerializedLayout,
@@ -17431,7 +17430,7 @@ export {
17431
17430
  jn as shortenUrl,
17432
17431
  it as spiffCoreConfiguration,
17433
17432
  zr as stepAspectValuesToDesignInputSteps,
17434
- HA as svgColorValueToDefinition,
17433
+ bA as svgColorValueToDefinition,
17435
17434
  ua as svgStringDimensions,
17436
17435
  ta as svgToDataUrl,
17437
17436
  Z as textStepService,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spiffcommerce/core",
3
- "version": "25.0.8",
3
+ "version": "25.0.9",
4
4
  "description": "Core client API for interacting with the Spiff Commerce backend.",
5
5
  "source": "src/index.ts",
6
6
  "main": "./dist/index.js",