@spiffcommerce/core 28.0.1-beta.29d7ea3f-e4d3-5c03-bd48-b02b5e782f5a → 28.0.1-beta.c9d47279-485f-5468-a067-5177a42fb1ae

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1435,7 +1435,7 @@
1435
1435
  fill="${e.color}"
1436
1436
  />
1437
1437
  </svg>
1438
- `,n={};n["spiff-fill-shape"]={browserValue:e.color};const i=e.region||await qt(t,M.Illustration),s=Q();return{stepRegion:e.region,colors:n,id:s,svg:a,type:M.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layer:i.layer||0,layerIndex:i.layerIndex||Gt(t,i.layer||0),immutable:i.immutable}}static async getIllustration(t,e){const a=e.region||await qt(t,M.Illustration,e.src),n=await ot(await rr(e.src)),i=await ne(n.svg),s=Q();return{cachedObjectURL:i,stepRegion:e.region,colors:n.colors,id:s,src:e.src,svg:n.svg,type:M.Illustration,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||Gt(t,a.layer||0),immutable:a.immutable}}}class G extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,G.prototype)}}const L=(r,t)=>_(r,t).elements.find(n=>n.id===r),_=(r,t)=>{const e=Object.values(t).find(a=>a.elements.some(n=>n.id===r));if(!e)throw new G;return e},X=(r,t)=>{const e=[...t.elements.filter(n=>n.id!==r.id),r],a=xa(e);return{layout:t.layout,elements:a,modificationID:Q()}},ir=async r=>{var a;const t=[...Object.keys(r.layouts)],e=[...new Set(t)];for(let n=0;n<e.length;n++){const i=e[n],s=r.layouts[i];await Promise.all(s.elements.map(async o=>{var l,c,d;if(o.type==="illustration"){const A=o;if(A.src&&!A.svg){const u=await tt(A.src),h=await ot(u);A.svg=ba(h.svg,A.width,A.height,A.colors)}}else if(o.type==="frame"){const A=o;if((l=A.pattern)!=null&&l.colors&&((c=A.pattern)!=null&&c.src)){const u=await tt((d=A.pattern)==null?void 0:d.src),h=await ot(u);A.pattern.svg=h.svg}}isNaN(o.x)&&(o.x=0),isNaN(o.y)&&(o.y=0),isNaN(o.width)&&(o.width=0),isNaN(o.height)&&(o.height=0),isNaN(o.rotation)&&(o.rotation=0)}))}for(const n in r.layouts){const i=r.layouts[n].elements.filter(o=>o.type===M.Illustration);for(let o=0;o<i.length;++o){const l=i[o];if(l.src&&l.svg)try{l.cachedObjectURL=await ne(l.svg)}catch(c){console.log(c)}}const s=r.layouts[n].elements.filter(o=>o.type===M.Textbox);for(let o=0;o<s.length;++o){const l=s[o];(a=l.fontData)!=null&&a.assetUrl&&await It(l.fontData.assetUrl)}}};class O{undo(){if(!this.oldState)throw new Error("Cannot undo.");return this.oldState}overrideOldState(t){this.oldState=t}}class sn extends O{constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class Ao extends O{constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,x:this.x,y:this.y},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class uo extends O{constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,rotation:this.angle},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class ho extends O{constructor(t,e,a){super(),this.id=t,this.width=Math.abs(e),this.height=Math.abs(a)}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;let a={...e,width:this.width,height:this.height};if(e.type==="frame"){const s=a;s.scaleX=s.scaleX*this.width/e.width,s.scaleY=s.scaleY*this.height/e.height}else if(e.type==="textbox"){const s=a,o=(!s.algorithm||s.algorithm===Bt.Autosize?s.text:s.input)??"";a=ce(s,o,e)}const n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class $ extends O{constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class Ta extends O{constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:Q()}}}}}class q extends O{constructor(t,e){super(),this.element=t,this.layout=e}apply(t){this.oldState=t,t.layouts[this.layout.id]||(t.layouts[this.layout.id]={layout:this.layout,elements:[],modificationID:""});const e=t.layouts[this.layout.id].elements;if(e.find(o=>o.id===this.element.id))throw new Error(`Failed to apply new ${this.element.type} element because ID ${this.element.id} already taken`);if(this.element.productOverlay||e.length===0){const o=[...e,this.element];return this.element.layerIndex===void 0&&(this.element.layerIndex=this.assignIndex(this.element,o)),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:o,modificationID:Q()}}}}const n=e[e.length-1],i=n.productOverlay?n:null;i&&e.pop();let s;if(this.element.layerIndex!==null&&this.element.layerIndex!==void 0)s=[...e,this.element].sort((o,l)=>o.layerIndex!==void 0&&l.layerIndex!==void 0?o.layerIndex-l.layerIndex:0);else{const o=this.assignIndex(this.element,e);this.element.layerIndex=o!==void 0?o:0,s=[...e,this.element]}return i&&s.push(i),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:s,modificationID:Q()}}}}assignIndex(t,e){var n;if(e.length===0)return 0;const a=(n=e.filter(i=>(i.layer||0)===(t.layer||0)).sort((i,s)=>(i.layerIndex||0)-(s.layerIndex||0))[e.length-1])==null?void 0:n.layerIndex;return a!==void 0?a+1:0}}class Ct extends O{constructor(t){super(),this.id=t}apply(t){this.oldState=t;let e=!1;const a=Object.values(t.layouts).map(i=>(i.elements.filter(o=>o.id!==this.id).length!==i.elements.length&&(e=!0),{...i,elements:i.elements.filter(o=>o.id!==this.id),modificationID:Q()}));e||console.log(`Failed to delete element ${this.id}`);const n={};return a.forEach(i=>{n[i.layout.id]=i}),{...t,layouts:n}}}class sr extends O{constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class Ke extends O{constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,textFillImage:this.imageFill},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class or extends O{constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,fontSize:this.size},n=_(e.id,Object.values(t.layouts)),i=(!e.algorithm||e.algorithm===Bt.Autosize?e.text:e.input)??"",s=X(ce(a,i),n);return{...t,layouts:{...t.layouts,[n.layout.id]:s}}}}class ha extends O{constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,fontData:this.fontData},n=_(e.id,Object.values(t.layouts)),i=(!e.algorithm||e.algorithm===Bt.Autosize?e.text:e.input)??"",s=X(ce(a,i),n);return{...t,layouts:{...t.layouts,[n.layout.id]:s}}}}class lr extends O{constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,align:this.align},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class go extends O{constructor(t,e,a){super(),this.id=t,this.imageData=e,this.offsets=a}apply(t){this.oldState=t;const e=_(this.id,Object.values(t.layouts)),a=e.elements.findIndex(o=>o.id===this.id),n=e.elements[a].pattern,i=[...e.elements];i.splice(a,1,{...e.elements[a],pattern:{...n,src:this.imageData.src,x:this.offsets.x,y:this.offsets.y,width:this.imageData.width,height:this.imageData.height,scaleX:this.offsets.zoom,scaleY:this.offsets.zoom,svg:this.imageData.svg,colors:this.imageData.colors}});const s={...e,elements:i,modificationID:Q()};return{...t,layouts:{...t.layouts,[e.layout.id]:s}}}}class mo extends O{constructor(t,e,a,n,i){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=n,this.thresholdSaturation=i}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class po extends O{constructor(t,e){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,src:this.src},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class cr extends O{constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a=_(e.id,Object.values(t.layouts)),n=X(ce(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:n}}}}class _e extends O{constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class ga extends O{constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a=e.colors||{},n=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:n==null?void 0:n.spotColor,pmsValue:n==null?void 0:n.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:n==null?void 0:n.spotColor,pmsValue:this.fill.pmsValue};const i={...e,colors:a},s=_(e.id,Object.values(t.layouts)),o=X(i,s);return{...t,layouts:{...t.layouts,[s.layout.id]:o}}}}class fo extends O{constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},n=_(e.id,Object.values(t.layouts)),i=X(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class Co extends O{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!L(this.id,Object.values(t.layouts)).id)throw new G;const a=Object.values(t.layouts).find(s=>s.elements.find(o=>o.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(s=>s.id===this.id);a.elements.push(a.elements.splice(n,1)[0]);const i=[...a.elements];return i.forEach((s,o)=>s.layerIndex=o),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:i,modificationID:Q()}}}}}class wo extends O{constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a=Object.values(t.layouts).find(o=>o.elements.find(l=>l.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(o=>o.id===this.id);a.elements.splice(n,1),a.elements.unshift(e);const i=[...a.elements],s=i.splice(n,1)[0];return i.splice(n,0,s),i.forEach((o,l)=>o.layerIndex=l),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:i,modificationID:Q()}}}}}class yo extends O{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!L(this.id,Object.values(t.layouts)).id)throw new G;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),i=n+1,s=[...a.elements],o=s.splice(n,1)[0];return s.splice(i,0,o),s.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:s,modificationID:Q()}}}}}class So extends O{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!L(this.id,Object.values(t.layouts)).id)throw new G;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),i=n-1,s=[...a.elements],o=s.splice(n,1)[0];return s.splice(i,0,o),s.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:s,modificationID:Q()}}}}}class on{constructor(t,e,a){this.processRegion=async n=>{var l,c,d,A;const i=this.layouts.find(u=>u.panelId===n.panelId);if(!i)throw new Y(n);let s="";if(this.configuration.type===P.ProductOverlay){let u="";if((l=this.product)!=null&&l.overlayImageUrl&&(u=this.product.overlayImageUrl),s=u,!u)throw new ee(this.configuration,"Couldn't find an asset for product overlay step")}const o=this.evaluateAssetType();if(o===M.Image){const u=this.configuration.type===P.SilentIllustration?(c=this.configuration.data.asset)==null?void 0:c.fileLink:(d=this.product)==null?void 0:d.overlayImageUrl;if(!u)throw new Error("Undefined raster silent step source");const h={stepName:this.configuration.stepName,id:Q(),src:u,type:o,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable,productOverlay:this.configuration.type===P.ProductOverlay?!0:void 0,rotation:n.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:h.id,region:n},command:new q(h,i)}}else{const u=this.configuration.type===P.SilentIllustration?(A=this.configuration.data.asset)==null?void 0:A.fileLink:s,g=await ot(await(async()=>new Promise((p,f)=>{if(!u){f("Undefined vector silent step source");return}tt(u,!0).then(C=>{p(C)}).catch(C=>console.error(C))}))()),m={stepName:this.configuration.stepName,id:Q(),cachedObjectURL:await ne(g.svg),src:u,svg:g.svg,colors:g.colors,type:o,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,rotation:n.rotation,immutable:n.immutable,productOverlay:this.configuration.type===P.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:m.id,region:n},command:new q(m,i)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new ee(this.configuration,"Missing regions.");if(this.configuration.type===P.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}else return this.configuration.type===P.ProductOverlay?Promise.all(this.configuration.data.regions.map(t=>{if(!this.layouts.find(a=>t.panelId===a.panelId))throw new Y(t);return this.processRegion(t)})):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){var e,a,n;const t=this.configuration.type===P.ProductOverlay&&((e=this.product)!=null&&e.overlayImageUrl)?this.product.overlayImageUrl.toLowerCase():(n=(a=this.configuration.data.asset)==null?void 0:a.fileLink)==null?void 0:n.toLowerCase().split("?")[0];return t!=null&&t.startsWith("data:image/png")||t!=null&&t.endsWith(".jpeg")||t!=null&&t.endsWith(".jpg")||t!=null&&t.endsWith(".png")?M.Image:(t!=null&&t.endsWith(".svg")||t!=null&&t.startsWith("image/svg+xml"),M.Illustration)}}const dr=async r=>{const t=`${At.getServicesApiUrl()}/shortener`;try{return(await(await st(t,{method:"POST",body:JSON.stringify({longUrl:r}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new Te("Failed to shorten URL, see console.")}};class Ar{async poll(){try{if(await this.predicate()){this.onSuccess(),this.pollingId>-1&&window.clearInterval(this.pollingId);return}}catch{}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,a,n=3e3,i=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=i,this.poll()}}class vo{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{var A,u;const c=(A=n==null?void 0:n.storage)==null?void 0:A.videoShortUrl,d=(u=n==null?void 0:n.storage)==null?void 0:u.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,n){const i=async()=>{var m,p;const h=(await Be([e]))[0],g=(p=(m=h==null?void 0:h.versions)==null?void 0:m.find(f=>f.name==="mpeg4"))==null?void 0:p.link;return{asset:h,link:g}},s=await new Promise((h,g)=>{new Ar(async()=>!!(await i()).link,async()=>{const m=await i();if(!m.link||!m.link)throw new Nt(m.asset);h({rel:"mpeg4",href:m.link})},()=>{g("Poller timed out with 40 attempts @ 3 second interval")},3e3,40)});t.forEach(h=>a.getCommandDispatcher()(new Ct(h.id)));const o=n.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(o+n.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([s]))),l.pathname=l.pathname+(l.pathname.slice(-1)==="/"?"":"/");const c=l.toString();if(c.length>=2e3)throw new Te("Cannot create QR code, URL too long.");const d=await dr(c);if(!n.data||!n.data.regions)throw new ee(n,"Missing regions.");const A=await this.regionElements(n),u=await this.command(d,A,a,n.stepName);return u&&(u.command&&a.getCommandDispatcher()(u.command),u.followup&&await u.followup()),await a.setSelectionsAndElements(n.stepName,[],A,async()=>{a.updateStorage(n.stepName,{videoShortUrl:d,videoUrl:s.href})}),d}async regionElements(t){const e=a=>({id:Q(),region:a});return t.data.regions.map(e)}async command(t,e,a,n){const i=a.getLayouts(),o=`data:image/svg+xml;base64,${btoa(await yn.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,A=i.find(u=>u.panelId===(d==null?void 0:d.panelId));if(!A&&d)throw new Y(d);if(A&&!d)throw new Error("Region not found");if(!A||!d)throw new Error("Neither a region or layout found!");return new q({stepRegion:d,stepName:n,id:c.id,src:o,type:M.Image,y:d.top,x:d.left,width:d.width,height:d.height,rotation:0},A)});return{command:new $(l),followup:async()=>{}}}}const Na=new vo;class De{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return Aa(e);const a=t.asset;if(!a)throw new mt(t);const n=a.fileLink;if(n)return tt(n,!0);throw new Nt(a)}}async init(t,e,a){const n=a==null?void 0:a.serializableWorkflow.steps.find(o=>o.stepName===t.stepName);if(n!=null&&n.storage&&Object.keys(n.storage).length!==0||n!=null&&n.selectedVariants&&n.selectedVariants.length!==0)return await this.reload(t,e,a),null;t.mandatory&&e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]);let i;const s=e.getWorkflowExperience().getBundle();if(s&&t.globalPropertyAspectConfigurations){const o=s.getGlobalPropertyStateManager(),l=t.globalPropertyAspectConfigurations[0],c=o.getAspectStorage(l.aspectName);c&&c.originalAssetKey&&(i=(await U.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option&&t.option.variants&&t.option.variants.length>0){const o=t.option,l=H.getDefaultVariant(o);return l?this.selectVariantCommand(t,l,[],e,void 0,i||t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,i||t.data.placeholderImageUrl)}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName).map(d=>({id:d.id,region:d.stepRegion}));if(!t.option||(t.option.variants||[]).length===0){const d=t.data.regions.map(A=>Aa(A));e.updateStorage(t.stepName,{currentFrameSources:d})}if(n){const d=async()=>{var g,m,p,f,C;const A=(g=n.storage)==null?void 0:g.colors,u=(m=n.storage)==null?void 0:m.framePatternSrc,h=(p=n.storage)==null?void 0:p.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:h,framePatternSrc:u}),u){const w=(f=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:f.frameService;if(!w)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(u,w,!0,A),e.updateMetadata(t.stepName,{image:u}),e.updateStorage(t.stepName,{framePatternSrc:u}),this.validateColorCount(t,e)}if(h!=null&&h.some(w=>w.zoom)){const w=(C=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:C.frameService;if(!w)throw new Error("Frame service unavailable, cannot load pattern!");w.updateOffsets(h)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const A=n.selectedVariants[0].id;if(t.option&&A){const u=(c=t.option.variants)==null?void 0:c.find(h=>h.id===A);u&&await e.setSelectionsAndElements(t.stepName,[u],l,async()=>{const h=await Promise.all(t.data.regions.map(g=>this.frameSourceSvg(u,g)));e.updateStorage(t.stepName,{currentFrameSources:h}),await d()})}}else await e.setSelectionsAndElements(t.stepName,[],l,d)}}async availableColors(t,e){var n;const a=t.data.colorOption;return((n=a==null?void 0:a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})))??[]}selectImage(t,e,a,n=!0){var l;const i=De.patternSource(e),s=(l=a.getStepStorage(t.stepName))==null?void 0:l.framePatternSrc;if(s&&s===i)return Promise.resolve();a.setEditedStatus(t.stepName,!0);const o=e.fileLink||"";return o.endsWith(".pdf")||o.endsWith(".eps")||o.endsWith(".ai")?new Promise(c=>{a.addPoller(new Ar(async()=>{var h;const A=(h=(await U.getFromServer(e.key||"")).versions)==null?void 0:h.find(g=>g.name==="svg");return A?(await st(A.link)).status===200:!1},()=>{U.getLocalOrFromServer(e.key||"").then(d=>{this.loadPatternFromAsset(d,t,a,n).then(c)})},()=>{throw new Te("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,n)}async selectVariant(t,e,a,n,i){const s=await this.selectVariantCommand(t,e,a,n,i);s&&(s.command&&n.getCommandDispatcher()(s.command),s.followup&&await s.followup())}getCreateElementCommand(t,e,a,n){return new q({id:t,type:M.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,pattern:n.pattern,immutable:e.immutable},a)}async loadPatternFromString(t,e,a=!0,n=void 0,i){if(t.endsWith("svg")){const s=await ka(t),o=s.width,l=s.height,c=await tt(t);if(i){const u=c.match(/<(image|linearGradient|radialGradient)(\s|>|\/>)/gim);if(u&&u.length>0)throw new Error("Vector files may not include images or gradients when a color limit is specified.")}const d=await ot(c),A={src:t,width:o,height:l,aspect:o/l,svg:d.svg,colors:n??d.colors};dt.set(t,A),e.setPatternData(A,a)}else{const s=await Ne(t,!0),o=await oe(s),l={src:t,width:o.width,height:o.height,aspect:o.width/o.height,svg:void 0,colors:void 0};dt.set(t,l),e.setPatternData(l,a)}}changeColors(t,e,a){var s,o;const n=(s=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:s.frameService;if(!n||!((o=n.getImageData())!=null&&o.svg)){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const i=this.calculateColorMetadata(n,t,a);e.updateMetadata(t.stepName,{colors:i.metadataColors}),e.updateStorage(t.stepName,{colors:i.storageColors}),n.setPatternData({...n.getImageData(),colors:i.newColors},!1),this.validateColorCount(t,e)}getUniqueColorCount(t,e){var s,o;const a=(s=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:s.frameService;if(!a)return 0;const n=((o=a.getImageData())==null?void 0:o.colors)??{},i=[];for(const l in n){const c=n[l];if(c.pmsValue){const d=c.pmsValue.trim().toLocaleLowerCase();i.includes(d)||i.push(d)}else if(c.browserValue){const d=$n(c.browserValue);i.includes(d)||i.push(d)}}return i.length}calculateColorMetadata(t,e,a){var l,c;if(!((l=t.getImageData())!=null&&l.svg))return{newColors:void 0,metadataColors:void 0,storageColors:void 0};const n={...t.getImageData().colors??{}},i={};Object.entries(n).forEach(([d,A])=>{const u={browserValue:A.browserValue};i[d]=u});for(const[d,A]of a.entries())n[d]={browserValue:A.browserValue,pmsValue:A.pmsValue},i[d]=A;let s=Array.from(Object.values(n)).map(d=>d.browserValue);const o=e.data.colorOption;return o&&((c=o.variants)==null||c.forEach(d=>{s=s.map(A=>{var u;return A.toLowerCase()===((u=d.color)==null?void 0:u.toLowerCase())?d.name:A})})),{newColors:n,metadataColors:s,storageColors:i}}validateColorCount(t,e){const a=t.data.colorPickerEnabled?t.data.maxColors??0:0;e.setStepError(t.stepName,"colors",a>0&&this.getUniqueColorCount(t,e)>a?"workflow.steps.frame.tooManyColors":void 0)}async selectVariantCommand(t,e,a,n,i,s){var h;const o=(h=n.getWorkflowExperience().getStepById(t.stepName))==null?void 0:h.frameService;if(!o)throw new Error("Frame service unavailable, cannot load pattern!");const l=await Promise.all(t.data.regions.map(g=>this.frameSourceSvg(e,g)));i&&i(!0);const c=t.data.initialZoomLevel,d=await Promise.all(t.data.regions.map(async(g,m)=>{const p=await Ae(l[m]),f=o.getImageData(),C=a.map(I=>new Ct(I.id)),w=f?Fa(f,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,S=f?{id:Q(),src:f.src,x:(w==null?void 0:w.x)||0,y:(w==null?void 0:w.y)||0,width:f.width,height:f.height,scaleX:(w==null?void 0:w.zoom)||1,scaleY:(w==null?void 0:w.zoom)||1,rotation:0}:void 0,y=Q(),b=n.getLayouts().find(I=>I.panelId===g.panelId);if(!b)throw new Y(g);return{command:this.getCreateElementCommand(y,g,b,{frameData:p,pattern:S,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:y,region:g},removeExistingCommands:C}})),A=d.map(g=>g.command),u=d.map(g=>g.removeExistingCommands).flat();return{command:new $([...A,...u]),followup:async()=>{i&&i(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(g=>g.regionEl)],async()=>{var g;if(n.updateStorage(t.stepName,{currentFrameSources:l}),s){const m=(g=n.getWorkflowExperience().getStepById(t.stepName))==null?void 0:g.frameService;if(!m)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(s,m,!0)}})}}}static patternSource(t){var n;const e=(n=t.versions)==null?void 0:n.find(i=>i.name==="svg");if(e!=null&&e.link)return e.link;const a=t.fileLink;if(a)return a;throw new Nt(t)}async loadPatternFromAsset(t,e,a,n){var c,d;const i=De.patternSource(t),s=a.markUpdatePending(),o=(c=a.getWorkflowExperience().getStepById(e.stepName))==null?void 0:c.frameService;if(!o)throw a.markUpdateCompleted(s),new Error("Frame service unavailable, cannot load pattern!");try{await this.loadPatternFromString(i,o,n,void 0,e.data.colorPickerEnabled&&!!e.data.maxColors&&e.data.maxColors>0)}catch(A){throw a.markUpdateCompleted(s),A}const l=this.calculateColorMetadata(o,e,new Map(Object.entries(((d=o.getImageData())==null?void 0:d.colors)??{})));a.updateMetadata(e.stepName,{image:i,colors:l.metadataColors}),a.updateStorage(e.stepName,{framePatternSrc:i,colors:l.storageColors}),a.markUpdateCompleted(s),a.setMandatoryFulfilled(e.stepName,!0),a.setInformationResults(a.getInformationResults().filter(A=>A.stepID===e.stepName)),this.validateColorCount(e,a)}}const ut=new De;class Eo{async getIllustrationBody(t){return new Promise(e=>{tt(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,n){return new q({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:M.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},a)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return L(a[0].id,e.getAllLayoutData()).colors}catch{return[]}}async init(t,e,a){const n=t.option;if(!n)return null;if(a)return this.reload(t,e,a);{const i=H.getDefaultVariant(n);if(i)return await this.selectVariantCommand(t,i,[],()=>{},e)}return null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{var h;e.updateMetadata(t.stepName,{colors:(h=n.storage)==null?void 0:h.colors}),e.setMandatoryFulfilled(t.stepName,!0)})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){var n;const a=t.data.colorOption;return a?a?(n=a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})):[]:[]}async changeColorsCommand(t,e,a,n,i){const s={};for(const[d,A]of i.entries())typeof A=="string"?s[d]={browserValue:A,spotColor:void 0,pmsValue:void 0}:s[d]={browserValue:A.browserValue,spotColor:A.spotColor,pmsValue:A.pmsValue};const o=ba(t,e,a,s),l=await ne(o),c=[];for(const d of n){for(const[A,u]of i.entries())c.push(new ga(d,A,u));c.push(new fo(d,o,l))}return new $(c)}async changeColors(t,e,a,n,i){var h,g;if(e.length===0)return;const s=L(e[0].id,n().map(m=>m.layoutState)),o={...s.colors},l={};Object.entries(o).forEach(([m,p])=>{const f={browserValue:p.browserValue,pmsValue:p.pmsValue},C=p.spotColor;C&&(f.spotColor={profileName:C.profileName,namedColor:C.namedColor}),l[m]=f});for(const[m,p]of i.entries()){const f=typeof p=="string"?p:p.browserValue,C=typeof p=="string"?void 0:p.pmsValue;o[m]={browserValue:f,spotColor:(h=o[m])==null?void 0:h.spotColor,pmsValue:C},l[m]={browserValue:f}}let c=Array.from(Object.values(o)).map(m=>m.browserValue);const d=t.data.colorOption;d&&((g=d.variants)==null||g.forEach(m=>{c=c.map(p=>{var f;return p.toLowerCase()===((f=m.color)==null?void 0:f.toLowerCase())?m.name:p})})),a.updateMetadata(t.stepName,{colors:c});const A=new Map;if(Object.entries(o).forEach(([m,p])=>{A.set(m,p)}),!s.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const u=await this.changeColorsCommand(s.svg,s.width,s.height,e.map(m=>m.id),A);a.updateStorage(t.stepName,{colors:l}),a.getCommandDispatcher()(u)}async selectVariant(t,e,a,n,i){const s=await this.selectVariantCommand(t,e,a,n,i);s&&(s.command&&i.getCommandDispatcher()(s.command),s.followup&&await s.followup())}async selectVariantCommand(t,e,a,n,i){var f;if(!t.data||!t.data.regions)throw new ee(t,"Missing regions.");n(!0);const s=a.map(C=>new Ct(C.id));t.mandatory&&i.setMandatoryFulfilled(t.stepName,!1);const o=e.asset;if(!o)throw new mt(e);const l=o.fileLink;if(!l)throw new Nt(o);const c=await ot(await this.getIllustrationBody(l)),d=await ne(c.svg),A=C=>{const w=i.getLayouts().find(y=>y.panelId===C.panelId);if(!w)throw new Y(C);const S=Q();return{regionElement:{id:S,region:C},command:this.getCreateElementCommand(S,C,w,{stepName:t.stepName,src:l,objectURL:d,svg:c})}},u=t.data.regions.map(A),g=[...u.map(C=>C.command),...s];let m=Array.from(Object.values(c.colors)).map(C=>C.browserValue);const p=t.data.colorOption;return p&&((f=p.variants)==null||f.forEach(C=>{m=m.map(w=>{var S;return w.toLowerCase()===((S=C.color)==null?void 0:S.toLowerCase())?C.name:w})})),i.updateMetadata(t.stepName,{colors:m}),{command:new $(g),followup:async()=>{var w,S;await i.setSelectionsAndElements(t.stepName,[e],u.map(y=>y.regionElement),async()=>{i.setMandatoryFulfilled(t.stepName,!0),n(!1)});const C=((w=o.assetConfiguration)==null?void 0:w.defaultColorVariants)||[];if(C.length!==0){const y={};(((S=o.assetConfiguration)==null?void 0:S.channelNumbers)||[]).forEach(b=>{var x;const I=C.find(F=>F.channelNumber===b.number);I&&(y[`${b.id.replace(/\W/g,"")}`]={browserValue:((x=I==null?void 0:I.variant)==null?void 0:x.color)||""})}),await this.changeColors(t,u.map(b=>b.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map(Object.entries(y)))}if(t.data.colorPickerEnabled){const y=await this.availableColors(t,i)||[],E=Object.keys(c.colors),b=y.length===1&&E.length===1;if(b){const I=y[0],x=E[0];await this.changeColors(t,u.map(F=>F.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map([[x,I.variant.color]]))}!b&&C.length===0&&await this.changeColors(t,u.map(I=>I.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map)}}}}}const Jt=new Eo;class bo{async init(t,e,a){const n=t.option;if(!n)throw new te(t);if(a)await this.reload(t,e,a);else{const i=H.getDefaultVariant(n);if(i)return await this.selectVariantLambda(t,i,e,()=>{})}return null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(!l)throw new te(t);if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=A.material,h=o.map(g=>({id:g.id,region:g.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],h,async()=>{const g=e.getModelContainer();if(g){const m=t.data.targetMaterials.map(p=>g.applyMaterialVariant(p,l.id||"",u||{}));Promise.all(m).then(()=>e.setMandatoryFulfilled(t.stepName,!0))}})}}}}async selectVariant(t,e,a,n){const i=await this.selectVariantLambda(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a,n){const i=a.getModelContainer();n(!0);const s=e.material;if(!s)throw n(!1),new mt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{i&&t.data.targetMaterials.forEach(o=>{t.option&&i.applyMaterialVariant(o,t.option.id||"",s)}),a.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}})}}}}const Qa=new bo;class Bo{async init(t,e,a){const n=t.option;if(!n)throw new te(t);if(a)await this.reload(t,e,a);else{const i=H.getDefaultVariant(n);if(i)return await this.selectVariantLambda(t,i,e,()=>{})}return null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{var g;const h=e.getModelContainer();if(h&&t.option){const m=(g=A.asset)==null?void 0:g.fileLink;if(!m)throw new mt(A);await h.applyModelVariant(t.stepName||"",{model:m,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}})}}}}async selectVariant(t,e,a,n){const i=await this.selectVariantLambda(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a,n){var s;n(!0);const i=(s=e.asset)==null?void 0:s.fileLink;if(!i)throw new mt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{const o=a.getModelContainer();o&&await o.applyModelVariant(t.stepName,{model:i,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1),a.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}})}}}}const Ra=new Bo;class Io{async init(t,e,a){if(a)await this.reload(t,e,a);else return e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,()=>{});return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{var c,d;e.updateStorage(t.stepName,{text:(c=n==null?void 0:n.storage)==null?void 0:c.text}),e.setMandatoryFulfilled(t.stepName,((d=n==null?void 0:n.storage)==null?void 0:d.text)!=="")})}async changeText(t,e,a,n){const i=await this.changeTextCommand(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async changeTextCommand(t,e,a,n){var d;const i=a.getRegionElements(t.stepName),s=(d=a.getStepSpecificServices(t.stepName))==null?void 0:d.module;if(!s)return console.error("Missing module."),null;const o=a.getProfanities(),l=this.validateInput(t,e,o,n);if(l.errorData)return a.setMandatoryFulfilled(t.stepName,!1),l.errorData.blockedProfanity?console.error("Blocked profanity."):l.errorData.hitCharacterLimit?console.error("Too many characters."):l.errorData.unsupportedCharacters&&console.error("Unsupported characters."),null;if(a.setMandatoryFulfilled(t.stepName,e!==""),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;a.updateStorage(t.stepName,{text:e}),a.updateMetadata(t.stepName,{text:e});const c=(A,u,h)=>{const g=h||Q(),p=a.getLayouts().find(C=>C.panelId===u.panelId);if(!p)return console.error(`Can not find layout for region: ${u.panelId}`),null;const f=[];return h&&f.push(new Ct(g)),f.push(new q({stepRegion:u,stepName:t.stepName,colors:{},id:g,svg:A,type:M.Illustration,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable},p)),{id:g,region:u,command:new $(f)}};if(i.length>0){const u=i.map(h=>{if(!h.region)return null;const g=s.svgPrint(e,h.region);return c(g,h.region,h.id)}).filter(h=>!!h).filter(h=>!!h).map(h=>h&&h.command);return{command:new $(u),followup:async()=>{}}}else{const A=t.data.regions.map(h=>c(s.svgPrint(e,h),h)),u=A.filter(h=>!!h).map(h=>h&&h.command);return{command:new $(u),followup:async()=>{const h=A.filter(g=>g).map(g=>g&&{id:g.id,region:g.region});await a.setSelectionsAndElements(t.stepName,[],h)}}}}validateInput(t,e,a,n){if(t.data&&t.data.maxLength){const s=t.data.maxLength;if(e.length>s)return n("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const i=ra.split(e.toLowerCase());for(const s of i)for(const o in a){const l=a[o].toLowerCase().replace(/\s/g,"");if(s===l)return n("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return n(""),{input:e,helperData:{}}}}const Oa=new Io;class Po{async init(t,e,a){const n=t.option;if(!n)return null;if(a)await this.reload(t,e,a);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,()=>{});return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{e.setMandatoryFulfilled(t.stepName,!0)})}}}}async selectVariant(t,e,a,n){const i=await this.selectVariantCommand(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,a,n){const i=e.asset;if(!i)throw new mt(e);const s=i==null?void 0:i.fileLink;if(!s)return console.error("No URL for picture!"),null;n(!0),t.mandatory&&a.setMandatoryFulfilled(t.stepName,!1);const l=a.getRegionElements(t.stepName).map(A=>new Ct(A.id)),c=A=>{const h=a.getLayouts().find(m=>m.panelId===A.panelId);if(!h)throw new Y(A);const g=Q();return{regionElement:{id:g,region:A},command:new q({stepName:t.stepName,stepRegion:A,id:g,src:s,type:M.Image,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,preserveAspectRatio:"none"},h)}},d=t.data.regions.map(c);return{command:new $([...l,...d.map(A=>A.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(A=>A.regionElement),async()=>{a.setMandatoryFulfilled(t.stepName,!0),n(!1)})}}}}const $a=new Po;class Do{async init(t,e,a){const n=t.option;if(!n)return null;if(a)await this.reload(t,e,a);else{const i=n.variants;if(H.getDefaultVariant(n)){const o=i==null?void 0:i.find(l=>{var c;return l.id===((c=n.defaultVariant)==null?void 0:c.id)});return this.selectVariantLambda(t,(o==null?void 0:o.id)||"",e)}}return null}async reload(t,e,a){var s;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),i=t.option;if(n!=null&&n.selectedVariants){const o=n.selectedVariants[0].id;if(i&&o){const l=(s=i.variants)==null?void 0:s.find(c=>c.id===o);l&&await e.setSelectionsAndElements(t.stepName,[l],[])}}}async selectVariant(t,e,a){await a.getInitializationPromise();const n=await this.selectVariantLambda(t,e,a);n&&(n.command&&a.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,a){const n=t.option;if(!n)return null;const i=n.variants;if(!i)return null;const s=i.length>1?i.find(o=>o.id===e):i[0];if(!s)throw new Error(`Failed to find selected variant ${e} in option ${n.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[s],[],async()=>{a.setMandatoryFulfilled(t.stepName,!0)})}}}}const Ua=new Do;class xo{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){var a;const e=t.option;return e?((a=e.variants)==null?void 0:a.map(n=>({fill:n.color,stroke:n.color,variant:n})))||[]:[]}setCustomColor(t,e,a){const n=a.getLayouts(),s=(a.getRegionElements(e.stepName)||[]).map(o=>{const l=o.region;if(!n.find(d=>d.panelId===(l==null?void 0:l.panelId)))throw new Y(l);return new ga(o.id,this.shapeFillId,t)}).filter(o=>!!o);a.getCommandDispatcher()(new $(s)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const n=t.option;if(!n)throw new te(t);if(a)await this.reload(t,e,a);else{const i=H.getDefaultVariant(n);return i?this.selectVariantCommand(t,{fill:i.color,stroke:i.color,variant:i},[],e):null}return null}async selectVariant(t,e,a,n){const i=await this.selectVariantCommand(t,e,a,n);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{var h;e.updateStorage(t.stepName,{colour:((h=n==null?void 0:n.storage)==null?void 0:h.colour)||""}),e.setMandatoryFulfilled(t.stepName,!0)})}}}}async selectVariantCommand(t,e,a,n){var l;const i=n.getLayouts(),s=(l=n.getStepStorage(t.stepName))==null?void 0:l.colour,o=()=>{var c,d;if(((c=e.variant)==null?void 0:c.color)==="#custom")return s||"#FFFFFF";if((d=e.variant)!=null&&d.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(a.length>0){const c=A=>{const u=A.region;if(!i.find(m=>m.panelId===(u==null?void 0:u.panelId)))throw new Y(u);const g=o();return new ga(A.id,this.shapeFillId,g)},d=a.map(c).filter(A=>!!A);return{command:new $(d),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),n.updateStorage(t.stepName,{colour:o()})}}}else{const c=h=>{const g=i.find(w=>w.panelId===h.panelId);if(!g)throw new Y(h);const m=o(),p=`
1438
+ `,n={};n["spiff-fill-shape"]={browserValue:e.color};const i=e.region||await qt(t,M.Illustration),s=Q();return{stepRegion:e.region,colors:n,id:s,svg:a,type:M.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layer:i.layer||0,layerIndex:i.layerIndex||Gt(t,i.layer||0),immutable:i.immutable}}static async getIllustration(t,e){const a=e.region||await qt(t,M.Illustration,e.src),n=await ot(await rr(e.src)),i=await ne(n.svg),s=Q();return{cachedObjectURL:i,stepRegion:e.region,colors:n.colors,id:s,src:e.src,svg:n.svg,type:M.Illustration,y:a.top,x:a.left,rotation:a.rotation,width:a.width,height:a.height,layer:a.layer||0,layerIndex:a.layerIndex||Gt(t,a.layer||0),immutable:a.immutable}}}class G extends Error{constructor(){super("Element not found!"),Object.setPrototypeOf(this,G.prototype)}}const L=(r,t)=>_(r,t).elements.find(n=>n.id===r),_=(r,t)=>{const e=Object.values(t).find(a=>a.elements.some(n=>n.id===r));if(!e)throw new G;return e},Z=(r,t)=>{const e=[...t.elements.filter(n=>n.id!==r.id),r],a=xa(e);return{layout:t.layout,elements:a,modificationID:Q()}},ir=async r=>{var a;const t=[...Object.keys(r.layouts)],e=[...new Set(t)];for(let n=0;n<e.length;n++){const i=e[n],s=r.layouts[i];await Promise.all(s.elements.map(async o=>{var l,c,d;if(o.type==="illustration"){const A=o;if(A.src&&!A.svg){const u=await tt(A.src),h=await ot(u);A.svg=ba(h.svg,A.width,A.height,A.colors)}}else if(o.type==="frame"){const A=o;if((l=A.pattern)!=null&&l.colors&&((c=A.pattern)!=null&&c.src)){const u=await tt((d=A.pattern)==null?void 0:d.src),h=await ot(u);A.pattern.svg=h.svg}}isNaN(o.x)&&(o.x=0),isNaN(o.y)&&(o.y=0),isNaN(o.width)&&(o.width=0),isNaN(o.height)&&(o.height=0),isNaN(o.rotation)&&(o.rotation=0)}))}for(const n in r.layouts){const i=r.layouts[n].elements.filter(o=>o.type===M.Illustration);for(let o=0;o<i.length;++o){const l=i[o];if(l.src&&l.svg)try{l.cachedObjectURL=await ne(l.svg)}catch(c){console.log(c)}}const s=r.layouts[n].elements.filter(o=>o.type===M.Textbox);for(let o=0;o<s.length;++o){const l=s[o];(a=l.fontData)!=null&&a.assetUrl&&await It(l.fontData.assetUrl)}}};class O{undo(){if(!this.oldState)throw new Error("Cannot undo.");return this.oldState}overrideOldState(t){this.oldState=t}}class sn extends O{constructor(t){super(),this.serializableWorkflow=t}apply(t){return this.oldState=t,{...t,serializableWorkflow:this.serializableWorkflow}}}class Ao extends O{constructor(t,e,a){super(),this.id=t,this.x=e,this.y=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,x:this.x,y:this.y},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class uo extends O{constructor(t,e){super(),this.id=t,this.angle=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,rotation:this.angle},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class ho extends O{constructor(t,e,a){super(),this.id=t,this.width=Math.abs(e),this.height=Math.abs(a)}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;let a={...e,width:this.width,height:this.height};if(e.type==="frame"){const s=a;s.scaleX=s.scaleX*this.width/e.width,s.scaleY=s.scaleY*this.height/e.height}else if(e.type==="textbox"){const s=a,o=(!s.algorithm||s.algorithm===Bt.Autosize?s.text:s.input)??"";a=ce(s,o,e)}const n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class $ extends O{constructor(t){super(),this.commands=t}apply(t){return this.oldState=t,this.commands.reduce((e,a)=>a.apply(e),t)}}class Ta extends O{constructor(t){super(),this.layout=t}apply(t){return this.oldState=t,{...t,layouts:{...t.layouts,[this.layout.id]:{elements:[],layout:{...this.layout},modificationID:Q()}}}}}class q extends O{constructor(t,e){super(),this.element=t,this.layout=e}apply(t){this.oldState=t,t.layouts[this.layout.id]||(t.layouts[this.layout.id]={layout:this.layout,elements:[],modificationID:""});const e=t.layouts[this.layout.id].elements;if(e.find(o=>o.id===this.element.id))throw new Error(`Failed to apply new ${this.element.type} element because ID ${this.element.id} already taken`);if(this.element.productOverlay||e.length===0){const o=[...e,this.element];return this.element.layerIndex===void 0&&(this.element.layerIndex=this.assignIndex(this.element,o)),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:o,modificationID:Q()}}}}const n=e[e.length-1],i=n.productOverlay?n:null;i&&e.pop();let s;if(this.element.layerIndex!==null&&this.element.layerIndex!==void 0)s=[...e,this.element].sort((o,l)=>o.layerIndex!==void 0&&l.layerIndex!==void 0?o.layerIndex-l.layerIndex:0);else{const o=this.assignIndex(this.element,e);this.element.layerIndex=o!==void 0?o:0,s=[...e,this.element]}return i&&s.push(i),{...t,layouts:{...t.layouts,[this.layout.id]:{...t.layouts[this.layout.id],elements:s,modificationID:Q()}}}}assignIndex(t,e){var n;if(e.length===0)return 0;const a=(n=e.filter(i=>(i.layer||0)===(t.layer||0)).sort((i,s)=>(i.layerIndex||0)-(s.layerIndex||0))[e.length-1])==null?void 0:n.layerIndex;return a!==void 0?a+1:0}}class Ct extends O{constructor(t){super(),this.id=t}apply(t){this.oldState=t;let e=!1;const a=Object.values(t.layouts).map(i=>(i.elements.filter(o=>o.id!==this.id).length!==i.elements.length&&(e=!0),{...i,elements:i.elements.filter(o=>o.id!==this.id),modificationID:Q()}));e||console.log(`Failed to delete element ${this.id}`);const n={};return a.forEach(i=>{n[i.layout.id]=i}),{...t,layouts:n}}}class sr extends O{constructor(t,e,a){super(),this.id=t,this.color=e,this.textFillSpotColor=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,fill:this.color,fillSpotColorDefinition:this.textFillSpotColor,textFillImage:void 0},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class Ke extends O{constructor(t,e){super(),this.id=t,this.imageFill=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,textFillImage:this.imageFill},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class or extends O{constructor(t,e){super(),this.id=t,this.size=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,fontSize:this.size},n=_(e.id,Object.values(t.layouts)),i=(!e.algorithm||e.algorithm===Bt.Autosize?e.text:e.input)??"",s=Z(ce(a,i),n);return{...t,layouts:{...t.layouts,[n.layout.id]:s}}}}class ha extends O{constructor(t,e){super(),this.id=t,this.fontData=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,fontData:this.fontData},n=_(e.id,Object.values(t.layouts)),i=(!e.algorithm||e.algorithm===Bt.Autosize?e.text:e.input)??"",s=Z(ce(a,i),n);return{...t,layouts:{...t.layouts,[n.layout.id]:s}}}}class lr extends O{constructor(t,e){super(),this.id=t,this.align=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,align:this.align},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class go extends O{constructor(t,e,a){super(),this.id=t,this.imageData=e,this.offsets=a}apply(t){this.oldState=t;const e=_(this.id,Object.values(t.layouts)),a=e.elements.findIndex(o=>o.id===this.id),n=e.elements[a].pattern,i=[...e.elements];i.splice(a,1,{...e.elements[a],pattern:{...n,src:this.imageData.src,x:this.offsets.x,y:this.offsets.y,width:this.imageData.width,height:this.imageData.height,scaleX:this.offsets.zoom,scaleY:this.offsets.zoom,svg:this.imageData.svg,colors:this.imageData.colors}});const s={...e,elements:i,modificationID:Q()};return{...t,layouts:{...t.layouts,[e.layout.id]:s}}}}class mo extends O{constructor(t,e,a,n,i){super(),this.id=t,this.useThreshold=e,this.invertThreshold=a,this.threshold=n,this.thresholdSaturation=i}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,useThreshold:this.useThreshold,invertThreshold:this.invertThreshold,threshold:this.threshold,thresholdSaturation:this.thresholdSaturation},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class po extends O{constructor(t,e){super(),this.id=t,this.src=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,src:this.src},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class cr extends O{constructor(t,e){super(),this.id=t,this.text=e}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a=_(e.id,Object.values(t.layouts)),n=Z(ce(e,this.text,e),a);return{...t,layouts:{...t.layouts,[a.layout.id]:n}}}}class _e extends O{constructor(t,e,a){super(),this.id=t,this.strokeColor=e,this.strokeThickness=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,strokeColor:this.strokeColor,strokeThickness:this.strokeThickness},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class ga extends O{constructor(t,e,a){super(),this.id=t,this.className=e,this.fill=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a=e.colors||{},n=a[this.className];typeof this.fill=="string"?a[this.className]={browserValue:this.fill,spotColor:n==null?void 0:n.spotColor,pmsValue:n==null?void 0:n.pmsValue}:a[this.className]={browserValue:this.fill.browserValue,spotColor:n==null?void 0:n.spotColor,pmsValue:this.fill.pmsValue};const i={...e,colors:a},s=_(e.id,Object.values(t.layouts)),o=Z(i,s);return{...t,layouts:{...t.layouts,[s.layout.id]:o}}}}class fo extends O{constructor(t,e,a){super(),this.id=t,this.svgBody=e,this.objectURL=a}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a={...e,svg:this.svgBody,cachedObjectURL:this.objectURL},n=_(e.id,Object.values(t.layouts)),i=Z(a,n);return{...t,layouts:{...t.layouts,[n.layout.id]:i}}}}class Co extends O{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!L(this.id,Object.values(t.layouts)).id)throw new G;const a=Object.values(t.layouts).find(s=>s.elements.find(o=>o.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(s=>s.id===this.id);a.elements.push(a.elements.splice(n,1)[0]);const i=[...a.elements];return i.forEach((s,o)=>s.layerIndex=o),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:i,modificationID:Q()}}}}}class wo extends O{constructor(t){super(),this.id=t}apply(t){this.oldState=t;const e=L(this.id,Object.values(t.layouts));if(!e.id)throw new G;const a=Object.values(t.layouts).find(o=>o.elements.find(l=>l.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(o=>o.id===this.id);a.elements.splice(n,1),a.elements.unshift(e);const i=[...a.elements],s=i.splice(n,1)[0];return i.splice(n,0,s),i.forEach((o,l)=>o.layerIndex=l),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:i,modificationID:Q()}}}}}class yo extends O{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!L(this.id,Object.values(t.layouts)).id)throw new G;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),i=n+1,s=[...a.elements],o=s.splice(n,1)[0];return s.splice(i,0,o),s.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:s,modificationID:Q()}}}}}class So extends O{constructor(t){super(),this.id=t}apply(t){if(this.oldState=t,!L(this.id,Object.values(t.layouts)).id)throw new G;const a=Object.values(t.layouts).find(l=>l.elements.find(c=>c.id===this.id));if(!a)throw new Error("Layout missing from state!");const n=a.elements.findIndex(l=>l.id===this.id),i=n-1,s=[...a.elements],o=s.splice(n,1)[0];return s.splice(i,0,o),s.forEach((l,c)=>l.layerIndex=c),{...t,layouts:{...t.layouts,[a.layout.id]:{...t.layouts[a.layout.id],elements:s,modificationID:Q()}}}}}class on{constructor(t,e,a){this.processRegion=async n=>{var l,c,d,A;const i=this.layouts.find(u=>u.panelId===n.panelId);if(!i)throw new Y(n);let s="";if(this.configuration.type===P.ProductOverlay){let u="";if((l=this.product)!=null&&l.overlayImageUrl&&(u=this.product.overlayImageUrl),s=u,!u)throw new ee(this.configuration,"Couldn't find an asset for product overlay step")}const o=this.evaluateAssetType();if(o===M.Image){const u=this.configuration.type===P.SilentIllustration?(c=this.configuration.data.asset)==null?void 0:c.fileLink:(d=this.product)==null?void 0:d.overlayImageUrl;if(!u)throw new Error("Undefined raster silent step source");const h={stepName:this.configuration.stepName,id:Q(),src:u,type:o,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable,productOverlay:this.configuration.type===P.ProductOverlay?!0:void 0,rotation:n.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:h.id,region:n},command:new q(h,i)}}else{const u=this.configuration.type===P.SilentIllustration?(A=this.configuration.data.asset)==null?void 0:A.fileLink:s,g=await ot(await(async()=>new Promise((p,f)=>{if(!u){f("Undefined vector silent step source");return}tt(u,!0).then(C=>{p(C)}).catch(C=>console.error(C))}))()),m={stepName:this.configuration.stepName,id:Q(),cachedObjectURL:await ne(g.svg),src:u,svg:g.svg,colors:g.colors,type:o,y:n.top,x:n.left,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,rotation:n.rotation,immutable:n.immutable,productOverlay:this.configuration.type===P.ProductOverlay?!0:void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:m.id,region:n},command:new q(m,i)}}},this.configuration=t,this.layouts=e,this.product=a||void 0}async trigger(){if(!this.configuration.data.regions)throw new ee(this.configuration,"Missing regions.");if(this.configuration.type===P.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}else return this.configuration.type===P.ProductOverlay?Promise.all(this.configuration.data.regions.map(t=>{if(!this.layouts.find(a=>t.panelId===a.panelId))throw new Y(t);return this.processRegion(t)})):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){var e,a,n;const t=this.configuration.type===P.ProductOverlay&&((e=this.product)!=null&&e.overlayImageUrl)?this.product.overlayImageUrl.toLowerCase():(n=(a=this.configuration.data.asset)==null?void 0:a.fileLink)==null?void 0:n.toLowerCase().split("?")[0];return t!=null&&t.startsWith("data:image/png")||t!=null&&t.endsWith(".jpeg")||t!=null&&t.endsWith(".jpg")||t!=null&&t.endsWith(".png")?M.Image:(t!=null&&t.endsWith(".svg")||t!=null&&t.startsWith("image/svg+xml"),M.Illustration)}}const dr=async r=>{const t=`${At.getServicesApiUrl()}/shortener`;try{return(await(await st(t,{method:"POST",body:JSON.stringify({longUrl:r}),headers:{"Content-Type":"application/json"}})).json()).shortUrl}catch(e){throw console.error(e),new Te("Failed to shorten URL, see console.")}};class Ar{async poll(){try{if(await this.predicate()){this.onSuccess(),this.pollingId>-1&&window.clearInterval(this.pollingId);return}}catch{}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,a,n=3e3,i=10){this.onSuccess=e,this.onFailure=a,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=i,this.poll()}}class vo{async init(t,e,a){return a&&await this.reload(t,e,a),null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{var A,u;const c=(A=n==null?void 0:n.storage)==null?void 0:A.videoShortUrl,d=(u=n==null?void 0:n.storage)==null?void 0:u.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:c,videoUrl:d})})}async regenerateQRCode(t,e,a,n){const i=async()=>{var m,p;const h=(await Be([e]))[0],g=(p=(m=h==null?void 0:h.versions)==null?void 0:m.find(f=>f.name==="mpeg4"))==null?void 0:p.link;return{asset:h,link:g}},s=await new Promise((h,g)=>{new Ar(async()=>!!(await i()).link,async()=>{const m=await i();if(!m.link||!m.link)throw new Nt(m.asset);h({rel:"mpeg4",href:m.link})},()=>{g("Poller timed out with 40 attempts @ 3 second interval")},3e3,40)});t.forEach(h=>a.getCommandDispatcher()(new Ct(h.id)));const o=n.data.baseUrl.slice(0,4)==="http"?"":"https://",l=new URL(o+n.data.baseUrl);l.searchParams.append("video",btoa(JSON.stringify([s]))),l.pathname=l.pathname+(l.pathname.slice(-1)==="/"?"":"/");const c=l.toString();if(c.length>=2e3)throw new Te("Cannot create QR code, URL too long.");const d=await dr(c);if(!n.data||!n.data.regions)throw new ee(n,"Missing regions.");const A=await this.regionElements(n),u=await this.command(d,A,a,n.stepName);return u&&(u.command&&a.getCommandDispatcher()(u.command),u.followup&&await u.followup()),await a.setSelectionsAndElements(n.stepName,[],A,async()=>{a.updateStorage(n.stepName,{videoShortUrl:d,videoUrl:s.href})}),d}async regionElements(t){const e=a=>({id:Q(),region:a});return t.data.regions.map(e)}async command(t,e,a,n){const i=a.getLayouts(),o=`data:image/svg+xml;base64,${btoa(await yn.toString(t,{type:"svg"}))}`,l=e.map(c=>{const d=c.region,A=i.find(u=>u.panelId===(d==null?void 0:d.panelId));if(!A&&d)throw new Y(d);if(A&&!d)throw new Error("Region not found");if(!A||!d)throw new Error("Neither a region or layout found!");return new q({stepRegion:d,stepName:n,id:c.id,src:o,type:M.Image,y:d.top,x:d.left,width:d.width,height:d.height,rotation:0},A)});return{command:new $(l),followup:async()=>{}}}}const Na=new vo;class De{constructor(){this.frameSourceSvg=async(t,e)=>{if(!t)return Aa(e);const a=t.asset;if(!a)throw new mt(t);const n=a.fileLink;if(n)return tt(n,!0);throw new Nt(a)}}async init(t,e,a){const n=a==null?void 0:a.serializableWorkflow.steps.find(o=>o.stepName===t.stepName);if(n!=null&&n.storage&&Object.keys(n.storage).length!==0||n!=null&&n.selectedVariants&&n.selectedVariants.length!==0)return await this.reload(t,e,a),null;t.mandatory&&e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]);let i;const s=e.getWorkflowExperience().getBundle();if(s&&t.globalPropertyAspectConfigurations){const o=s.getGlobalPropertyStateManager(),l=t.globalPropertyAspectConfigurations[0],c=o.getAspectStorage(l.aspectName);c&&c.originalAssetKey&&(i=(await U.getLocalOrFromServer(c.originalAssetKey)).fileLink)}if(t.option&&t.option.variants&&t.option.variants.length>0){const o=t.option,l=H.getDefaultVariant(o);return l?this.selectVariantCommand(t,l,[],e,void 0,i||t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,i||t.data.placeholderImageUrl)}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName).map(d=>({id:d.id,region:d.stepRegion}));if(!t.option||(t.option.variants||[]).length===0){const d=t.data.regions.map(A=>Aa(A));e.updateStorage(t.stepName,{currentFrameSources:d})}if(n){const d=async()=>{var g,m,p,f,C;const A=(g=n.storage)==null?void 0:g.colors,u=(m=n.storage)==null?void 0:m.framePatternSrc,h=(p=n.storage)==null?void 0:p.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:h,framePatternSrc:u}),u){const w=(f=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:f.frameService;if(!w)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(u,w,!0,A),e.updateMetadata(t.stepName,{image:u}),e.updateStorage(t.stepName,{framePatternSrc:u}),this.validateColorCount(t,e)}if(h!=null&&h.some(w=>w.zoom)){const w=(C=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:C.frameService;if(!w)throw new Error("Frame service unavailable, cannot load pattern!");w.updateOffsets(h)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const A=n.selectedVariants[0].id;if(t.option&&A){const u=(c=t.option.variants)==null?void 0:c.find(h=>h.id===A);u&&await e.setSelectionsAndElements(t.stepName,[u],l,async()=>{const h=await Promise.all(t.data.regions.map(g=>this.frameSourceSvg(u,g)));e.updateStorage(t.stepName,{currentFrameSources:h}),await d()})}}else await e.setSelectionsAndElements(t.stepName,[],l,d)}}async availableColors(t,e){var n;const a=t.data.colorOption;return((n=a==null?void 0:a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})))??[]}selectImage(t,e,a,n=!0){var l;const i=De.patternSource(e),s=(l=a.getStepStorage(t.stepName))==null?void 0:l.framePatternSrc;if(s&&s===i)return Promise.resolve();a.setEditedStatus(t.stepName,!0);const o=e.fileLink||"";return o.endsWith(".pdf")||o.endsWith(".eps")||o.endsWith(".ai")?new Promise(c=>{a.addPoller(new Ar(async()=>{var h;const A=(h=(await U.getFromServer(e.key||"")).versions)==null?void 0:h.find(g=>g.name==="svg");return A?(await st(A.link)).status===200:!1},()=>{U.getLocalOrFromServer(e.key||"").then(d=>{this.loadPatternFromAsset(d,t,a,n).then(c)})},()=>{throw new Te("Failed to resolve transcoded PDF")}))}):this.loadPatternFromAsset(e,t,a,n)}async selectVariant(t,e,a,n,i){const s=await this.selectVariantCommand(t,e,a,n,i);s&&(s.command&&n.getCommandDispatcher()(s.command),s.followup&&await s.followup())}getCreateElementCommand(t,e,a,n){return new q({id:t,type:M.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,pattern:n.pattern,immutable:e.immutable},a)}async loadPatternFromString(t,e,a=!0,n=void 0,i){if(t.endsWith("svg")){const s=await ka(t),o=s.width,l=s.height,c=await tt(t);if(i){const u=c.match(/<(image|linearGradient|radialGradient)(\s|>|\/>)/gim);if(u&&u.length>0)throw new Error("Vector files may not include images or gradients when a color limit is specified.")}const d=await ot(c),A={src:t,width:o,height:l,aspect:o/l,svg:d.svg,colors:n??d.colors};dt.set(t,A),e.setPatternData(A,a)}else{const s=await Ne(t,!0),o=await oe(s),l={src:t,width:o.width,height:o.height,aspect:o.width/o.height,svg:void 0,colors:void 0};dt.set(t,l),e.setPatternData(l,a)}}changeColors(t,e,a){var s,o;const n=(s=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:s.frameService;if(!n||!((o=n.getImageData())!=null&&o.svg)){console.warn("changeColors was called without an SVG being assigned to a frame step");return}const i=this.calculateColorMetadata(n,t,a);e.updateMetadata(t.stepName,{colors:i.metadataColors}),e.updateStorage(t.stepName,{colors:i.storageColors}),n.setPatternData({...n.getImageData(),colors:i.newColors},!1),this.validateColorCount(t,e)}getUniqueColorCount(t,e){var s,o;const a=(s=e.getWorkflowExperience().getStepById(t.stepName))==null?void 0:s.frameService;if(!a)return 0;const n=((o=a.getImageData())==null?void 0:o.colors)??{},i=[];for(const l in n){const c=n[l];if(c.pmsValue){const d=c.pmsValue.trim().toLocaleLowerCase();i.includes(d)||i.push(d)}else if(c.browserValue){const d=$n(c.browserValue);i.includes(d)||i.push(d)}}return i.length}calculateColorMetadata(t,e,a){var l,c;if(!((l=t.getImageData())!=null&&l.svg))return{newColors:void 0,metadataColors:void 0,storageColors:void 0};const n={...t.getImageData().colors??{}},i={};Object.entries(n).forEach(([d,A])=>{const u={browserValue:A.browserValue};i[d]=u});for(const[d,A]of a.entries())n[d]={browserValue:A.browserValue,pmsValue:A.pmsValue},i[d]=A;let s=Array.from(Object.values(n)).map(d=>d.browserValue);const o=e.data.colorOption;return o&&((c=o.variants)==null||c.forEach(d=>{s=s.map(A=>{var u;return A.toLowerCase()===((u=d.color)==null?void 0:u.toLowerCase())?d.name:A})})),{newColors:n,metadataColors:s,storageColors:i}}validateColorCount(t,e){const a=t.data.colorPickerEnabled?t.data.maxColors??0:0;e.setStepError(t.stepName,"colors",a>0&&this.getUniqueColorCount(t,e)>a?"workflow.steps.frame.tooManyColors":void 0)}async selectVariantCommand(t,e,a,n,i,s){var h;const o=(h=n.getWorkflowExperience().getStepById(t.stepName))==null?void 0:h.frameService;if(!o)throw new Error("Frame service unavailable, cannot load pattern!");const l=await Promise.all(t.data.regions.map(g=>this.frameSourceSvg(e,g)));i&&i(!0);const c=t.data.initialZoomLevel,d=await Promise.all(t.data.regions.map(async(g,m)=>{const p=await Ae(l[m]),f=o.getImageData(),C=a.map(I=>new Ct(I.id)),w=f?Fa(f,p,c&&!t.data.forceImageCover?{scale:c}:void 0,t.data.forceImageCover):void 0,S=f?{id:Q(),src:f.src,x:(w==null?void 0:w.x)||0,y:(w==null?void 0:w.y)||0,width:f.width,height:f.height,scaleX:(w==null?void 0:w.zoom)||1,scaleY:(w==null?void 0:w.zoom)||1,rotation:0}:void 0,y=Q(),b=n.getLayouts().find(I=>I.panelId===g.panelId);if(!b)throw new Y(g);return{command:this.getCreateElementCommand(y,g,b,{frameData:p,pattern:S,disablePlaceholder:t.data.disablePlaceholder,stepName:t.stepName}),regionEl:{id:y,region:g},removeExistingCommands:C}})),A=d.map(g=>g.command),u=d.map(g=>g.removeExistingCommands).flat();return{command:new $([...A,...u]),followup:async()=>{i&&i(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...d.map(g=>g.regionEl)],async()=>{var g;if(n.updateStorage(t.stepName,{currentFrameSources:l}),s){const m=(g=n.getWorkflowExperience().getStepById(t.stepName))==null?void 0:g.frameService;if(!m)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(s,m,!0)}})}}}static patternSource(t){var n;const e=(n=t.versions)==null?void 0:n.find(i=>i.name==="svg");if(e!=null&&e.link)return e.link;const a=t.fileLink;if(a)return a;throw new Nt(t)}async loadPatternFromAsset(t,e,a,n){var c,d;const i=De.patternSource(t),s=a.markUpdatePending(),o=(c=a.getWorkflowExperience().getStepById(e.stepName))==null?void 0:c.frameService;if(!o)throw a.markUpdateCompleted(s),new Error("Frame service unavailable, cannot load pattern!");try{await this.loadPatternFromString(i,o,n,void 0,e.data.colorPickerEnabled&&!!e.data.maxColors&&e.data.maxColors>0)}catch(A){throw a.markUpdateCompleted(s),A}const l=this.calculateColorMetadata(o,e,new Map(Object.entries(((d=o.getImageData())==null?void 0:d.colors)??{})));a.updateMetadata(e.stepName,{image:i,colors:l.metadataColors}),a.updateStorage(e.stepName,{framePatternSrc:i,colors:l.storageColors}),a.markUpdateCompleted(s),a.setMandatoryFulfilled(e.stepName,!0),a.setInformationResults(a.getInformationResults().filter(A=>A.stepID===e.stepName)),this.validateColorCount(e,a)}}const ut=new De;class Eo{async getIllustrationBody(t){return new Promise(e=>{tt(t,!0).then(a=>{e(a)}).catch(a=>console.error(a))})}getCreateElementCommand(t,e,a,n){return new q({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:M.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},a)}getColors(t,e){const a=e.getRegionElements(t.stepName)||[];if(a.length===0)return[];try{return L(a[0].id,e.getAllLayoutData()).colors}catch{return[]}}async init(t,e,a){const n=t.option;if(!n)return null;if(a)return this.reload(t,e,a);{const i=H.getDefaultVariant(n);if(i)return await this.selectVariantCommand(t,i,[],()=>{},e)}return null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{var h;e.updateMetadata(t.stepName,{colors:(h=n.storage)==null?void 0:h.colors}),e.setMandatoryFulfilled(t.stepName,!0)})}}else throw new Error("Required illustration variant no longer available")}return null}async availableColors(t,e){var n;const a=t.data.colorOption;return a?a?(n=a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})):[]:[]}async changeColorsCommand(t,e,a,n,i){const s={};for(const[d,A]of i.entries())typeof A=="string"?s[d]={browserValue:A,spotColor:void 0,pmsValue:void 0}:s[d]={browserValue:A.browserValue,spotColor:A.spotColor,pmsValue:A.pmsValue};const o=ba(t,e,a,s),l=await ne(o),c=[];for(const d of n){for(const[A,u]of i.entries())c.push(new ga(d,A,u));c.push(new fo(d,o,l))}return new $(c)}async changeColors(t,e,a,n,i){var h,g;if(e.length===0)return;const s=L(e[0].id,n().map(m=>m.layoutState)),o={...s.colors},l={};Object.entries(o).forEach(([m,p])=>{const f={browserValue:p.browserValue,pmsValue:p.pmsValue},C=p.spotColor;C&&(f.spotColor={profileName:C.profileName,namedColor:C.namedColor}),l[m]=f});for(const[m,p]of i.entries()){const f=typeof p=="string"?p:p.browserValue,C=typeof p=="string"?void 0:p.pmsValue;o[m]={browserValue:f,spotColor:(h=o[m])==null?void 0:h.spotColor,pmsValue:C},l[m]={browserValue:f}}let c=Array.from(Object.values(o)).map(m=>m.browserValue);const d=t.data.colorOption;d&&((g=d.variants)==null||g.forEach(m=>{c=c.map(p=>{var f;return p.toLowerCase()===((f=m.color)==null?void 0:f.toLowerCase())?m.name:p})})),a.updateMetadata(t.stepName,{colors:c});const A=new Map;if(Object.entries(o).forEach(([m,p])=>{A.set(m,p)}),!s.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const u=await this.changeColorsCommand(s.svg,s.width,s.height,e.map(m=>m.id),A);a.updateStorage(t.stepName,{colors:l}),a.getCommandDispatcher()(u)}async selectVariant(t,e,a,n,i){const s=await this.selectVariantCommand(t,e,a,n,i);s&&(s.command&&i.getCommandDispatcher()(s.command),s.followup&&await s.followup())}async selectVariantCommand(t,e,a,n,i){var f;if(!t.data||!t.data.regions)throw new ee(t,"Missing regions.");n(!0);const s=a.map(C=>new Ct(C.id));t.mandatory&&i.setMandatoryFulfilled(t.stepName,!1);const o=e.asset;if(!o)throw new mt(e);const l=o.fileLink;if(!l)throw new Nt(o);const c=await ot(await this.getIllustrationBody(l)),d=await ne(c.svg),A=C=>{const w=i.getLayouts().find(y=>y.panelId===C.panelId);if(!w)throw new Y(C);const S=Q();return{regionElement:{id:S,region:C},command:this.getCreateElementCommand(S,C,w,{stepName:t.stepName,src:l,objectURL:d,svg:c})}},u=t.data.regions.map(A),g=[...u.map(C=>C.command),...s];let m=Array.from(Object.values(c.colors)).map(C=>C.browserValue);const p=t.data.colorOption;return p&&((f=p.variants)==null||f.forEach(C=>{m=m.map(w=>{var S;return w.toLowerCase()===((S=C.color)==null?void 0:S.toLowerCase())?C.name:w})})),i.updateMetadata(t.stepName,{colors:m}),{command:new $(g),followup:async()=>{var w,S;await i.setSelectionsAndElements(t.stepName,[e],u.map(y=>y.regionElement),async()=>{i.setMandatoryFulfilled(t.stepName,!0),n(!1)});const C=((w=o.assetConfiguration)==null?void 0:w.defaultColorVariants)||[];if(C.length!==0){const y={};(((S=o.assetConfiguration)==null?void 0:S.channelNumbers)||[]).forEach(b=>{var x;const I=C.find(F=>F.channelNumber===b.number);I&&(y[`${b.id.replace(/\W/g,"")}`]={browserValue:((x=I==null?void 0:I.variant)==null?void 0:x.color)||""})}),await this.changeColors(t,u.map(b=>b.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map(Object.entries(y)))}if(t.data.colorPickerEnabled){const y=await this.availableColors(t,i)||[],E=Object.keys(c.colors),b=y.length===1&&E.length===1;if(b){const I=y[0],x=E[0];await this.changeColors(t,u.map(F=>F.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map([[x,I.variant.color]]))}!b&&C.length===0&&await this.changeColors(t,u.map(I=>I.regionElement),i,()=>i.getCommandContext().getAllLayouts(),new Map)}}}}}const Jt=new Eo;class bo{async init(t,e,a){const n=t.option;if(!n)throw new te(t);if(a)await this.reload(t,e,a);else{const i=H.getDefaultVariant(n);if(i)return await this.selectVariantLambda(t,i,e,()=>{})}return null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(!l)throw new te(t);if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=A.material,h=o.map(g=>({id:g.id,region:g.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],h,async()=>{const g=e.getModelContainer();if(g){const m=t.data.targetMaterials.map(p=>g.applyMaterialVariant(p,l.id||"",u||{}));Promise.all(m).then(()=>e.setMandatoryFulfilled(t.stepName,!0))}})}}}}async selectVariant(t,e,a,n){const i=await this.selectVariantLambda(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a,n){const i=a.getModelContainer();n(!0);const s=e.material;if(!s)throw n(!1),new mt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{i&&t.data.targetMaterials.forEach(o=>{t.option&&i.applyMaterialVariant(o,t.option.id||"",s)}),a.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}})}}}}const Qa=new bo;class Bo{async init(t,e,a){const n=t.option;if(!n)throw new te(t);if(a)await this.reload(t,e,a);else{const i=H.getDefaultVariant(n);if(i)return await this.selectVariantLambda(t,i,e,()=>{})}return null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{var g;const h=e.getModelContainer();if(h&&t.option){const m=(g=A.asset)==null?void 0:g.fileLink;if(!m)throw new mt(A);await h.applyModelVariant(t.stepName||"",{model:m,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}})}}}}async selectVariant(t,e,a,n){const i=await this.selectVariantLambda(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,a,n){var s;n(!0);const i=(s=e.asset)==null?void 0:s.fileLink;if(!i)throw new mt(e);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],[],async()=>{try{const o=a.getModelContainer();o&&await o.applyModelVariant(t.stepName,{model:i,contextService:a.getLayoutPreviewService()},t.data.replaceProductModel||!1),a.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}})}}}}const Ra=new Bo;class Io{async init(t,e,a){if(a)await this.reload(t,e,a);else return e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,()=>{});return null}async reload(t,e,a){const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),l=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName).map(c=>({id:c.id,region:c.stepRegion}));await e.setSelectionsAndElements(t.stepName,[],l,async()=>{var c,d;e.updateStorage(t.stepName,{text:(c=n==null?void 0:n.storage)==null?void 0:c.text}),e.setMandatoryFulfilled(t.stepName,((d=n==null?void 0:n.storage)==null?void 0:d.text)!=="")})}async changeText(t,e,a,n){const i=await this.changeTextCommand(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async changeTextCommand(t,e,a,n){var d;const i=a.getRegionElements(t.stepName),s=(d=a.getStepSpecificServices(t.stepName))==null?void 0:d.module;if(!s)return console.error("Missing module."),null;const o=a.getProfanities(),l=this.validateInput(t,e,o,n);if(l.errorData)return a.setMandatoryFulfilled(t.stepName,!1),l.errorData.blockedProfanity?console.error("Blocked profanity."):l.errorData.hitCharacterLimit?console.error("Too many characters."):l.errorData.unsupportedCharacters&&console.error("Unsupported characters."),null;if(a.setMandatoryFulfilled(t.stepName,e!==""),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;a.updateStorage(t.stepName,{text:e}),a.updateMetadata(t.stepName,{text:e});const c=(A,u,h)=>{const g=h||Q(),p=a.getLayouts().find(C=>C.panelId===u.panelId);if(!p)return console.error(`Can not find layout for region: ${u.panelId}`),null;const f=[];return h&&f.push(new Ct(g)),f.push(new q({stepRegion:u,stepName:t.stepName,colors:{},id:g,svg:A,type:M.Illustration,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable},p)),{id:g,region:u,command:new $(f)}};if(i.length>0){const u=i.map(h=>{if(!h.region)return null;const g=s.svgPrint(e,h.region);return c(g,h.region,h.id)}).filter(h=>!!h).filter(h=>!!h).map(h=>h&&h.command);return{command:new $(u),followup:async()=>{}}}else{const A=t.data.regions.map(h=>c(s.svgPrint(e,h),h)),u=A.filter(h=>!!h).map(h=>h&&h.command);return{command:new $(u),followup:async()=>{const h=A.filter(g=>g).map(g=>g&&{id:g.id,region:g.region});await a.setSelectionsAndElements(t.stepName,[],h)}}}}validateInput(t,e,a,n){if(t.data&&t.data.maxLength){const s=t.data.maxLength;if(e.length>s)return n("Too many characters."),{input:e,helperData:{},errorData:{hitCharacterLimit:!0}}}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),{input:e,helperData:{},errorData:{unsupportedCharacters:!0}};const i=ra.split(e.toLowerCase());for(const s of i)for(const o in a){const l=a[o].toLowerCase().replace(/\s/g,"");if(s===l)return n("Blocked profanity."),{input:e,helperData:{},errorData:{blockedProfanity:!0}}}return n(""),{input:e,helperData:{}}}}const Oa=new Io;class Po{async init(t,e,a){const n=t.option;if(!n)return null;if(a)await this.reload(t,e,a);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,()=>{});return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{e.setMandatoryFulfilled(t.stepName,!0)})}}}}async selectVariant(t,e,a,n){const i=await this.selectVariantCommand(t,e,a,n);i&&(i.command&&a.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,a,n){const i=e.asset;if(!i)throw new mt(e);const s=i==null?void 0:i.fileLink;if(!s)return console.error("No URL for picture!"),null;n(!0),t.mandatory&&a.setMandatoryFulfilled(t.stepName,!1);const l=a.getRegionElements(t.stepName).map(A=>new Ct(A.id)),c=A=>{const h=a.getLayouts().find(m=>m.panelId===A.panelId);if(!h)throw new Y(A);const g=Q();return{regionElement:{id:g,region:A},command:new q({stepName:t.stepName,stepRegion:A,id:g,src:s,type:M.Image,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,preserveAspectRatio:"none"},h)}},d=t.data.regions.map(c);return{command:new $([...l,...d.map(A=>A.command)]),followup:async()=>{await a.setSelectionsAndElements(t.stepName,[e],d.map(A=>A.regionElement),async()=>{a.setMandatoryFulfilled(t.stepName,!0),n(!1)})}}}}const $a=new Po;class Do{async init(t,e,a){const n=t.option;if(!n)return null;if(a)await this.reload(t,e,a);else{const i=n.variants;if(H.getDefaultVariant(n)){const o=i==null?void 0:i.find(l=>{var c;return l.id===((c=n.defaultVariant)==null?void 0:c.id)});return this.selectVariantLambda(t,(o==null?void 0:o.id)||"",e)}}return null}async reload(t,e,a){var s;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),i=t.option;if(n!=null&&n.selectedVariants){const o=n.selectedVariants[0].id;if(i&&o){const l=(s=i.variants)==null?void 0:s.find(c=>c.id===o);l&&await e.setSelectionsAndElements(t.stepName,[l],[])}}}async selectVariant(t,e,a){await a.getInitializationPromise();const n=await this.selectVariantLambda(t,e,a);n&&(n.command&&a.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,a){const n=t.option;if(!n)return null;const i=n.variants;if(!i)return null;const s=i.length>1?i.find(o=>o.id===e):i[0];if(!s)throw new Error(`Failed to find selected variant ${e} in option ${n.id} of step ${t.stepName} (${t.stepTitle})`);return{command:void 0,followup:async()=>{await a.setSelectionsAndElements(t.stepName,[s],[],async()=>{a.setMandatoryFulfilled(t.stepName,!0)})}}}}const Ua=new Do;class xo{constructor(){this.shapeFillId="spiff-fill-shape"}async availableColours(t){var a;const e=t.option;return e?((a=e.variants)==null?void 0:a.map(n=>({fill:n.color,stroke:n.color,variant:n})))||[]:[]}setCustomColor(t,e,a){const n=a.getLayouts(),s=(a.getRegionElements(e.stepName)||[]).map(o=>{const l=o.region;if(!n.find(d=>d.panelId===(l==null?void 0:l.panelId)))throw new Y(l);return new ga(o.id,this.shapeFillId,t)}).filter(o=>!!o);a.getCommandDispatcher()(new $(s)),a.updateStorage(e.stepName,{colour:t})}async init(t,e,a){const n=t.option;if(!n)throw new te(t);if(a)await this.reload(t,e,a);else{const i=H.getDefaultVariant(n);return i?this.selectVariantCommand(t,{fill:i.color,stroke:i.color,variant:i},[],e):null}return null}async selectVariant(t,e,a,n){const i=await this.selectVariantCommand(t,e,a,n);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async reload(t,e,a){var c;const n=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),o=Object.values(a.layouts).map(d=>d.elements).flat().filter(d=>d.stepName===t.stepName),l=t.option;if(n!=null&&n.selectedVariants){const d=n.selectedVariants[0].id;if(l&&d){const A=(c=l.variants)==null?void 0:c.find(u=>u.id===d);if(A){const u=o.map(h=>({id:h.id,region:h.stepRegion}));await e.setSelectionsAndElements(t.stepName,[A],u,async()=>{var h;e.updateStorage(t.stepName,{colour:((h=n==null?void 0:n.storage)==null?void 0:h.colour)||""}),e.setMandatoryFulfilled(t.stepName,!0)})}}}}async selectVariantCommand(t,e,a,n){var l;const i=n.getLayouts(),s=(l=n.getStepStorage(t.stepName))==null?void 0:l.colour,o=()=>{var c,d;if(((c=e.variant)==null?void 0:c.color)==="#custom")return s||"#FFFFFF";if((d=e.variant)!=null&&d.color)return e.variant.color;throw new Error("Failed to resolve color for shape step.")};if(a.length>0){const c=A=>{const u=A.region;if(!i.find(m=>m.panelId===(u==null?void 0:u.panelId)))throw new Y(u);const g=o();return new ga(A.id,this.shapeFillId,g)},d=a.map(c).filter(A=>!!A);return{command:new $(d),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],a),n.updateStorage(t.stepName,{colour:o()})}}}else{const c=h=>{const g=i.find(w=>w.panelId===h.panelId);if(!g)throw new Y(h);const m=o(),p=`
1439
1439
  <svg
1440
1440
  xmlns="http://www.w3.org/2000/svg"
1441
1441
  xmlnsXlink="http://www.w3.org/1999/xlink"
@@ -2125,7 +2125,7 @@
2125
2125
  id
2126
2126
  }
2127
2127
  }
2128
- `;var ge=(r=>(r.Error="Error",r.Warning="Warning",r.Info="Info",r))(ge||{});const yl=1e3;class dn extends Ia{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},yl)})}}class Sl{constructor(t,e,a,n,i,s,o,l,c,d,A,u,h,g=!1,m,p=!1,f=!1,C=!1){var w;this.workflowStatePromiseQueue=new Pa(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.renderLayouts=()=>{var E;if(!this.previewService)return;const S=this.getCommandContext().getAllLayouts(),y=(E=this.getLayoutPreviewService())==null?void 0:E.getAll();if(y)for(const[,b]of y)b.render(S)},this.experience=t,this.client=e,this.updateTransaction=o,this.graphQlClient=l,this.commandContext=s,this.reloadedState=h,this.transaction=c,this.readOnly=g,this.singleVariantsRenderable=f,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=a,this.stepSpecificServices={},this.profanityFilter=n,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=d,this.previewService=A,this.modelContainer=m,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.currentAdjustingStepId="",this.renderableContextService=u,(w=this.renderableContextService)==null||w.setWorkflowManager(this),this.isReloadedTransaction=p,this.workflow.steps.forEach(S=>{this.stepTags[S.stepName]=S.tags??[]}),C&&(this.workflowStatePromiseQueue.enabled=!1),this.initializationPromise=this.initializeDefaultWorkflowState(a),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(S=>{throw console.error(S),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.getCommandContext().registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()}))}getTemplatingContext(){return{recipient:this.transaction.recipient}}async updateRecipient(t,e,a,n,i,s,o,l,c,d){var A,u,h,g,m;if((A=this.transaction.recipient)!=null&&A.id)this.transaction.recipient={id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:n||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:s||this.transaction.recipient.email,postalCode:o||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company},await this.graphQlClient().mutate({mutation:Cl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:n||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:s||this.transaction.recipient.email,postalCode:o||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company}});else{const p=await this.graphQlClient().mutate({mutation:fl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:n,state:i,email:s,postalCode:o,country:l,mobile:c,company:d}});this.transaction.recipient={id:(h=(u=p==null?void 0:p.data)==null?void 0:u.recipientCreate)==null?void 0:h.id,firstName:t,lastName:e,address:a,suburb:n,state:i,email:s,postalCode:o,country:l,mobile:c,company:d},await this.graphQlClient().mutate({mutation:wl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id,recipientId:(m=(g=p.data)==null?void 0:g.recipientCreate)==null?void 0:m.id},context:{transactionOwnerId:this.transaction.transactionOwnerId}})}this.recipientCallbacks.forEach(p=>p(this.transaction.recipient))}async initializeDefaultWorkflowState(t){const e=()=>{var d,A;const o=this.workflow.finalizeStepConfig;if(!o)return;const l=o.lookAtAnimation,c=o.modelAnimation;l&&((d=this.previewService)==null||d.executeCameraAnimation(l)),c&&((A=this.modelContainer)==null||A.executeAnimation(c))};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(o=>{this.storage[o.stepName]=o.storage||{}}),this.allScenes=await Fs(t);const n=xt(this.allScenes,this.stepSelections).map(o=>o.silentSteps).flat(),{stepElements:i,commands:s}=await this.stepElementsForIntroducedSilentSteps(n,!!this.reloadedState);this.commandContext.apply(new $(s),!0),this.stepElements={...this.stepElements,...i},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addPoller(t){this.pollers.push(t)}addValidationCallback(t){this.validationCallbacks.push(t),t(this.validationErrors)}addRecipientCallback(t){this.recipientCallbacks.push(t),t(this.transaction.recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(t=>t.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!0}),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter(e=>e!==t)}markUpdatePending(){const t=Q();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}setStepError(t,e,a){let n=!1;if(!this.validationErrors.steps.has(t)&&a)n=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const i=this.validationErrors.steps.get(t);a&&a!==i.get(e)?(n=!0,i.set(e,a)):a||(n=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}n&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const a=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(a),xt(this.allScenes,this.stepSelections).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===P.Model||s.type===P.Material).forEach(s=>{var c,d,A;if(!((c=s.option)!=null&&c.id)){console.error(`Failed to read option id from step: ${s.stepName}`);return}const o=((d=this.stepSelections[s.stepName])==null?void 0:d.selectedVariants)||[];if(o.length===0)return;const l=o[0];if(s.type===P.Model){if(!this.modelContainer)throw new z("We should always have a model container when injecting a preview!");const u=(A=l.asset)==null?void 0:A.fileLink;if(!u){console.error(`Failed to read model url from variant: ${l.id} for step: ${s.stepName}`);return}const h=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:u,contextService:this.getLayoutPreviewService()},h.replaceProductModel||!1)}else{const u=l.material;if(!u){console.error(`Failed to read material from variant: ${l.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(g=>{if(!this.modelContainer)throw new z("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(g,s.option.id,u)})}}),await a.getInitializationPromise(),this.renderLayouts()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}updateStorage(t,e){const a={...this.storage,[t]:{...this.storage[t],...e}};if(!Sn(a,this.storage)){this.storage=a;const n=new sn(this.constructSerializableWorkflow());this.commandContext.apply(n,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{var i,s;const n={stepName:a.stepName};n.storage=this.storage[a.stepName],n.selectedVariants=(s=(i=this.stepSelections[a.stepName])==null?void 0:i.selectedVariants)==null?void 0:s.map(o=>({id:o.id,priceModifier:o.priceModifier})),t.push(n)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new dn(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new dn(async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new z("Attempted to serialize state before it was initialized.");const e=Et(t.transaction),a=this.dehydrateState(e);return JSON.stringify(a)}dehydrateState(t){var e;for(const a of Object.values(t.layouts).map(n=>n.elements).flat())a.type==="illustration"&&(delete a.cachedObjectURL,a.src&&delete a.svg),a.type==="frame"&&((e=a.pattern)==null||delete e.svg);return this.deleteFieldNameFromObjectRecursive(t,"__typename"),t}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,n)=>Object.keys(a).reduce((i,s)=>{const o=[...a[s]||[]];return n.forEach(l=>{const c=o.findIndex(d=>d.id===l.id);c>-1&&o.splice(c,1)}),i[s]=o,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce((t,e)=>(vt(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])}getInvalidModelVariants(){return this.workflow.steps.reduce((t,e)=>(e.type===P.Model&&!vt(e,this.stepSelections)&&t.push(e.stepName),t),[])}async stepElementsForIntroducedSilentSteps(t,e){const a=this.product;if(!a)return Promise.resolve({stepElements:{},commands:[]});const n=async(c,d,A)=>{if(c.type===P.SilentIllustration){const u=await new on(c,d).trigger();return{step:c,results:u}}else if(c.type===P.ProductOverlay){const u=await new on(c,d,A).trigger();return{step:c,results:u}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),s={stepElements:{},commands:[]},o=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||o.push(n(c,this.layouts,a));const l=await Promise.all(o);for(const c of l)s.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),s.commands=[...s.commands,...c.results.map(d=>d.command)];return s}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.transaction.id);this.transaction.transactionShareActions=t}async updateTransactionStakeholders(){var e;const t=await B.getShadowGraphqlClient().query({query:ms,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id}});!((e=t==null?void 0:t.data)!=null&&e.transactions)||t.data.transactions.length!==1?(this.transaction.currentStakeholder=void 0,this.transaction.stakeholders=void 0):(this.transaction.stakeholders=t.data.transactions[0].stakeholders,this.transaction.currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await B.getShadowGraphqlClient().mutate({mutation:ml,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async rejectTransaction(t){await B.getShadowGraphqlClient().mutate({mutation:pl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async reset(){this.commandContext.getAllLayouts().forEach(e=>e.layoutState.elements.forEach(a=>{this.getCommandDispatcher()(new Ct(a.id))})),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,n){var y;const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((E,b)=>E+b.selectedVariants.map(I=>I.priceModifier||0).reduce((I,x)=>I+x,0),0),this.workflow.steps.forEach(E=>{vt(E,this.stepSelections)||(this.stepInitialised[E.stepName]=!1,delete this.stepMetadata[E.stepName],delete this.stepSelections[E.stepName],delete this.storage[E.stepName])});const s=this.allScenes,o=xt(s,i),l=xt(s,this.stepSelections),c=o.map(E=>E.silentSteps).flat(),A=l.map(E=>E.silentSteps).flat().filter(E=>!c.some(b=>b.stepName===E.stepName));c.forEach(E=>{vt(E,this.stepSelections)||(this.stepInitialised[E.stepName]=!1)});const u=this.getInvalidCanvasRegions(),{stepElements:h,commands:g}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...h,[t]:a},this.removeElements(u);const m=this.workflow.steps.find(E=>E.stepName===t);if((m==null?void 0:m.type)===P.Frame){const E=(y=this.getWorkflowExperience().getStepById(m.stepName))==null?void 0:y.frameService;E==null||E.setTargetElements(a.map(b=>b.id))}const p=u.map(E=>new Ct(E.id)),f=new sn(this.constructSerializableWorkflow()),C=[...g,...p,f];C.length>0&&this.commandContext.apply(new $(C),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const w=this.getInvalidModelVariants(),S=this.modelContainer;if(S){const E=w.map(b=>S.applyModelVariant(b,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(E)}await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const e=xt(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],n=e.flat();for(const l of n)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case P.DigitalContent:a.push(Na.init(l,this,this.reloadedState));break;case P.Frame:a.push(ut.init(l,this,this.reloadedState));break;case P.Illustration:a.push(Jt.init(l,this,this.reloadedState));break;case P.Material:a.push(Qa.init(l,this,this.reloadedState));break;case P.Model:a.push(Ra.init(l,this,this.reloadedState));break;case P.Module:this.stepSpecificServices[l.stepName]={module:await hr(l.data.module)},a.push(Oa.init(l,this,this.reloadedState));break;case P.Picture:a.push($a.init(l,this,this.reloadedState));break;case P.Question:a.push(Ua.init(l,this,this.reloadedState));break;case P.Shape:a.push(kt.init(l,this,this.reloadedState));break;case P.Text:a.push(W.init(l,this,this.reloadedState));break}const i=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),s=i.filter(l=>!!l&&!!l.command).map(l=>l.command),o=i.filter(l=>!!l&&!!l.followup).map(l=>l.followup);s&&s.length>0&&this.commandContext.apply(new $(s),!0);for(const l of o)await l();o.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(t=>t(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(t=>t(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(t=>t(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(t=>t(this.informationResults))}onInitChange(){this.initCallbacks.forEach(t=>t(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(t=>{t(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(t=>t(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(t=>{t(this.stepMetadata)})}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach(e=>e(this.storage[t]))}onStorageChange(){this.storageCallbacks.forEach(t=>t(this.storage))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return Ts(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class it{constructor(t){this.variantData=t}getType(){var t;return(t=this.variantData.asset)==null?void 0:t.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){var t,e,a;return(a=(e=(t=this.variantData.asset)==null?void 0:t.versions)==null?void 0:e.find(n=>n.name==="cdn"))==null?void 0:a.link}getAssetResource(){return this.variantData.asset}getThumbnail(){var a,n,i,s;const t=(i=(n=(a=this.variantData.thumbnail)==null?void 0:a.versions)==null?void 0:n.find(o=>o.name==="thumbnail"))==null?void 0:i.link,e=(s=this.variantData.thumbnail)==null?void 0:s.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}const gr=class ma{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){ma.updateState.set(`${this.step.stepName}-${this.manager.getTransaction().id}`,t)}getUpdateState(){return!!ma.updateState.get(`${this.step.stepName}-${this.manager.getTransaction().id}`)}getCurrentVariant(){const e=this.manager.getWorkflowSelections()[this.step.stepName],a=e==null?void 0:e.selections[0];if(a)return new it(a)}getAvailableVariants(){var e,a;return(((a=(e=this.step.option)==null?void 0:e.variants)==null?void 0:a.filter(n=>n.enabled))||[]).map(n=>new it(n))}getAllVariants(){var e;return(((e=this.step.option)==null?void 0:e.variants)||[]).map(a=>new it(a))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.tags}hasTag(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){var a;return(((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.overrideGlobalConfigurations)??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){var n;const a=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.overrideGlobalConfigurations)??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){var e;return((e=this.step.globalPropertyAspectConfigurations)==null?void 0:e.filter(a=>a.globalPropertyConfigurationId===t&&a.aspectName).map(a=>a.aspectName))??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),n=this.step.data.modelAnimation,i=this.step.data.lookAtAnimation;e?i&&e.executeCameraAnimation(i):console.warn("No preview service available, cannot execute camera animations."),a?n&&a.executeAnimation(n,t):console.warn("No model container available, cannot execute model animations.")}};gr.updateState=new Map;let nt=gr;class mr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Jt.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){var o;const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=L(t[0].id,this.manager.getAllLayoutData()).colors,n=(o=this.getCurrentVariant())==null?void 0:o.getAssetResource(),i=n==null?void 0:n.assetConfiguration,s=(i==null?void 0:i.defaultColorVariants)||[];if(s.length!==0){const l={};return s.forEach(c=>{var A;const d=i.channelNumbers.find(u=>u.number===c.channelNumber);if(d){const u=d.id.replace(/\W/g,"");l[c.channelNumber]={browserValue:((A=a[u])==null?void 0:A.browserValue)||""}}}),l}try{return a}catch(l){console.error(l)}}setColor(t,e,a){var l;const n=new Map,i=(l=this.getCurrentVariant())==null?void 0:l.getAssetResource(),s=i==null?void 0:i.assetConfiguration;return((s==null?void 0:s.defaultColorVariants)||[]).length!==0?s.channelNumbers.forEach(c=>{if(c.number.toString()===t){const d=c.id.replace(/\W/g,"");a?n.set(d,{browserValue:e,pmsValue:a}):n.set(d,e)}}):a?n.set(t,{browserValue:e,pmsValue:a}):n.set(t,e),Jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),n)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?Jt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}}class pr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Qa.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class fr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ra.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Cr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){return $a.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class wr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await Ua.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){var t;return this.step.data.displayType||((t=this.step.option)==null?void 0:t.displayType)}}class yr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return kt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return kt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return kt.availableColours(this.step)}setCustomColor(t){var e,a;return((e=this.getCurrentVariant())==null?void 0:e.getColor())!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${(a=this.getCurrentVariant())==null?void 0:a.getColor()}`),kt.setCustomColor(t,this.step,this.manager)}getCustomColor(){var e,a,n;((e=this.getCurrentVariant())==null?void 0:e.getColor())!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${(a=this.getCurrentVariant())==null?void 0:a.getColor()}`);const t=(n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}}class Sr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(t){W.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:ge.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?W.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillColor(this.step,t,e,this.manager)}getFillColor(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.color)||"#000000"}getAvailableFillImages(){return W.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillImage(this.step,t,e,this.manager)}getFillImage(){var t;return(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.fillImage}getAlignment(){const t=W.findLayoutElements(this.manager,this.step);return t==null?void 0:t[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);W.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){var s;const e=((s=this.manager.getStepStorage(this.step.stepName))==null?void 0:s.inputText)||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,n=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1}),this.setText(n)}setText(t){var d;console.log("LOG: attempting to set text in handle"),console.trace();const e={input:t,helperData:{}},a=W.findLayoutElements(this.manager,this.step),n=W.filterUnsupportedCharacters(t,(d=a[0])==null?void 0:d.fontData),i=!!this.step.data&&!!this.step.data.maxLength&&n.length>this.step.data.maxLength;i||(e.input=n);const s=a.length<=0,o=s?{inputText:n,text:n}:{inputText:n};this.manager.updateStorage(this.step.stepName,o);const l=this.manager.getStepStorage(this.step.stepName),c=W.getProcessedInput(n,this.step.data,(l==null?void 0:l.customiseAllText)??!1);if(s)i||this.manager.updateMetadata(this.step.stepName,{text:c});else{const{command:A,errorData:u,helperData:h}=W.updateInputText(n,a,this.step,this.manager);A&&this.manager.getCommandDispatcher()(A),e.helperData=h,e.errorData=u,!i&&!u&&this.manager.updateMetadata(this.step.stepName,{text:c})}return e}getText(){var a;const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&(e==null?void 0:e.defaultCleared)!==void 0&&!(e!=null&&e.defaultCleared)?t:((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.text)||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){const t=this.manager.getStepStorage(this.step.stepName);if(!(t!=null&&t.defaultCleared)&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=W.findLayoutElements(this.manager,this.step);return W.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=this.getText();return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}getAvailableStrokeColors(){return this.step.data.strokeEnabled?W.availableStrokeColors(this.step):[]}getStrokeColor(){var t,e;return((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.strokeColor)==null?void 0:e.browserValue)||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeStrokeColor(this.step,t,e,this.manager)}}class vr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Er extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.videoUrl)||""}async selectVideo(t){return Na.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class br extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=this.getText();return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.text)||""}setText(t){Oa.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:ge.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class we{static get(t,e){switch(e.type){case P.DigitalContent:return new Er(t,e,t.getStepTags(e.stepName));case P.Information:return new vr(t,e,t.getStepTags(e.stepName));case P.Question:return new wr(t,e,t.getStepTags(e.stepName));case P.Text:return new Sr(t,e,t.getStepTags(e.stepName));case P.Illustration:return new mr(t,e,t.getStepTags(e.stepName));case P.Picture:return new Cr(t,e,t.getStepTags(e.stepName));case P.Shape:return new yr(t,e,t.getStepTags(e.stepName));case P.Material:return new pr(t,e,t.getStepTags(e.stepName));case P.Model:return new fr(t,e,t.getStepTags(e.stepName));case P.Frame:return new Hr(t,e,t.getStepTags(e.stepName));case P.Module:return new br(t,e,t.getStepTags(e.stepName));default:throw new z(`Step type ${e.type} not yet supported in Core SDK`)}}}const Br=v.gql`
2128
+ `;var ge=(r=>(r.Error="Error",r.Warning="Warning",r.Info="Info",r))(ge||{});const yl=1e3;class dn extends Ia{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},yl)})}}class Sl{constructor(t,e,a,n,i,s,o,l,c,d,A,u,h,g=!1,m,p=!1,f=!1,C=!1){var w;this.workflowStatePromiseQueue=new Pa(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.renderLayouts=()=>{var E;if(!this.previewService)return;const S=this.getCommandContext().getAllLayouts(),y=(E=this.getLayoutPreviewService())==null?void 0:E.getAll();if(y)for(const[,b]of y)b.render(S)},this.experience=t,this.client=e,this.updateTransaction=o,this.graphQlClient=l,this.commandContext=s,this.reloadedState=h,this.transaction=c,this.readOnly=g,this.singleVariantsRenderable=f,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=a,this.stepSpecificServices={},this.profanityFilter=n,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=d,this.previewService=A,this.modelContainer=m,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.currentAdjustingStepId="",this.renderableContextService=u,(w=this.renderableContextService)==null||w.setWorkflowManager(this),this.isReloadedTransaction=p,this.workflow.steps.forEach(S=>{this.stepTags[S.stepName]=S.tags??[]}),C&&(this.workflowStatePromiseQueue.enabled=!1),this.initializationPromise=this.initializeDefaultWorkflowState(a),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(S=>{throw console.error(S),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.getCommandContext().registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()}))}getTemplatingContext(){return{recipient:this.transaction.recipient}}async updateRecipient(t,e,a,n,i,s,o,l,c,d){var A,u,h,g,m;if((A=this.transaction.recipient)!=null&&A.id)this.transaction.recipient={id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:n||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:s||this.transaction.recipient.email,postalCode:o||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company},await this.graphQlClient().mutate({mutation:Cl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:n||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:s||this.transaction.recipient.email,postalCode:o||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company}});else{const p=await this.graphQlClient().mutate({mutation:fl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:n,state:i,email:s,postalCode:o,country:l,mobile:c,company:d}});this.transaction.recipient={id:(h=(u=p==null?void 0:p.data)==null?void 0:u.recipientCreate)==null?void 0:h.id,firstName:t,lastName:e,address:a,suburb:n,state:i,email:s,postalCode:o,country:l,mobile:c,company:d},await this.graphQlClient().mutate({mutation:wl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id,recipientId:(m=(g=p.data)==null?void 0:g.recipientCreate)==null?void 0:m.id},context:{transactionOwnerId:this.transaction.transactionOwnerId}})}this.recipientCallbacks.forEach(p=>p(this.transaction.recipient))}async initializeDefaultWorkflowState(t){const e=()=>{var d,A;const o=this.workflow.finalizeStepConfig;if(!o)return;const l=o.lookAtAnimation,c=o.modelAnimation;l&&((d=this.previewService)==null||d.executeCameraAnimation(l)),c&&((A=this.modelContainer)==null||A.executeAnimation(c))};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(o=>{this.storage[o.stepName]=o.storage||{}}),this.allScenes=await Fs(t);const n=xt(this.allScenes,this.stepSelections).map(o=>o.silentSteps).flat(),{stepElements:i,commands:s}=await this.stepElementsForIntroducedSilentSteps(n,!!this.reloadedState);this.commandContext.apply(new $(s),!0),this.stepElements={...this.stepElements,...i},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addPoller(t){this.pollers.push(t)}addValidationCallback(t){this.validationCallbacks.push(t),t(this.validationErrors)}addRecipientCallback(t){this.recipientCallbacks.push(t),t(this.transaction.recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(t=>t.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!0}),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter(e=>e!==t)}markUpdatePending(){const t=Q();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}setStepError(t,e,a){let n=!1;if(!this.validationErrors.steps.has(t)&&a)n=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const i=this.validationErrors.steps.get(t);a&&a!==i.get(e)?(n=!0,i.set(e,a)):a||(n=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}n&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const a=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(a),xt(this.allScenes,this.stepSelections).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===P.Model||s.type===P.Material).forEach(s=>{var c,d,A;if(!((c=s.option)!=null&&c.id)){console.error(`Failed to read option id from step: ${s.stepName}`);return}const o=((d=this.stepSelections[s.stepName])==null?void 0:d.selectedVariants)||[];if(o.length===0)return;const l=o[0];if(s.type===P.Model){if(!this.modelContainer)throw new z("We should always have a model container when injecting a preview!");const u=(A=l.asset)==null?void 0:A.fileLink;if(!u){console.error(`Failed to read model url from variant: ${l.id} for step: ${s.stepName}`);return}const h=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:u,contextService:this.getLayoutPreviewService()},h.replaceProductModel||!1)}else{const u=l.material;if(!u){console.error(`Failed to read material from variant: ${l.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(g=>{if(!this.modelContainer)throw new z("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(g,s.option.id,u)})}}),await a.getInitializationPromise(),this.renderLayouts()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}updateStorage(t,e){const a={...this.storage,[t]:{...this.storage[t],...e}};if(!Sn(a,this.storage)){this.storage=a;const n=new sn(this.constructSerializableWorkflow());this.commandContext.apply(n,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{var i,s;const n={stepName:a.stepName};n.storage=this.storage[a.stepName],n.selectedVariants=(s=(i=this.stepSelections[a.stepName])==null?void 0:i.selectedVariants)==null?void 0:s.map(o=>({id:o.id,priceModifier:o.priceModifier})),t.push(n)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new dn(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new dn(async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new z("Attempted to serialize state before it was initialized.");const e=Et(t.transaction),a=this.dehydrateState(e);return JSON.stringify(a)}dehydrateState(t){var e;for(const a of Object.values(t.layouts).map(n=>n.elements).flat())a.type==="illustration"&&(delete a.cachedObjectURL,a.src&&delete a.svg),a.type==="frame"&&((e=a.pattern)==null||delete e.svg);return this.deleteFieldNameFromObjectRecursive(t,"__typename"),t}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,n)=>Object.keys(a).reduce((i,s)=>{const o=[...a[s]||[]];return n.forEach(l=>{const c=o.findIndex(d=>d.id===l.id);c>-1&&o.splice(c,1)}),i[s]=o,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce((t,e)=>(vt(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])}getInvalidModelVariants(){return this.workflow.steps.reduce((t,e)=>(e.type===P.Model&&!vt(e,this.stepSelections)&&t.push(e.stepName),t),[])}async stepElementsForIntroducedSilentSteps(t,e){const a=this.product;if(!a)return Promise.resolve({stepElements:{},commands:[]});const n=async(c,d,A)=>{if(c.type===P.SilentIllustration){const u=await new on(c,d).trigger();return{step:c,results:u}}else if(c.type===P.ProductOverlay){const u=await new on(c,d,A).trigger();return{step:c,results:u}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),s={stepElements:{},commands:[]},o=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||o.push(n(c,this.layouts,a));const l=await Promise.all(o);for(const c of l)s.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),s.commands=[...s.commands,...c.results.map(d=>d.command)];return s}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.transaction.id);this.transaction.transactionShareActions=t}async updateTransactionStakeholders(){var e;const t=await B.getShadowGraphqlClient().query({query:ms,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id}});!((e=t==null?void 0:t.data)!=null&&e.transactions)||t.data.transactions.length!==1?(this.transaction.currentStakeholder=void 0,this.transaction.stakeholders=void 0):(this.transaction.stakeholders=t.data.transactions[0].stakeholders,this.transaction.currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await B.getShadowGraphqlClient().mutate({mutation:ml,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async rejectTransaction(t){await B.getShadowGraphqlClient().mutate({mutation:pl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async reset(){this.commandContext.getAllLayouts().forEach(e=>e.layoutState.elements.forEach(a=>{this.getCommandDispatcher()(new Ct(a.id))})),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,n){var y;const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((E,b)=>E+b.selectedVariants.map(I=>I.priceModifier||0).reduce((I,x)=>I+x,0),0),this.workflow.steps.forEach(E=>{vt(E,this.stepSelections)||(this.stepInitialised[E.stepName]=!1,delete this.stepMetadata[E.stepName],delete this.stepSelections[E.stepName],delete this.storage[E.stepName])});const s=this.allScenes,o=xt(s,i),l=xt(s,this.stepSelections),c=o.map(E=>E.silentSteps).flat(),A=l.map(E=>E.silentSteps).flat().filter(E=>!c.some(b=>b.stepName===E.stepName));c.forEach(E=>{vt(E,this.stepSelections)||(this.stepInitialised[E.stepName]=!1)});const u=this.getInvalidCanvasRegions(),{stepElements:h,commands:g}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...h,[t]:a},this.removeElements(u);const m=this.workflow.steps.find(E=>E.stepName===t);if((m==null?void 0:m.type)===P.Frame){const E=(y=this.getWorkflowExperience().getStepById(m.stepName))==null?void 0:y.frameService;E==null||E.setTargetElements(a.map(b=>b.id))}const p=u.map(E=>new Ct(E.id)),f=new sn(this.constructSerializableWorkflow()),C=[...g,...p,f];C.length>0&&this.commandContext.apply(new $(C),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const w=this.getInvalidModelVariants(),S=this.modelContainer;if(S){const E=w.map(b=>S.applyModelVariant(b,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(E)}await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const e=xt(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],n=e.flat();for(const l of n)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case P.DigitalContent:a.push(Na.init(l,this,this.reloadedState));break;case P.Frame:a.push(ut.init(l,this,this.reloadedState));break;case P.Illustration:a.push(Jt.init(l,this,this.reloadedState));break;case P.Material:a.push(Qa.init(l,this,this.reloadedState));break;case P.Model:a.push(Ra.init(l,this,this.reloadedState));break;case P.Module:this.stepSpecificServices[l.stepName]={module:await hr(l.data.module)},a.push(Oa.init(l,this,this.reloadedState));break;case P.Picture:a.push($a.init(l,this,this.reloadedState));break;case P.Question:a.push(Ua.init(l,this,this.reloadedState));break;case P.Shape:a.push(kt.init(l,this,this.reloadedState));break;case P.Text:a.push(W.init(l,this,this.reloadedState));break}const i=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),s=i.filter(l=>!!l&&!!l.command).map(l=>l.command),o=i.filter(l=>!!l&&!!l.followup).map(l=>l.followup);s&&s.length>0&&this.commandContext.apply(new $(s),!0);for(const l of o)await l();o.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(t=>t(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(t=>t(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(t=>t(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(t=>t(this.informationResults))}onInitChange(){this.initCallbacks.forEach(t=>t(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(t=>{t(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(t=>t(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(t=>{t(this.stepMetadata)})}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach(e=>e(this.storage[t]))}onStorageChange(){this.storageCallbacks.forEach(t=>t(this.storage))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return Ts(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class it{constructor(t){this.variantData=t}getType(){var t;return(t=this.variantData.asset)==null?void 0:t.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){var t,e,a;return(a=(e=(t=this.variantData.asset)==null?void 0:t.versions)==null?void 0:e.find(n=>n.name==="cdn"))==null?void 0:a.link}getAssetResource(){return this.variantData.asset}getThumbnail(){var a,n,i,s;const t=(i=(n=(a=this.variantData.thumbnail)==null?void 0:a.versions)==null?void 0:n.find(o=>o.name==="thumbnail"))==null?void 0:i.link,e=(s=this.variantData.thumbnail)==null?void 0:s.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}const gr=class ma{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){ma.updateState.set(`${this.step.stepName}-${this.manager.getTransaction().id}`,t)}getUpdateState(){return!!ma.updateState.get(`${this.step.stepName}-${this.manager.getTransaction().id}`)}getCurrentVariant(){const e=this.manager.getWorkflowSelections()[this.step.stepName],a=e==null?void 0:e.selections[0];if(a)return new it(a)}getAvailableVariants(){var e,a;return(((a=(e=this.step.option)==null?void 0:e.variants)==null?void 0:a.filter(n=>n.enabled))||[]).map(n=>new it(n))}getAllVariants(){var e;return(((e=this.step.option)==null?void 0:e.variants)||[]).map(a=>new it(a))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.tags}hasTag(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){var a;return(((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.overrideGlobalConfigurations)??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){var n;const a=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.overrideGlobalConfigurations)??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){var e;return((e=this.step.globalPropertyAspectConfigurations)==null?void 0:e.filter(a=>a.globalPropertyConfigurationId===t&&a.aspectName).map(a=>a.aspectName))??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),n=this.step.data.modelAnimation,i=this.step.data.lookAtAnimation;e?i&&e.executeCameraAnimation(i):console.warn("No preview service available, cannot execute camera animations."),a?n&&a.executeAnimation(n,t):console.warn("No model container available, cannot execute model animations.")}};gr.updateState=new Map;let nt=gr;class mr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Jt.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){var o;const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=L(t[0].id,this.manager.getAllLayoutData()).colors,n=(o=this.getCurrentVariant())==null?void 0:o.getAssetResource(),i=n==null?void 0:n.assetConfiguration,s=(i==null?void 0:i.defaultColorVariants)||[];if(s.length!==0){const l={};return s.forEach(c=>{var A;const d=i.channelNumbers.find(u=>u.number===c.channelNumber);if(d){const u=d.id.replace(/\W/g,"");l[c.channelNumber]={browserValue:((A=a[u])==null?void 0:A.browserValue)||""}}}),l}try{return a}catch(l){console.error(l)}}setColor(t,e,a){var l;const n=new Map,i=(l=this.getCurrentVariant())==null?void 0:l.getAssetResource(),s=i==null?void 0:i.assetConfiguration;return((s==null?void 0:s.defaultColorVariants)||[]).length!==0?s.channelNumbers.forEach(c=>{if(c.number.toString()===t){const d=c.id.replace(/\W/g,"");a?n.set(d,{browserValue:e,pmsValue:a}):n.set(d,e)}}):a?n.set(t,{browserValue:e,pmsValue:a}):n.set(t,e),Jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),n)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?Jt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}}class pr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Qa.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class fr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ra.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Cr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){return $a.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class wr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await Ua.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){var t;return this.step.data.displayType||((t=this.step.option)==null?void 0:t.displayType)}}class yr extends nt{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return kt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return kt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return kt.availableColours(this.step)}setCustomColor(t){var e,a;return((e=this.getCurrentVariant())==null?void 0:e.getColor())!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${(a=this.getCurrentVariant())==null?void 0:a.getColor()}`),kt.setCustomColor(t,this.step,this.manager)}getCustomColor(){var e,a,n;((e=this.getCurrentVariant())==null?void 0:e.getColor())!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${(a=this.getCurrentVariant())==null?void 0:a.getColor()}`);const t=(n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}}class Sr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(t){W.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:ge.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?W.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);console.log(`LOG: changing fill color of step ${this.step.stepTitle} (${this.step.stepName}) with ${e.length} elements to ${t}`),await W.changeFillColor(this.step,t,e,this.manager)}getFillColor(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.color)||"#000000"}getAvailableFillImages(){return W.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillImage(this.step,t,e,this.manager)}getFillImage(){var t;return(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.fillImage}getAlignment(){const t=W.findLayoutElements(this.manager,this.step);return t==null?void 0:t[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);W.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){var s;const e=((s=this.manager.getStepStorage(this.step.stepName))==null?void 0:s.inputText)||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,n=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1}),this.setText(n)}setText(t){var d;const e={input:t,helperData:{}},a=W.findLayoutElements(this.manager,this.step),n=W.filterUnsupportedCharacters(t,(d=a[0])==null?void 0:d.fontData),i=!!this.step.data&&!!this.step.data.maxLength&&n.length>this.step.data.maxLength;i||(e.input=n);const s=a.length<=0,o=s?{inputText:n,text:n}:{inputText:n};this.manager.updateStorage(this.step.stepName,o);const l=this.manager.getStepStorage(this.step.stepName),c=W.getProcessedInput(n,this.step.data,(l==null?void 0:l.customiseAllText)??!1);if(s)i||this.manager.updateMetadata(this.step.stepName,{text:c});else{const{command:A,errorData:u,helperData:h}=W.updateInputText(n,a,this.step,this.manager);A&&this.manager.getCommandDispatcher()(A),e.helperData=h,e.errorData=u,!i&&!u&&this.manager.updateMetadata(this.step.stepName,{text:c})}return e}getText(){var a;const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&(e==null?void 0:e.defaultCleared)!==void 0&&!(e!=null&&e.defaultCleared)?t:((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.text)||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){const t=this.manager.getStepStorage(this.step.stepName);if(!(t!=null&&t.defaultCleared)&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=W.findLayoutElements(this.manager,this.step);return W.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=this.getText();return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}getAvailableStrokeColors(){return this.step.data.strokeEnabled?W.availableStrokeColors(this.step):[]}getStrokeColor(){var t,e;return((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.strokeColor)==null?void 0:e.browserValue)||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeStrokeColor(this.step,t,e,this.manager)}}class vr extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Er extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.videoUrl)||""}async selectVideo(t){return Na.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class br extends nt{constructor(t,e,a){super(t,e,a)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=this.getText();return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.text)||""}setText(t){Oa.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:ge.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class we{static get(t,e){switch(e.type){case P.DigitalContent:return new Er(t,e,t.getStepTags(e.stepName));case P.Information:return new vr(t,e,t.getStepTags(e.stepName));case P.Question:return new wr(t,e,t.getStepTags(e.stepName));case P.Text:return new Sr(t,e,t.getStepTags(e.stepName));case P.Illustration:return new mr(t,e,t.getStepTags(e.stepName));case P.Picture:return new Cr(t,e,t.getStepTags(e.stepName));case P.Shape:return new yr(t,e,t.getStepTags(e.stepName));case P.Material:return new pr(t,e,t.getStepTags(e.stepName));case P.Model:return new fr(t,e,t.getStepTags(e.stepName));case P.Frame:return new Hr(t,e,t.getStepTags(e.stepName));case P.Module:return new br(t,e,t.getStepTags(e.stepName));default:throw new z(`Step type ${e.type} not yet supported in Core SDK`)}}}const Br=v.gql`
2129
2129
  fragment CreateDesignTransaction on Transaction {
2130
2130
  id
2131
2131
  designName
@@ -2196,7 +2196,7 @@
2196
2196
  }
2197
2197
  }
2198
2198
  }
2199
- `;function _t(r){const t=JSON.parse(atob(r.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const bl=async(r,t)=>{var n,i;const e={};try{if(t){const s=await t.loggedInBearerToken();e.Authorization=`Bearer ${s}`}else throw new Error}catch{const l=((n=Object.entries(localStorage).find(([d,A])=>d.startsWith("CognitoIdentityServiceProvider")&&d.endsWith("idToken")))==null?void 0:n[0])||"",c=localStorage.getItem(l);c&&!_t(c)&&(e.Authorization=`Bearer ${c}`)}return(i=(await B.getShadowGraphqlClient().mutate({mutation:vl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:r.name,layouts:r.layouts,workflowId:r.workflowId,transactionId:r.transactionId,previewImage:r.previewImage,useThreeDimPreview:r.useThreeDimPreview,metadata:r.metadata,selectedVariants:r.selectedVariants},context:{headers:e}})).data)==null?void 0:i.designCreate},Bl=async(r,t)=>{var n,i;const e={};try{if(t){const s=await t.loggedInBearerToken();e.Authorization=`Bearer ${s}`}else throw new Error}catch{const l=((n=Object.entries(localStorage).find(([d,A])=>d.startsWith("CognitoIdentityServiceProvider")&&d.endsWith("idToken")))==null?void 0:n[0])||"",c=localStorage.getItem(l);c&&!_t(c)&&(e.Authorization=`Bearer ${c}`)}return(i=(await B.getShadowGraphqlClient().mutate({mutation:El,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:r.map(s=>({name:s.name,layouts:s.layouts,workflowId:s.workflowId,transactionId:s.transactionId,previewImage:s.previewImage,useThreeDimPreview:s.useThreeDimPreview,metadata:s.metadata,selectedVariants:s.selectedVariants}))},context:{headers:e}})).data)==null?void 0:i.designCreateMany},pa=(r,t,e)=>{const a=i=>{const s={};if(i.type==="Frame"){const o=r[i.stepName],l=i.data;if(!o||!o.image||l.hideImageInCart&&e)return s;s[`${i.stepTitle} image`]=o.image}if(i.type==="Illustration"){const o=r[i.stepName],l=i.data;if(!o||l.hideColorsInCart&&e||!o.colors)return s;if(o.colors.length>0){const c=o.colors.join(", ").toUpperCase();s[`${i.stepTitle} colors`]=c}}if(i.type==="Module"){const o=r[i.stepName],l=i.data;if(!o||o.text===void 0||o.text===null||l.hideTextInCart&&e)return s;s[`${i.stepTitle} text`]=o.text}if(i.type==="Text"){const o=r[i.stepName];if(!o)return s;const l=i.data;(!l.hideTextInCart||!e&&o.text!==void 0&&o.text!==null)&&(s[`${i.stepTitle} text`]=o.text),o.color&&(!l.hideColorInCart||!e)&&(s[`${i.stepTitle} color`]=o.color),o.strokeColor&&(!l.hideStrokeInCart||!e)&&(s[`${i.stepTitle} stroke`]=o.strokeColor)}return s},n={};return t.steps.forEach(i=>{Object.assign(n,a(i))}),n},Il=(r,t,e,a)=>{const n={};let i={};e?i=pa(e,t,!1):a&&(i=a);const o=t.steps.map(l=>l.stepTitle).filter((l,c,d)=>d.indexOf(l)==c);for(const l of o){if(Object.keys(r).includes(l)){const c=r[l],d=t.steps.find(A=>A.stepTitle===l);n[`${d==null?void 0:d.stepTitle} selection`]={value:c[0].name,priceModifier:c[0].priceModifier}}for(const c of Object.keys(i))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(c)&&(n[c]={value:i[c],priceModifier:0})}return n},Ir=(r,t,e,a,n,i,s,o)=>{var g,m;const l=t.basePrice||0,c=r.priceModifierTotal||0,d=Il(a,e,void 0,i),u=(T.getMap("transactionOwnerIds")||new Map).get(r.id),h={additionalExternalProductId:(g=r.integrationProduct)==null?void 0:g.additionalExternalProductId,additionalExternalVariantId:(m=r.integrationProduct)==null?void 0:m.additionalExternalVariantId,baseCost:l,designExternalVariants:r.designExternalVariants,designProductId:r.externalDesignProductId,designProductVariantId:r.externalDesignProductVariantId,event:"onComplete",exportedData:d,externalCartProductId:r.externalCartProductId,externalCartProductVariantId:r.externalCartProductVariantId,lineItemImageUrl:s||"",optionsCost:c,processExecutionId:o,quantity:r.quantity,transactionId:r.id,transactionOwnerId:u,weight:t.weight,workflowViewerLink:r.workflowViewerLink||"",workflowViewerReadOnlyLink:r.workflowViewerReadOnlyLink||""};return i&&(h.metadata=i),a&&(h.selectedVariants=a),n&&(h.sku=n),h},Pr=async(r,t,e,a,n,i,s,o,l,c)=>{var I;await(async()=>{var R;if(c!==void 0)return c;await r.outstandingRequestsPromise();const F=(T.getMap("transactionOwnerIds")||new Map).get(n.id),N=await B.getShadowGraphqlClient().query({query:Yn,variables:{ids:[n.id]},fetchPolicy:"no-cache",errorPolicy:"all",context:{transactionOwnerId:F}}),rt=(R=N.data)==null?void 0:R.transactions[0].workflowState;return N.errors?(N.errors.forEach(et=>{N.errors&&console.log("Server Error:",et.message)}),null):rt??null})()||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(a())),await r.updateStateWithServerImmediate(a),console.log("Server state is undefined @ Workflow completion"));const u=r.getPreviewService(),h=(I=t==null?void 0:t.finalizeStepConfig)==null?void 0:I.lookAtAnimation,g=u&&t.showModelOnFinishStep&&!!h,m=l&&pa(l,t,!0),p=l&&pa(l,t,!1),f=async x=>{const F={};let k=0;if(Object.keys(i).length>0)for(const N of Object.keys(i)){const rt=i[N],R=t.steps.find(et=>et.stepName===N);for(let et=0;et<rt.selections.length;++et){const Z=rt.selections[et];if(R&&(!x||R.option&&(R.option.variants||[]).length>1&&!R.data.hideSelectionInCart&&!R.data.hideSelectionsInCart)){const Ut=R.stepTitle;F[Ut]?F[Ut].push({id:Z.id||"",name:Z.name,priceModifier:Z.priceModifier}):F[Ut]=[{id:Z.id||"",name:Z.name,priceModifier:Z.priceModifier}]}k+=Z.priceModifier}}return[F,k]},[C]=await f(!0),w=Object.fromEntries(Object.keys(C).map(x=>[x,C[x].map(F=>F.id)])),[S]=await f(!1),y=Object.fromEntries(Object.keys(S).map(x=>[x,S[x].map(F=>F.id)]));let E=await o(g,n.id);if(E){const x=await(await st(E)).blob();E=(await U.uploadAsset({name:`${n.id}-preview-image.png`,blob:x},Xt.Image,!0,!1)).fileLink}return{designDetails:(()=>{const x={name:s,layouts:e.map(F=>({index:F.index,panelId:F.panelId})),workflowId:t.id,transactionId:n.id,useThreeDimPreview:!!g,previewImage:E};if(p){const F=[];for(const[k,N]of Object.entries(p))F.push({key:k,value:N});x.metadata=F}if(w){const F=[];for(const[k,N]of Object.entries(y))F.push({key:k,ids:N});x.selectedVariants=F}return x})(),cartSelectionsWithPrices:C,cartMetadata:m}},Dr=async(r,t,e,a,n,i,s,o,l,c,d)=>{var f,C;l("workflow.steps.finish.finalize.buildingLayouts");const{designDetails:A,cartSelectionsWithPrices:u,cartMetadata:h}=await Pr(r,t,e,a,i,s,o,c,d);l("workflow.steps.finish.finalize.creatingDesign");const g=await bl(A),m=(f=g==null?void 0:g.transaction)==null?void 0:f.previewImageLink;if(!(g!=null&&g.transaction))throw new Error("Failed to create design");l("workflow.steps.finish.finalize.updatingTransaction");const p=g.transaction;return Ir(p,n,t,u,g==null?void 0:g.sku,h,m,(C=g==null?void 0:g.processExecution)==null?void 0:C.id)},Pl=async(r,t,e)=>{t("workflow.steps.finish.finalize.buildingLayouts"),await Promise.all(r.map(async o=>{await o.workflowManager.outstandingRequestsPromise()}));const n=await(async()=>{var c;const l=await B.getShadowGraphqlClient().query({query:Yn,variables:{ids:r.map(d=>d.transaction.id)},fetchPolicy:"no-cache",errorPolicy:"all"});return l.errors?(l.errors.forEach(d=>{l.errors&&console.log("Server Error:",d.message)}),null):(c=l.data)!=null&&c.transactions?l.data.transactions.map(d=>d.workflowState??null):null})(),i=await Promise.all(r.map(async(o,l)=>await Pr(o.workflowManager,o.workflow,o.layouts,o.getReducerState,o.transaction,o.workflowSelections,o.designName,e??(()=>Promise.resolve(void 0)),o.workflowMetadata,n?n[l]:void 0)));t("workflow.steps.finish.finalize.creatingDesign");const s=await Bl(i.map(o=>o.designDetails));if(!s)throw new Error("Failed to create designs");return t("workflow.steps.finish.finalize.updatingTransaction"),s.map((o,l)=>{var u;const c=r[l],d=i[l],A=o.transaction;return Ir(A,c.product,c.workflow,d.cartSelectionsWithPrices,o.sku,d.cartMetadata,A.previewImageLink,(u=o.processExecution)==null?void 0:u.id)})};class Dl{constructor(){this.localPersistenceKey="designTransactions",this.storageMethod="Local",this.designSavedListeners=[]}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter(e=>e!==t)}async getSavedDesigns(){if(this.storageMethod==="Local"){const t=T.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new z("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find(a=>a.transactionId===t)}async addDesign(t){const a=(await this.getSavedDesigns()).filter(n=>n.transactionId!==t.transactionId);a.unshift(t),await this.setDesigns(a),this.designSavedListeners.forEach(n=>n(t))}async renameDesign(t,e){const a=await this.getSavedDesigns(),n=a.find(i=>i.transactionId===t);if(!n)throw new Error(`No saved design for transaction ${t}.`);n.title=e,await this.setDesigns(a)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter(a=>a.transactionId!==t))}async setDesigns(t){if(this.storageMethod==="Local"){T.set(this.localPersistenceKey,JSON.stringify(t));return}throw new z("Unexpected storage method requested")}}const Ee=new Dl,xl=v.gql`
2199
+ `;function _t(r){const t=JSON.parse(atob(r.split(".")[1])).exp;return Math.floor(new Date().getTime()/1e3)>=t}const bl=async(r,t)=>{var n,i;const e={};try{if(t){const s=await t.loggedInBearerToken();e.Authorization=`Bearer ${s}`}else throw new Error}catch{const l=((n=Object.entries(localStorage).find(([d,A])=>d.startsWith("CognitoIdentityServiceProvider")&&d.endsWith("idToken")))==null?void 0:n[0])||"",c=localStorage.getItem(l);c&&!_t(c)&&(e.Authorization=`Bearer ${c}`)}return(i=(await B.getShadowGraphqlClient().mutate({mutation:vl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{name:r.name,layouts:r.layouts,workflowId:r.workflowId,transactionId:r.transactionId,previewImage:r.previewImage,useThreeDimPreview:r.useThreeDimPreview,metadata:r.metadata,selectedVariants:r.selectedVariants},context:{headers:e}})).data)==null?void 0:i.designCreate},Bl=async(r,t)=>{var n,i;const e={};try{if(t){const s=await t.loggedInBearerToken();e.Authorization=`Bearer ${s}`}else throw new Error}catch{const l=((n=Object.entries(localStorage).find(([d,A])=>d.startsWith("CognitoIdentityServiceProvider")&&d.endsWith("idToken")))==null?void 0:n[0])||"",c=localStorage.getItem(l);c&&!_t(c)&&(e.Authorization=`Bearer ${c}`)}return(i=(await B.getShadowGraphqlClient().mutate({mutation:El,errorPolicy:"all",fetchPolicy:"no-cache",variables:{inputs:r.map(s=>({name:s.name,layouts:s.layouts,workflowId:s.workflowId,transactionId:s.transactionId,previewImage:s.previewImage,useThreeDimPreview:s.useThreeDimPreview,metadata:s.metadata,selectedVariants:s.selectedVariants}))},context:{headers:e}})).data)==null?void 0:i.designCreateMany},pa=(r,t,e)=>{const a=i=>{const s={};if(i.type==="Frame"){const o=r[i.stepName],l=i.data;if(!o||!o.image||l.hideImageInCart&&e)return s;s[`${i.stepTitle} image`]=o.image}if(i.type==="Illustration"){const o=r[i.stepName],l=i.data;if(!o||l.hideColorsInCart&&e||!o.colors)return s;if(o.colors.length>0){const c=o.colors.join(", ").toUpperCase();s[`${i.stepTitle} colors`]=c}}if(i.type==="Module"){const o=r[i.stepName],l=i.data;if(!o||o.text===void 0||o.text===null||l.hideTextInCart&&e)return s;s[`${i.stepTitle} text`]=o.text}if(i.type==="Text"){const o=r[i.stepName];if(!o)return s;const l=i.data;(!l.hideTextInCart||!e&&o.text!==void 0&&o.text!==null)&&(s[`${i.stepTitle} text`]=o.text),o.color&&(!l.hideColorInCart||!e)&&(s[`${i.stepTitle} color`]=o.color),o.strokeColor&&(!l.hideStrokeInCart||!e)&&(s[`${i.stepTitle} stroke`]=o.strokeColor)}return s},n={};return t.steps.forEach(i=>{Object.assign(n,a(i))}),n},Il=(r,t,e,a)=>{const n={};let i={};e?i=pa(e,t,!1):a&&(i=a);const o=t.steps.map(l=>l.stepTitle).filter((l,c,d)=>d.indexOf(l)==c);for(const l of o){if(Object.keys(r).includes(l)){const c=r[l],d=t.steps.find(A=>A.stepTitle===l);n[`${d==null?void 0:d.stepTitle} selection`]={value:c[0].name,priceModifier:c[0].priceModifier}}for(const c of Object.keys(i))[`${l} color`,`${l} colors`,`${l} text`,`${l} image`].includes(c)&&(n[c]={value:i[c],priceModifier:0})}return n},Ir=(r,t,e,a,n,i,s,o)=>{var g,m;const l=t.basePrice||0,c=r.priceModifierTotal||0,d=Il(a,e,void 0,i),u=(T.getMap("transactionOwnerIds")||new Map).get(r.id),h={additionalExternalProductId:(g=r.integrationProduct)==null?void 0:g.additionalExternalProductId,additionalExternalVariantId:(m=r.integrationProduct)==null?void 0:m.additionalExternalVariantId,baseCost:l,designExternalVariants:r.designExternalVariants,designProductId:r.externalDesignProductId,designProductVariantId:r.externalDesignProductVariantId,event:"onComplete",exportedData:d,externalCartProductId:r.externalCartProductId,externalCartProductVariantId:r.externalCartProductVariantId,lineItemImageUrl:s||"",optionsCost:c,processExecutionId:o,quantity:r.quantity,transactionId:r.id,transactionOwnerId:u,weight:t.weight,workflowViewerLink:r.workflowViewerLink||"",workflowViewerReadOnlyLink:r.workflowViewerReadOnlyLink||""};return i&&(h.metadata=i),a&&(h.selectedVariants=a),n&&(h.sku=n),h},Pr=async(r,t,e,a,n,i,s,o,l,c)=>{var I;await(async()=>{var R;if(c!==void 0)return c;await r.outstandingRequestsPromise();const F=(T.getMap("transactionOwnerIds")||new Map).get(n.id),N=await B.getShadowGraphqlClient().query({query:Yn,variables:{ids:[n.id]},fetchPolicy:"no-cache",errorPolicy:"all",context:{transactionOwnerId:F}}),rt=(R=N.data)==null?void 0:R.transactions[0].workflowState;return N.errors?(N.errors.forEach(et=>{N.errors&&console.log("Server Error:",et.message)}),null):rt??null})()||(console.warn("State mismatch detected. Uploading known state explicitly"),console.warn("State Object:",JSON.stringify(a())),await r.updateStateWithServerImmediate(a),console.log("Server state is undefined @ Workflow completion"));const u=r.getPreviewService(),h=(I=t==null?void 0:t.finalizeStepConfig)==null?void 0:I.lookAtAnimation,g=u&&t.showModelOnFinishStep&&!!h,m=l&&pa(l,t,!0),p=l&&pa(l,t,!1),f=async x=>{const F={};let k=0;if(Object.keys(i).length>0)for(const N of Object.keys(i)){const rt=i[N],R=t.steps.find(et=>et.stepName===N);for(let et=0;et<rt.selections.length;++et){const X=rt.selections[et];if(R&&(!x||R.option&&(R.option.variants||[]).length>1&&!R.data.hideSelectionInCart&&!R.data.hideSelectionsInCart)){const Ut=R.stepTitle;F[Ut]?F[Ut].push({id:X.id||"",name:X.name,priceModifier:X.priceModifier}):F[Ut]=[{id:X.id||"",name:X.name,priceModifier:X.priceModifier}]}k+=X.priceModifier}}return[F,k]},[C]=await f(!0),w=Object.fromEntries(Object.keys(C).map(x=>[x,C[x].map(F=>F.id)])),[S]=await f(!1),y=Object.fromEntries(Object.keys(S).map(x=>[x,S[x].map(F=>F.id)]));let E=await o(g,n.id);if(E){const x=await(await st(E)).blob();E=(await U.uploadAsset({name:`${n.id}-preview-image.png`,blob:x},Xt.Image,!0,!1)).fileLink}return{designDetails:(()=>{const x={name:s,layouts:e.map(F=>({index:F.index,panelId:F.panelId})),workflowId:t.id,transactionId:n.id,useThreeDimPreview:!!g,previewImage:E};if(p){const F=[];for(const[k,N]of Object.entries(p))F.push({key:k,value:N});x.metadata=F}if(w){const F=[];for(const[k,N]of Object.entries(y))F.push({key:k,ids:N});x.selectedVariants=F}return x})(),cartSelectionsWithPrices:C,cartMetadata:m}},Dr=async(r,t,e,a,n,i,s,o,l,c,d)=>{var f,C;l("workflow.steps.finish.finalize.buildingLayouts");const{designDetails:A,cartSelectionsWithPrices:u,cartMetadata:h}=await Pr(r,t,e,a,i,s,o,c,d);l("workflow.steps.finish.finalize.creatingDesign");const g=await bl(A),m=(f=g==null?void 0:g.transaction)==null?void 0:f.previewImageLink;if(!(g!=null&&g.transaction))throw new Error("Failed to create design");l("workflow.steps.finish.finalize.updatingTransaction");const p=g.transaction;return Ir(p,n,t,u,g==null?void 0:g.sku,h,m,(C=g==null?void 0:g.processExecution)==null?void 0:C.id)},Pl=async(r,t,e)=>{t("workflow.steps.finish.finalize.buildingLayouts"),await Promise.all(r.map(async o=>{await o.workflowManager.outstandingRequestsPromise()}));const n=await(async()=>{var c;const l=await B.getShadowGraphqlClient().query({query:Yn,variables:{ids:r.map(d=>d.transaction.id)},fetchPolicy:"no-cache",errorPolicy:"all"});return l.errors?(l.errors.forEach(d=>{l.errors&&console.log("Server Error:",d.message)}),null):(c=l.data)!=null&&c.transactions?l.data.transactions.map(d=>d.workflowState??null):null})(),i=await Promise.all(r.map(async(o,l)=>await Pr(o.workflowManager,o.workflow,o.layouts,o.getReducerState,o.transaction,o.workflowSelections,o.designName,e??(()=>Promise.resolve(void 0)),o.workflowMetadata,n?n[l]:void 0)));t("workflow.steps.finish.finalize.creatingDesign");const s=await Bl(i.map(o=>o.designDetails));if(!s)throw new Error("Failed to create designs");return t("workflow.steps.finish.finalize.updatingTransaction"),s.map((o,l)=>{var u;const c=r[l],d=i[l],A=o.transaction;return Ir(A,c.product,c.workflow,d.cartSelectionsWithPrices,o.sku,d.cartMetadata,A.previewImageLink,(u=o.processExecution)==null?void 0:u.id)})};class Dl{constructor(){this.localPersistenceKey="designTransactions",this.storageMethod="Local",this.designSavedListeners=[]}attachSaveListener(t){this.designSavedListeners.push(t)}detachSaveListener(t){this.designSavedListeners=this.designSavedListeners.filter(e=>e!==t)}async getSavedDesigns(){if(this.storageMethod==="Local"){const t=T.get(this.localPersistenceKey);return t?JSON.parse(t):[]}throw new z("Unexpected storage method requested")}async getSavedDesignByTransaction(t){return(await this.getSavedDesigns()).find(a=>a.transactionId===t)}async addDesign(t){const a=(await this.getSavedDesigns()).filter(n=>n.transactionId!==t.transactionId);a.unshift(t),await this.setDesigns(a),this.designSavedListeners.forEach(n=>n(t))}async renameDesign(t,e){const a=await this.getSavedDesigns(),n=a.find(i=>i.transactionId===t);if(!n)throw new Error(`No saved design for transaction ${t}.`);n.title=e,await this.setDesigns(a)}async removeDesign(t){const e=await this.getSavedDesigns();await this.setDesigns(e.filter(a=>a.transactionId!==t))}async setDesigns(t){if(this.storageMethod==="Local"){T.set(this.localPersistenceKey,JSON.stringify(t));return}throw new z("Unexpected storage method requested")}}const Ee=new Dl,xl=v.gql`
2200
2200
  mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
2201
2201
  transactionAddStakeholder(id: $id, details: $details, type: $type) {
2202
2202
  id
@@ -2259,7 +2259,7 @@
2259
2259
  />
2260
2260
  </svg>
2261
2261
  `,g={"spiff-fill-shape":{browserValue:s.color||"#000000"}},m=Q();return new q({colors:g,id:m,svg:u,type:M.Illustration,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable},A)},l=a.data.regions;try{return l.map(o)}catch(d){return console.error(d),[]}},Ul=async(r,t,e)=>{const a=[],i=(()=>{var c,d;return t.type===P.ProductOverlay?e||((c=t.data.asset)==null?void 0:c.fileLink)||"":((d=t.data.asset)==null?void 0:d.fileLink)||""})(),o=(()=>i.endsWith(".jpeg")||i.endsWith(".jpg")||i.endsWith(".png")?M.Image:(i.endsWith(".svg"),M.Illustration))(),l=t.data.regions;if(o==="image")try{l.forEach(c=>{const d=r.find(u=>u.panelId===c.panelId);if(!d)throw new Y(c);const A={id:Q(),src:i,type:o,y:c.top,x:c.left,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,productOverlay:t.type===P.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:c.rotation,excludeFromExport:t.data.excludeFromPrint,preserveAspectRatio:"none"};a.push(new q(A,d))})}catch(c){console.error(c)}else{const c=await tt(i,!0),d=A=>{const u=/<svg.*?<\/svg>/s,h=A.match(u)||[],g=(h==null?void 0:h.length)>0?h[0]:"",f=ct().parseFromString(g,"image/svg+xml").firstElementChild;if(!f)throw new St("Failed to read SVG.");return Oe(f),wt().serializeToString(f)};l.forEach(A=>{const u=r.find(g=>g.panelId===A.panelId);if(!u)throw new Y(A);const h={id:Q(),src:i,asset_key:i,svg:d(c),colors:{},type:o,y:A.top,x:A.left,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,scaleX:1,scaleY:1,rotation:A.rotation,productOverlay:t.type===P.ProductOverlay?!0:void 0,excludeFromExport:t.data.excludeFromPrint};a.push(new q(h,u))})}return a},Ll=async(r,t,e,a)=>{const n=[],i=e.data,s=30,o=p=>p.vertical?"center":p.textAlign||"center",l=()=>{var w;const p=a.option;if(!p)return;const f=((w=p.variants)==null?void 0:w.find(S=>S.id===i.fontVariantId))||de(p);if(!f||!f.asset)return;t[a.stepName]={selectedVariants:[f]};const C=f.asset.fileLink;if(C)return C},d=await(async()=>{const p=l();if(!p)return;const f=await It(p);return{assetUrl:p,name:f.names.fullName.en}})(),A=(a.data.replaceableText?a.data.replaceableText.replace("{{}}",i.text):i.text)||"",u=Pe(A,{vertical:a.data.vertical,uppercase:a.data.uppercase}),h=async p=>{const f=p.colorOption;if(!f)return;const C=H.getDefaultVariant(f);return C==null?void 0:C.color},g=i.color||await h(a.data),m=a.data.regions;for(const p of m){const f=r.find(w=>w.panelId===p.panelId);if(!f)continue;const C={stepName:e.name,id:Q(),align:o(a.data),curved:a.data.curved,fill:i.color||g||"#000000",fontData:d,fontSize:a.data.size||s,height:p.height,layer:p.layer,layerIndex:p.layerIndex,paths:a.data.paths,rotation:p.rotation,text:u,type:M.Textbox,vertical:a.data.vertical,verticalAlign:a.data.verticalAlign||"middle",width:p.width,x:p.left,y:p.top};if(d){const[w,S]=Kt(a.data.size||s,d,p,[Pe(u,{vertical:a.data.vertical,uppercase:a.data.uppercase})],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});n.push(new q({...C,fontSize:w,text:C.curved?C.text:(S||[]).join(`
2262
- `)},f))}else n.push(new q(C,f))}return n},Vl=(r,t)=>r.conditions?r.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const n=a.selectedVariants;return e.requiredVariantSelections.some(i=>n.find(s=>s.id===i)!==void 0)}return!1}):!0,kr=async(r,t,e,a)=>{const n=[],i={};for(const s of r){const o=t.steps.find(l=>l.stepName===s.name);if(o)switch(o.type){case P.DigitalContent:n.push(...await Tl(e,s,o));break;case P.Frame:case P.Photo:n.push(...await Nl(e,i,s,o));break;case P.Illustration:n.push(...await Ql(e,i,s,o));break;case P.Module:n.push(...await Rl(e,s,o));break;case P.Picture:n.push(...await Ol(e,i,s,o));break;case P.Shape:n.push(...await $l(e,i,s,o));break;case P.Text:n.push(...await Ll(e,i,s,o));break}}for(const s of t.steps)s.type!==P.SilentIllustration&&s.type!==P.ProductOverlay||Vl(s,i)&&n.push(...await Ul(e,s,a));return n};class zl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Wl(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Gl=()=>new Promise((r,t)=>{try{const a=pt().getContext("webgl2");r(!!a)}catch{r(!1)}}),ql=Gl();class Wl{constructor(t,e,a,n,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Pa(2),this.id=t,this.name=e,this.service=a,this.panelSize=n,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=Et(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new jl(this.getID(),a,await ql,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class jl extends Ia{constructor(t,e,a,n,i,s){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=n,this.layouts=i,this.getWorkflowManager=s}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,n=e/t.height,i=Math.min(a,n);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){var h,g;const t=this.layouts.find(m=>m.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,n=t.layoutState.layout.height,i=a===1||n===1?{width:1,height:1}:this.getDynamicTextureResolution(),s=i.width,o=i.height;let l,c;if(this.nonPOTSupport){const m=s/o;a/n<m?(l=s,c=n*(s/a)):(l=a*(o/n),c=o);const f=this.resizeFit({width:l,height:c});l=f.width,c=f.height}else l=i.width,c=i.height;const d=Ve(t.layoutState.layout,e,{renderingConfiguration:{purpose:Tt.ThreeD,templatingContext:(g=(h=this.getWorkflowManager)==null?void 0:h.call(this))==null?void 0:g.getTemplatingContext()}}),A=Mn(d),u=await ya.Pith.from(this.ctx,A,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:pt,createImage:se,DOMParser:Ea(),fetch});u.resize(l,c),await u.render(),this.onRender()}}const Hl=(r,t)=>{const e=[];return r.forEach(a=>{const n=t.steps.find(i=>i.stepName===a.stepName);(n==null?void 0:n.type)===P.Text&&a.stepAspectType==="Text"&&e.push({name:n.stepName,data:{text:a.value}})}),e},Yl=async(r,t,e,a)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};n=new $(e.map(l=>new Ta(l))).apply(n);const s=await kr(r,t,e,a);return new $(s).apply(n)};class Jl{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){var e;if(!((e=this.bundle.getProductCollection())!=null&&e.getResource().globalPropertyConfiguration))return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(a=>this.getHandle(a)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const n=e.aspects.find(i=>i.name===a.targetAspectName);return n?a.requiredVariantSelections.some(i=>i===n.value):!1})}async createHandle(t){switch(t.type){case V.FileUpload:return new Mr(this.bundle,t).initialize();case V.ColorOption:return new fa(this.bundle,t,t.entityId?await H.getOption(t.entityId):void 0);case V.Option:{const e=t.entityId?await H.getOption(t.entityId):void 0;return(e==null?void 0:e.type)==="Color"?new fa(this.bundle,t,e):new Va(this.bundle,t,e)}case V.Text:return new Tr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class ze{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(n=>n.getStepsConditionallyActive().filter(i=>{var s;return i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:(s=i.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name})}))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Mr extends ze{constructor(t,e){super(t,e)}async initialize(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorOptionId&&(this.colorOption=await H.getOption((n=(a=this.property.data)==null?void 0:a.fileUpload)==null?void 0:n.colorOptionId)),await this.loadImageData(),this}async loadImageData(){var e;const t=await this.getImage();if(t!=null&&t.fileLink)if(t!=null&&t.fileLink.endsWith(".svg")){const a=await tt(t==null?void 0:t.fileLink),n=await ka(t==null?void 0:t.fileLink),i=n.width,s=n.height,o=await ot(a),l=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);(e=l==null?void 0:l.colors)==null||e.forEach(d=>{o.colors[d.key]={browserValue:d.browserValue,pmsValue:d.pmsValue}});const c={src:t==null?void 0:t.fileLink,width:i,height:s,aspect:i/s,svg:o.svg,colors:o.colors};dt.set(t==null?void 0:t.fileLink,c),this.imageData=c}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(ke.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await U.removeBackgroundFromAsset(e),s={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,s):a.setAspectStorage(this.property.name,s)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return U.getLocalOrFromServer(t)}async getImageWithColors(){var t,e;return await this.loadImageData(),(t=this.imageData)!=null&&t.svg?Re($e(this.imageData.svg,this.imageData.colors??{},!1)):(e=this.imageData)==null?void 0:e.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.originalAssetKey)return U.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.backgroundRemovedAssetKey)return U.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){var t;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.useOriginalAsset)??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if((n==null?void 0:n.useOriginalAsset)===t)return;const i={...n,useOriginalAsset:t},s=t?n==null?void 0:n.originalAssetKey:n==null?void 0:n.backgroundRemovedAssetKey,o=[a.setAspect(this.property.name,s||"",i)];if(t)o.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};o.push(l())}o.push(this.loadImageData()),await Promise.all(o),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await U.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const i=new Map(n.colors.map(s=>[s.key,{browserValue:s.browserValue,pmsValue:s.pmsValue}])??[]);this.getSharedSteps(t).forEach(s=>{s.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorPickerEnabled?((n=(a=this.colorOption)==null?void 0:a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})))??[]:[]}getCurrentColors(){var t;return(t=this.imageData)==null?void 0:t.colors}isColorPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.colorPickerEnabled)??!1}isPmsPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.pmsPickerEnabled)??!1}async getOriginalColors(){var e;return(e=this.imageData)!=null&&e.svg?(await ot(this.imageData.svg)).colors:void 0}async changeColors(t){var i;if(!((i=this.imageData)!=null&&i.svg))return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(s=>{s.changeColors(a)});const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([s,o])=>({key:s,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const s=this.getSharedSteps(e).map(o=>{const l=o;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(s)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{var s;if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;((s=n.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name}))&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Tr extends ze{constructor(t,e){super(t,e)}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(n)}}class Va extends ze{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){var e,a;console.log(`LOG: attempting to init default variant for property ${this.property.name}`);const t=(a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.find(n=>{var i,s;return n.id===((s=(i=this.optionResource)==null?void 0:i.defaultVariant)==null?void 0:s.id)});t&&(console.log("LOG: found one"),await this.selectVariant(new it(t)))}getCurrentVariant(){var e,a;if(!this.optionResource)return;const t=this.getStateValue();if(t){const n=(a=this.optionResource.variants)==null?void 0:a.find(i=>i.id===t);return n?new it(n):void 0}else{const n=(e=this.optionResource.variants)==null?void 0:e.find(i=>{var s,o;return i.id===((o=(s=this.optionResource)==null?void 0:s.defaultVariant)==null?void 0:o.id)});return n?new it(n):void 0}}getAvailableVariants(){var e,a;return(((a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.filter(n=>n.enabled))||[]).map(n=>new it(n))}getAllVariants(){var e;return(((e=this.optionResource)==null?void 0:e.variants)||[]).map(a=>new it(a))}async selectVariant(t,e){console.log(`LOG: selecting variant ${t.getName()} (${t.getId()}) for property ${this.property.name}`),console.trace(),await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){var n,i;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(i=(n=this.optionResource)==null?void 0:n.variants)==null?void 0:i.find(s=>s.id===e);return a?this.applyVariantSelection(new it(a),t):Promise.resolve()}async applyVariantSelection(t,e){const n=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(n)}}class fa extends Va{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){console.log(`LOG: selecting color variant ${t.getName()} (${t.getId()}) for property ${this.property.name}`),console.trace(),await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyColorVariant(t,void 0,e)])}async applyGlobalState(t){var i,s,o;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(s=(i=this.optionResource)==null?void 0:i.variants)==null?void 0:s.find(l=>l.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new it(a),t);const n=(o=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:o.customColor;n&&this.setCustomColor(n)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(s=>{switch(s.getType()){case P.Shape:return s.selectVariant(t);case P.Text:return s.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case P.Illustration:return s.setColor((a==null?void 0:a.toString())||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){var t,e;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.customColor)||((e=this.getCurrentVariant())==null?void 0:e.getColor())||"#ffffff"}}const Kl=(r,t,e,a)=>r.flatMap(n=>n.getSteps()).filter(n=>n.getGlobalPropertyAspects(t).includes(e)&&n.getType()===a),_l=(r,t,e)=>{const n=Kl(r,t,e,P.Illustration).map(i=>{var l;const s=(l=i.getCurrentVariant())==null?void 0:l.getAssetResource(),o=i.getColors();return!(s!=null&&s.assetConfiguration)||!o?0:Object.getOwnPropertyNames(o).length});return Math.max(...n)};class Xl{constructor(t,e,a,n,i){this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const s=i==null?void 0:i.existingGlobalPropertyState;this.initPromise=s?Promise.resolve(s).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=s}):this.createGlobalPropertyState().then(o=>{console.log("Setting global property state to new state."),this.globalPropertyState=o}),this.onGlobalPropertyStateChange=n}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=Et(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){var a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e))==null?void 0:a.storage}async setAspect(t,e,a,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);const s=Et(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(l=>l.name===t);if(o.length>0)if(n){const l=o.find(c=>c.channel===n);if(l)l.value=e,l.type=i.type,l.channel=n,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(n===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n})}}else{const l=o[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(s,this.globalPropertyState)}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(o=>o.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=Et(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(o=>o.name===t);if(s.length>0)if(a){const o=s.find(l=>l.channel===a);o&&(o.storage=e!==null?e:void 0,o.type=n.type)}else{const o=s[0];o.storage=e!==null?e:void 0,o.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async updateGlobalPropertyState(){var e,a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await B.getShadowGraphqlClient().mutate({mutation:Go,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(n=>{let i=n.type&&n.storage?{}:void 0;if(i)switch(n.type){case V.FileUpload:{i.fileUpload=n.storage;break}case V.Option:{i.option=n.storage;break}case V.ColorOption:{i=n.storage;break}}return{name:n.name,value:n.value,type:n.type,storage:i,channel:n.channel}})},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 createGlobalPropertyState(){var e,a;const t=await B.getShadowGraphqlClient().mutate({mutation:zo,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.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}`)}}class Zl{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 n=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=n.position,i.rotation=n.rotation,i.scale=n.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(s=>s.transactionId===n);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:n,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){var l,c;if(!((l=t==null?void 0:t.getWorkflowManager())!=null&&l.getModelContainer())||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,n=this.state.transactions.find(d=>d.transactionId===a),i=(c=n==null?void 0:n.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,n.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const tc=v.gql`
2262
+ `)},f))}else n.push(new q(C,f))}return n},Vl=(r,t)=>r.conditions?r.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const n=a.selectedVariants;return e.requiredVariantSelections.some(i=>n.find(s=>s.id===i)!==void 0)}return!1}):!0,kr=async(r,t,e,a)=>{const n=[],i={};for(const s of r){const o=t.steps.find(l=>l.stepName===s.name);if(o)switch(o.type){case P.DigitalContent:n.push(...await Tl(e,s,o));break;case P.Frame:case P.Photo:n.push(...await Nl(e,i,s,o));break;case P.Illustration:n.push(...await Ql(e,i,s,o));break;case P.Module:n.push(...await Rl(e,s,o));break;case P.Picture:n.push(...await Ol(e,i,s,o));break;case P.Shape:n.push(...await $l(e,i,s,o));break;case P.Text:n.push(...await Ll(e,i,s,o));break}}for(const s of t.steps)s.type!==P.SilentIllustration&&s.type!==P.ProductOverlay||Vl(s,i)&&n.push(...await Ul(e,s,a));return n};class zl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Wl(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Gl=()=>new Promise((r,t)=>{try{const a=pt().getContext("webgl2");r(!!a)}catch{r(!1)}}),ql=Gl();class Wl{constructor(t,e,a,n,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Pa(2),this.id=t,this.name=e,this.service=a,this.panelSize=n,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=Et(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new jl(this.getID(),a,await ql,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class jl extends Ia{constructor(t,e,a,n,i,s){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=n,this.layouts=i,this.getWorkflowManager=s}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,n=e/t.height,i=Math.min(a,n);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){var h,g;const t=this.layouts.find(m=>m.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,n=t.layoutState.layout.height,i=a===1||n===1?{width:1,height:1}:this.getDynamicTextureResolution(),s=i.width,o=i.height;let l,c;if(this.nonPOTSupport){const m=s/o;a/n<m?(l=s,c=n*(s/a)):(l=a*(o/n),c=o);const f=this.resizeFit({width:l,height:c});l=f.width,c=f.height}else l=i.width,c=i.height;const d=Ve(t.layoutState.layout,e,{renderingConfiguration:{purpose:Tt.ThreeD,templatingContext:(g=(h=this.getWorkflowManager)==null?void 0:h.call(this))==null?void 0:g.getTemplatingContext()}}),A=Mn(d),u=await ya.Pith.from(this.ctx,A,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:pt,createImage:se,DOMParser:Ea(),fetch});u.resize(l,c),await u.render(),this.onRender()}}const Hl=(r,t)=>{const e=[];return r.forEach(a=>{const n=t.steps.find(i=>i.stepName===a.stepName);(n==null?void 0:n.type)===P.Text&&a.stepAspectType==="Text"&&e.push({name:n.stepName,data:{text:a.value}})}),e},Yl=async(r,t,e,a)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};n=new $(e.map(l=>new Ta(l))).apply(n);const s=await kr(r,t,e,a);return new $(s).apply(n)};class Jl{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){var e;if(!((e=this.bundle.getProductCollection())!=null&&e.getResource().globalPropertyConfiguration))return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(a=>this.getHandle(a)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const n=e.aspects.find(i=>i.name===a.targetAspectName);return n?a.requiredVariantSelections.some(i=>i===n.value):!1})}async createHandle(t){switch(t.type){case V.FileUpload:return new Mr(this.bundle,t).initialize();case V.ColorOption:return new fa(this.bundle,t,t.entityId?await H.getOption(t.entityId):void 0);case V.Option:{const e=t.entityId?await H.getOption(t.entityId):void 0;return(e==null?void 0:e.type)==="Color"?new fa(this.bundle,t,e):new Va(this.bundle,t,e)}case V.Text:return new Tr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class ze{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(n=>n.getSteps().filter(s=>{var o;return s.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:(o=s.getRaw().globalPropertyAspectConfigurations)==null?void 0:o.some(l=>{var c,d;return l.globalPropertyConfigurationId===((d=(c=this.bundle.getProductCollection())==null?void 0:c.getResource().globalPropertyConfiguration)==null?void 0:d.id)&&l.aspectName===this.property.name})}))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Mr extends ze{constructor(t,e){super(t,e)}async initialize(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorOptionId&&(this.colorOption=await H.getOption((n=(a=this.property.data)==null?void 0:a.fileUpload)==null?void 0:n.colorOptionId)),await this.loadImageData(),this}async loadImageData(){var e;const t=await this.getImage();if(t!=null&&t.fileLink)if(t!=null&&t.fileLink.endsWith(".svg")){const a=await tt(t==null?void 0:t.fileLink),n=await ka(t==null?void 0:t.fileLink),i=n.width,s=n.height,o=await ot(a),l=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);(e=l==null?void 0:l.colors)==null||e.forEach(d=>{o.colors[d.key]={browserValue:d.browserValue,pmsValue:d.pmsValue}});const c={src:t==null?void 0:t.fileLink,width:i,height:s,aspect:i/s,svg:o.svg,colors:o.colors};dt.set(t==null?void 0:t.fileLink,c),this.imageData=c}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(ke.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await U.removeBackgroundFromAsset(e),s={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,s):a.setAspectStorage(this.property.name,s)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return U.getLocalOrFromServer(t)}async getImageWithColors(){var t,e;return await this.loadImageData(),(t=this.imageData)!=null&&t.svg?Re($e(this.imageData.svg,this.imageData.colors??{},!1)):(e=this.imageData)==null?void 0:e.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.originalAssetKey)return U.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.backgroundRemovedAssetKey)return U.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){var t;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.useOriginalAsset)??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if((n==null?void 0:n.useOriginalAsset)===t)return;const i={...n,useOriginalAsset:t},s=t?n==null?void 0:n.originalAssetKey:n==null?void 0:n.backgroundRemovedAssetKey,o=[a.setAspect(this.property.name,s||"",i)];if(t)o.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};o.push(l())}o.push(this.loadImageData()),await Promise.all(o),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await U.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const i=new Map(n.colors.map(s=>[s.key,{browserValue:s.browserValue,pmsValue:s.pmsValue}])??[]);this.getSharedSteps(t).forEach(s=>{s.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorPickerEnabled?((n=(a=this.colorOption)==null?void 0:a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})))??[]:[]}getCurrentColors(){var t;return(t=this.imageData)==null?void 0:t.colors}isColorPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.colorPickerEnabled)??!1}isPmsPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.pmsPickerEnabled)??!1}async getOriginalColors(){var e;return(e=this.imageData)!=null&&e.svg?(await ot(this.imageData.svg)).colors:void 0}async changeColors(t){var i;if(!((i=this.imageData)!=null&&i.svg))return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(s=>{s.changeColors(a)});const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([s,o])=>({key:s,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const s=this.getSharedSteps(e).map(o=>{const l=o;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(s)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{var s;if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;((s=n.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name}))&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Tr extends ze{constructor(t,e){super(t,e)}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(n)}}class Va extends ze{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){var e,a;const t=(a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.find(n=>{var i,s;return n.id===((s=(i=this.optionResource)==null?void 0:i.defaultVariant)==null?void 0:s.id)});t&&await this.selectVariant(new it(t))}getCurrentVariant(){var e,a;if(!this.optionResource)return;const t=this.getStateValue();if(t){const n=(a=this.optionResource.variants)==null?void 0:a.find(i=>i.id===t);return n?new it(n):void 0}else{const n=(e=this.optionResource.variants)==null?void 0:e.find(i=>{var s,o;return i.id===((o=(s=this.optionResource)==null?void 0:s.defaultVariant)==null?void 0:o.id)});return n?new it(n):void 0}}getAvailableVariants(){var e,a;return(((a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.filter(n=>n.enabled))||[]).map(n=>new it(n))}getAllVariants(){var e;return(((e=this.optionResource)==null?void 0:e.variants)||[]).map(a=>new it(a))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){var n,i;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(i=(n=this.optionResource)==null?void 0:n.variants)==null?void 0:i.find(s=>s.id===e);return a?this.applyVariantSelection(new it(a),t):Promise.resolve()}async applyVariantSelection(t,e){const n=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(n)}}class fa extends Va{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyColorVariant(t,void 0,e)])}async applyGlobalState(t){var i,s,o;console.log(`LOG: applying global state for color ${this.property.name}`);const e=this.getStateValue();if(!e)return Promise.resolve();const a=(s=(i=this.optionResource)==null?void 0:i.variants)==null?void 0:s.find(l=>l.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new it(a),t);const n=(o=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:o.customColor;console.log(`LOG: custom color ${n}`),n&&this.setCustomColor(n)}async applyColorVariant(t,e,a){const n=this.getSharedSteps(e);console.log(`LOG: applying color variant for ${n.length} shared steps`);const i=n.map(s=>{switch(console.log(`LOG: applying to step type ${s.getType()}`),s.getType()){case P.Shape:return s.selectVariant(t);case P.Text:return s.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case P.Illustration:return s.setColor((a==null?void 0:a.toString())||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){var t,e;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.customColor)||((e=this.getCurrentVariant())==null?void 0:e.getColor())||"#ffffff"}}const Kl=(r,t,e,a)=>r.flatMap(n=>n.getSteps()).filter(n=>n.getGlobalPropertyAspects(t).includes(e)&&n.getType()===a),_l=(r,t,e)=>{const n=Kl(r,t,e,P.Illustration).map(i=>{var l;const s=(l=i.getCurrentVariant())==null?void 0:l.getAssetResource(),o=i.getColors();return!(s!=null&&s.assetConfiguration)||!o?0:Object.getOwnPropertyNames(o).length});return Math.max(...n)};class Xl{constructor(t,e,a,n,i){this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const s=i==null?void 0:i.existingGlobalPropertyState;this.initPromise=s?Promise.resolve(s).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=s}):this.createGlobalPropertyState().then(o=>{console.log("Setting global property state to new state."),this.globalPropertyState=o}),this.onGlobalPropertyStateChange=n}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=Et(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){var a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e))==null?void 0:a.storage}async setAspect(t,e,a,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);const s=Et(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(l=>l.name===t);if(o.length>0)if(n){const l=o.find(c=>c.channel===n);if(l)l.value=e,l.type=i.type,l.channel=n,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(n===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n})}}else{const l=o[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(s,this.globalPropertyState)}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(o=>o.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=Et(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(o=>o.name===t);if(s.length>0)if(a){const o=s.find(l=>l.channel===a);o&&(o.storage=e!==null?e:void 0,o.type=n.type)}else{const o=s[0];o.storage=e!==null?e:void 0,o.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async updateGlobalPropertyState(){var e,a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await B.getShadowGraphqlClient().mutate({mutation:Go,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(n=>{let i=n.type&&n.storage?{}:void 0;if(i)switch(n.type){case V.FileUpload:{i.fileUpload=n.storage;break}case V.Option:{i.option=n.storage;break}case V.ColorOption:{i=n.storage;break}}return{name:n.name,value:n.value,type:n.type,storage:i,channel:n.channel}})},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 createGlobalPropertyState(){var e,a;const t=await B.getShadowGraphqlClient().mutate({mutation:zo,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.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}`)}}class Zl{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 n=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=n.position,i.rotation=n.rotation,i.scale=n.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(s=>s.transactionId===n);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:n,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){var l,c;if(!((l=t==null?void 0:t.getWorkflowManager())!=null&&l.getModelContainer())||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,n=this.state.transactions.find(d=>d.transactionId===a),i=(c=n==null?void 0:n.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,n.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const tc=v.gql`
2263
2263
  query GetManyMetafields($entityIds: [String!]!) {
2264
2264
  metafieldsMany(entityIds: $entityIds) {
2265
2265
  id
@@ -2435,7 +2435,7 @@
2435
2435
  }
2436
2436
  }
2437
2437
  }
2438
- `;class gc{constructor(t,e=B.getShadowGraphqlClient.bind(B)){this.options=t,this.client=e}query(t){var a,n;const e=(a=this.options)!=null&&a.onQuery?(n=this.options)==null?void 0:n.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){var a,n;const e=(a=this.options)!=null&&a.onMutate?(n=this.options)==null?void 0:n.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class mc{init(t,e,a){this.cognitoClient=new me.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){var a;const e=await((a=this.cognitoClient)==null?void 0:a.send(new me.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}})));(e==null?void 0:e.ChallengeName)==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){var n;return await((n=this.cognitoClient)==null?void 0:n.send(new me.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}})))}async refreshTokens(){var a;const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await((a=this.cognitoClient)==null?void 0:a.send(new me.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}})))}}const Wt=new mc;class Vr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return ci(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ja.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t,a=Ja.code(e);if((a==null?void 0:a.code)==="CLP")return"USD0,0"}}const An=new Vr;class zr{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,An.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,An.getPrecisionForCurrency(e))}}const pc=async(r,t)=>{var n;const e=await B.getShadowGraphqlClient().query({query:Ss(((n=t==null?void 0:t.assets)==null?void 0:n.metadata)||!1),errorPolicy:"all",variables:{ids:r}});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!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.steps.forEach(s=>{var o,l,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((l=s.option.defaultVariant)!=null&&l.asset&&U.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&U.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(d=>{d.asset&&U.cacheAsset(d.asset),d.thumbnail&&U.cacheAsset(d.thumbnail),d.material&&U.cacheMaterial(d.material)}),Ot.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},fc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},Wa=async(r,t)=>{const e=r.map(o=>Ot.get({id:o,options:t})),a=r.filter((o,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=pc(a,t),i=a.map(o=>Ot.set({id:o,options:t},fc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},Cc=async(r,t)=>(await Wa([r],t))[0],wc=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:Q(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),yc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):wc(t.panels)};class Sc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return B.getShadowGraphqlClient().mutate({...e,mutation:cs})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ii(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 28.0.1-beta.f5df4b3f-ec7b-542e-84ca-48ed7f2a1458"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Qn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!Pi())throw new Error("Application key required to use Flow Service.");return new $r}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await B.getShadowGraphqlClient().query({query:xs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:s,rateTo:o}=i.data.currencyConversion;return new zr(s,o,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Gr(this.options.applicationKey),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 n,i;const e=T.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const a=T.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const s=a.get(t);if((T.getMap("partnerCustomerIds")||new Map).get(s)&&await this.reloadLoggedInCustomer()){const d=(i=(n=this.customer)==null?void 0:n.bundleStakeholders)==null?void 0:i.find(A=>{var u;return((u=A.bundle)==null?void 0:u.id)===t});if(d)return Promise.resolve({success:!0,stakeholderType:d.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var d,A,u,h,g,m;const e=B.getShadowGraphqlClient(),a=await e.query({query:vs,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 n=a.data.transactions[0];if(!((A=(d=n.product)==null?void 0:d.partner)==null?void 0:A.id))throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=T.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const o=T.getMap("transactionCustomerIds");if(o!=null&&o.has(t)&&o.get(t)&&await this.reloadLoggedInCustomer()){const C=((h=(u=this.customer)==null?void 0:u.bundleStakeholders)==null?void 0:h.find(w=>{var S,y;return(y=(S=w.bundle)==null?void 0:S.transactions)==null?void 0:y.some(E=>E.id===t)}))||((m=(g=this.customer)==null?void 0:g.stakeholders)==null?void 0:m.find(w=>{var S;return((S=w.transaction)==null?void 0:S.id)===t}));if(C)return Promise.resolve({success:!0,stakeholderType:C.type})}const c=(await e.query({query:Es,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=T.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),T.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var a,n;const e=(n=(a=this.customer)==null?void 0:a.stakeholders)==null?void 0:n.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=B.getShadowGraphqlClient(),n=(await e.query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:Ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!l)throw new Error("Unable to create customer.");return this.storeCustomer(l),this.customer=l,{customer:l,isAuthenticated:!1}}this.storeCustomer(n);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),i=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l!=null&&l.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const o=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return o.id?(this.customer=o,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await B.getShadowGraphqlClient().mutate({mutation:uc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n!=null&&n.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const s=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!s.id)throw new Error("Failed to get customer.");return this.customer=s,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,i=!(a!=null&&a.AccessToken)||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||i){const s=await Wt.refreshTokens();if(s!=null&&s.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await B.getShadowGraphqlClient().query({query:hc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){var c,d,A,u,h;const i=(A=(await B.getShadowGraphqlClient().mutate({mutation:Xo(((d=(c=a==null?void 0:a.graphql)==null?void 0:c.productCollection)==null?void 0:d.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((g,m)=>({key:g[0],value:g[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:A.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=T.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),T.setMap("bundlePartnerIds",s);const o=T.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),T.setMap("bundleOwnerIds",o);const l=new ta(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(h=(u=a==null?void 0:a.graphql)==null?void 0:u.productCollection)==null?void 0:h.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){var h,g,m,p,f,C,w,S,y,E,b;const i=T.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),o={};try{const I=await this.loggedInBearerToken();o.Authorization=`Bearer ${I}`}catch{const F=((h=Object.entries(localStorage).find(([N,rt])=>N.startsWith("CognitoIdentityServiceProvider")&&N.endsWith("idToken")))==null?void 0:h[0])||"",k=localStorage.getItem(F);k&&!_t(k)&&(o.Authorization=`Bearer ${k}`)}const l={bundleOwnerId:s,...o,...(g=n==null?void 0:n.graphql)==null?void 0:g.additionalHeaders},c=await B.getShadowGraphqlClient().query({query:Ho(((p=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:p.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!((f=c.data)!=null&&f.bundles)||((C=c.data)==null?void 0:C.bundles.length)===0||!((w=c.data)!=null&&w.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const d=(S=c.data)==null?void 0:S.bundles[0],A=T.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),T.setMap("bundlePartnerIds",A);const u=new ta(this,d,e,a,s,{additionalHeaders:(y=n==null?void 0:n.graphql)==null?void 0:y.additionalHeaders,eagerFetchProducts:(b=(E=n==null?void 0:n.graphql)==null?void 0:E.productCollection)==null?void 0:b.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:n==null?void 0:n.readonly});return await u.getInitializationPromise(),u}async duplicateBundle(t,e,a,n){var u,h,g,m,p,f;const i=(u=T.getMap("bundleOwnerIds"))==null?void 0:u.get(t),s={};try{const C=await this.loggedInBearerToken();s.Authorization=`Bearer ${C}`}catch{const S=((h=Object.entries(localStorage).find(([E,b])=>E.startsWith("CognitoIdentityServiceProvider")&&E.endsWith("idToken")))==null?void 0:h[0])||"",y=localStorage.getItem(S);y&&!_t(y)&&(s.Authorization=`Bearer ${y}`)}const o={bundleOwnerId:i,...s,...(g=n==null?void 0:n.graphql)==null?void 0:g.additionalHeaders},c=(f=(await B.getShadowGraphqlClient().mutate({mutation:Zo(((p=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:p.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data)==null?void 0:f.bundleDuplicate;if(!(c!=null&&c.id))throw new Error("Unable to duplicate bundle");const d=T.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),T.setMap("bundlePartnerIds",d);const A=T.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),T.setMap("bundleOwnerIds",A),async()=>{var w,S;const C=new ta(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:(S=(w=n==null?void 0:n.graphql)==null?void 0:w.productCollection)==null?void 0:S.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});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 B.getShadowGraphqlClient().query({query:Al(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 B.getShadowGraphqlClient().query({query:Yo,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||[],n=T.getMap("bundlePartnerIds")||new Map;return a.forEach(s=>{var o,l;(o=s.bundle)!=null&&o.id&&((l=s.bundle.partner)!=null&&l.id)&&n.set(s.bundle.id,s.bundle.partner.id)}),T.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new ht("No options provided!");const a=B.getShadowGraphqlClient(),n=async y=>{var x,F,k;if(y.length===0)return[];const E=y.map(N=>N.option.transactionId),b=await a.query({query:ls,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),I=b.data.transactions;if(I.length!==y.length){const N=((F=(x=b.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Not all transactions were found: ${N}`)}return!this.activeIntegration&&((k=I[0].integrationProduct)!=null&&k.integration)&&(this.activeIntegration=Promise.resolve(I[0].integrationProduct.integration)),I.map((N,rt)=>{var R;return{transaction:N,workflowId:N.workflowId,readOnly:((R=y.find(et=>et.option.transactionId===N.id))==null?void 0:R.option.readOnly)??!1,index:y[rt].index}})},i=async y=>{var I,x,F;if(y.length===0)return[];const E=await a.mutate({mutation:os,variables:{inputs:y.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),b=(I=E.data)==null?void 0:I.transactionCreateMany;if(!b||b.length===0){const k=((F=(x=E.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Failed to create transactions: ${k}`)}return b.map((k,N)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:y[N].index}))},s=t.map((y,E)=>({option:y,index:E})),o=s.filter(y=>y.option.type==="transaction"),l=s.filter(y=>y.option.type==="integration"||y.option.type==="external"),c=Ya(o,10),d=Ya(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(y=>y.workflowId))],h=await Wa(u,e),g=new Map(h.map(y=>[y.id,y])),m=T.getMap("transactionOwnerIds")||new Map,p=A.map(async y=>{var et;const{transaction:E,workflowId:b,readOnly:I,index:x}=y,F=g.get(b),k=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const N=m.get(E.id)||void 0,rt=new gc({onMutate:()=>({context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})}),R={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:(et=k==null?void 0:k.workflowConfiguration)==null?void 0:et.singleVariantsRenderable,stateMutationFunc:I?async()=>{throw new z("State mutation is forbidden in read only mode!")}:async Z=>this.updateTransactionState({...Z,context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),graphQlClient:()=>rt,readOnly:I,workflow:F,isReloadedTransaction:k.type==="transaction"};if(!I&&k.workflowState){const Z=JSON.parse(k.workflowState);R.layouts=Object.values(Z.layouts||{}).map(Ut=>Ut.layout),await ir(Z),R.reloadedState=Z}else R.layouts=yc(R.transaction,R.workflow);return R.renderableContextService=new zl(R.layouts),R.delayWorkflowStateSync=!0,{experienceOptions:R,index:x,options:k}}),f=await Promise.all(p);T.setMap("transactionOwnerIds",m);const w=f.sort((y,E)=>y.index-E.index).map(async y=>{const{experienceOptions:E,options:b}=y,I=new Fr(this,E);return await I.getWorkflowManager().getInitializationPromise(),b.type!=="transaction"&&this.customer&&await I.attachCustomerDetails({email:this.customer.emailAddress}),I}),S=await Promise.all(w);return S.forEach(y=>y.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),S}storeCustomer(t){const e=T.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),T.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){var s,o;const i=(s=(await B.getShadowGraphqlClient().query({query:hs(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProducts;if(!i||i.length===0||!((o=i[0])!=null&&o.id))throw new Error("Integration product not found.");return new Ca(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await B.getShadowGraphqlClient().query({query:gs(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:o.integrationProductFromExternalIds;if(!(s!=null&&s.id))throw new Error("Integration product not found.");return new Ca(s)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(T.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await B.getShadowGraphqlClient().query({query:us,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await B.getShadowGraphqlClient().mutate({mutation:Ds,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const Gr=async(r,t)=>(await B.getShadowGraphqlClient().query({query:Bs,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,vc=async r=>{const e=await B.getShadowGraphqlClient().query({query:As,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Ec=async(r,t)=>{var a;return(a=(await B.getShadowGraphqlClient().query({query:bs,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},bc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Ps,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},Bc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Is,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function qr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const o=r,l=Math.max(t.width/e.width,t.height/e.height);o.zoom=Math.max(l,r.zoom);const c=e.width*o.zoom,d=e.height*o.zoom;return o.x=Se(r.x,t.width-c,0),o.y=Se(r.y,t.height-d,0),o}const s=r;return s.x=Se(s.x,-n,t.width),s.y=Se(s.y,-i,t.height),s}function Se(r,t,e){return Math.min(Math.max(r,t),e)}class Wr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=vn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let s=0;s<n.currentFrameSources.length;s++){const o=n.currentFrameSources[s],l=await Ae(o),c=this.frameData?this.frameData[s]:void 0;Sn(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[s]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Ft.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=$e(this.imageData.svg,this.imageData.colors||{},!1);return Re(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((s,o)=>{const l=(e[o]-this.offsets[o].x)/this.offsets[o].zoom,c=(a[o]-this.offsets[o].y)/this.offsets[o].zoom,d=e[o]-l*t[o],A=a[o]-c*t[o];return{x:d,y:A,zoom:this.imageData.width*t[o]/this.imageData.width}});this.updateOffsets(i,n),this.onZoomChangeListeners.forEach(s=>s(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new z("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(t[o].x===s.x&&t[o].y===s.y&&t[o].zoom===s.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=qr(t[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,i){if(!a||a.length===0||a.some(o=>!o))throw new z("Frame data not set. This is a bug");if(!this.workflowManager)throw new z("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,l)=>{s(new $([new go(o,e,t[l]),new mo(o,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Fa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Ic{updateRecipient(t,e,a,n,i,s,o,l,c,d){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var jr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(jr||{});class Hr extends nt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Wr(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ut.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 n;if(await ut.selectImage(this.step,t,this.manager,a),e){const i=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.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(ke.BackgroundRemover)}async canRemoveBackground(){var t,e,a,n;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((n=(a=this.frameService)==null?void 0:a.getImageData())!=null&&n.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 U.removeBackgroundFromAsset(e);t&&await ut.selectImage(this.step,a,this.manager,!1);const n=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ut.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?ut.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 ut.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){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 U.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 U.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 n;const e=((n=this.getFrameStepStorage())==null?void 0:n.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)}}const Pc=v.gql`
2438
+ `;class gc{constructor(t,e=B.getShadowGraphqlClient.bind(B)){this.options=t,this.client=e}query(t){var a,n;const e=(a=this.options)!=null&&a.onQuery?(n=this.options)==null?void 0:n.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){var a,n;const e=(a=this.options)!=null&&a.onMutate?(n=this.options)==null?void 0:n.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class mc{init(t,e,a){this.cognitoClient=new me.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){var a;const e=await((a=this.cognitoClient)==null?void 0:a.send(new me.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}})));(e==null?void 0:e.ChallengeName)==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){var n;return await((n=this.cognitoClient)==null?void 0:n.send(new me.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}})))}async refreshTokens(){var a;const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await((a=this.cognitoClient)==null?void 0:a.send(new me.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}})))}}const Wt=new mc;class Vr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return ci(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ja.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t,a=Ja.code(e);if((a==null?void 0:a.code)==="CLP")return"USD0,0"}}const An=new Vr;class zr{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,An.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,An.getPrecisionForCurrency(e))}}const pc=async(r,t)=>{var n;const e=await B.getShadowGraphqlClient().query({query:Ss(((n=t==null?void 0:t.assets)==null?void 0:n.metadata)||!1),errorPolicy:"all",variables:{ids:r}});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!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.steps.forEach(s=>{var o,l,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((l=s.option.defaultVariant)!=null&&l.asset&&U.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&U.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(d=>{d.asset&&U.cacheAsset(d.asset),d.thumbnail&&U.cacheAsset(d.thumbnail),d.material&&U.cacheMaterial(d.material)}),Ot.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},fc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},Wa=async(r,t)=>{const e=r.map(o=>Ot.get({id:o,options:t})),a=r.filter((o,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=pc(a,t),i=a.map(o=>Ot.set({id:o,options:t},fc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},Cc=async(r,t)=>(await Wa([r],t))[0],wc=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:Q(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),yc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):wc(t.panels)};class Sc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return B.getShadowGraphqlClient().mutate({...e,mutation:cs})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ii(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 28.0.1-beta.10d96995-f841-5fe3-9e44-7c0791da863a"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Qn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!Pi())throw new Error("Application key required to use Flow Service.");return new $r}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await B.getShadowGraphqlClient().query({query:xs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:s,rateTo:o}=i.data.currencyConversion;return new zr(s,o,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Gr(this.options.applicationKey),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 n,i;const e=T.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const a=T.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const s=a.get(t);if((T.getMap("partnerCustomerIds")||new Map).get(s)&&await this.reloadLoggedInCustomer()){const d=(i=(n=this.customer)==null?void 0:n.bundleStakeholders)==null?void 0:i.find(A=>{var u;return((u=A.bundle)==null?void 0:u.id)===t});if(d)return Promise.resolve({success:!0,stakeholderType:d.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var d,A,u,h,g,m;const e=B.getShadowGraphqlClient(),a=await e.query({query:vs,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 n=a.data.transactions[0];if(!((A=(d=n.product)==null?void 0:d.partner)==null?void 0:A.id))throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=T.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const o=T.getMap("transactionCustomerIds");if(o!=null&&o.has(t)&&o.get(t)&&await this.reloadLoggedInCustomer()){const C=((h=(u=this.customer)==null?void 0:u.bundleStakeholders)==null?void 0:h.find(w=>{var S,y;return(y=(S=w.bundle)==null?void 0:S.transactions)==null?void 0:y.some(E=>E.id===t)}))||((m=(g=this.customer)==null?void 0:g.stakeholders)==null?void 0:m.find(w=>{var S;return((S=w.transaction)==null?void 0:S.id)===t}));if(C)return Promise.resolve({success:!0,stakeholderType:C.type})}const c=(await e.query({query:Es,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=T.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),T.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var a,n;const e=(n=(a=this.customer)==null?void 0:a.stakeholders)==null?void 0:n.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=B.getShadowGraphqlClient(),n=(await e.query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:Ac,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!l)throw new Error("Unable to create customer.");return this.storeCustomer(l),this.customer=l,{customer:l,isAuthenticated:!1}}this.storeCustomer(n);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),i=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l!=null&&l.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const o=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return o.id?(this.customer=o,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await B.getShadowGraphqlClient().mutate({mutation:uc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n!=null&&n.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const s=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!s.id)throw new Error("Failed to get customer.");return this.customer=s,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,i=!(a!=null&&a.AccessToken)||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||i){const s=await Wt.refreshTokens();if(s!=null&&s.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await B.getShadowGraphqlClient().query({query:hc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){var c,d,A,u,h;const i=(A=(await B.getShadowGraphqlClient().mutate({mutation:Xo(((d=(c=a==null?void 0:a.graphql)==null?void 0:c.productCollection)==null?void 0:d.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((g,m)=>({key:g[0],value:g[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:A.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=T.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),T.setMap("bundlePartnerIds",s);const o=T.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),T.setMap("bundleOwnerIds",o);const l=new ta(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(h=(u=a==null?void 0:a.graphql)==null?void 0:u.productCollection)==null?void 0:h.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){var h,g,m,p,f,C,w,S,y,E,b;const i=T.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),o={};try{const I=await this.loggedInBearerToken();o.Authorization=`Bearer ${I}`}catch{const F=((h=Object.entries(localStorage).find(([N,rt])=>N.startsWith("CognitoIdentityServiceProvider")&&N.endsWith("idToken")))==null?void 0:h[0])||"",k=localStorage.getItem(F);k&&!_t(k)&&(o.Authorization=`Bearer ${k}`)}const l={bundleOwnerId:s,...o,...(g=n==null?void 0:n.graphql)==null?void 0:g.additionalHeaders},c=await B.getShadowGraphqlClient().query({query:Ho(((p=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:p.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!((f=c.data)!=null&&f.bundles)||((C=c.data)==null?void 0:C.bundles.length)===0||!((w=c.data)!=null&&w.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const d=(S=c.data)==null?void 0:S.bundles[0],A=T.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),T.setMap("bundlePartnerIds",A);const u=new ta(this,d,e,a,s,{additionalHeaders:(y=n==null?void 0:n.graphql)==null?void 0:y.additionalHeaders,eagerFetchProducts:(b=(E=n==null?void 0:n.graphql)==null?void 0:E.productCollection)==null?void 0:b.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:n==null?void 0:n.readonly});return await u.getInitializationPromise(),u}async duplicateBundle(t,e,a,n){var u,h,g,m,p,f;const i=(u=T.getMap("bundleOwnerIds"))==null?void 0:u.get(t),s={};try{const C=await this.loggedInBearerToken();s.Authorization=`Bearer ${C}`}catch{const S=((h=Object.entries(localStorage).find(([E,b])=>E.startsWith("CognitoIdentityServiceProvider")&&E.endsWith("idToken")))==null?void 0:h[0])||"",y=localStorage.getItem(S);y&&!_t(y)&&(s.Authorization=`Bearer ${y}`)}const o={bundleOwnerId:i,...s,...(g=n==null?void 0:n.graphql)==null?void 0:g.additionalHeaders},c=(f=(await B.getShadowGraphqlClient().mutate({mutation:Zo(((p=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:p.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data)==null?void 0:f.bundleDuplicate;if(!(c!=null&&c.id))throw new Error("Unable to duplicate bundle");const d=T.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),T.setMap("bundlePartnerIds",d);const A=T.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),T.setMap("bundleOwnerIds",A),async()=>{var w,S;const C=new ta(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:(S=(w=n==null?void 0:n.graphql)==null?void 0:w.productCollection)==null?void 0:S.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});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 B.getShadowGraphqlClient().query({query:Al(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 B.getShadowGraphqlClient().query({query:Yo,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||[],n=T.getMap("bundlePartnerIds")||new Map;return a.forEach(s=>{var o,l;(o=s.bundle)!=null&&o.id&&((l=s.bundle.partner)!=null&&l.id)&&n.set(s.bundle.id,s.bundle.partner.id)}),T.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new ht("No options provided!");const a=B.getShadowGraphqlClient(),n=async y=>{var x,F,k;if(y.length===0)return[];const E=y.map(N=>N.option.transactionId),b=await a.query({query:ls,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),I=b.data.transactions;if(I.length!==y.length){const N=((F=(x=b.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Not all transactions were found: ${N}`)}return!this.activeIntegration&&((k=I[0].integrationProduct)!=null&&k.integration)&&(this.activeIntegration=Promise.resolve(I[0].integrationProduct.integration)),I.map((N,rt)=>{var R;return{transaction:N,workflowId:N.workflowId,readOnly:((R=y.find(et=>et.option.transactionId===N.id))==null?void 0:R.option.readOnly)??!1,index:y[rt].index}})},i=async y=>{var I,x,F;if(y.length===0)return[];const E=await a.mutate({mutation:os,variables:{inputs:y.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),b=(I=E.data)==null?void 0:I.transactionCreateMany;if(!b||b.length===0){const k=((F=(x=E.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Failed to create transactions: ${k}`)}return b.map((k,N)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:y[N].index}))},s=t.map((y,E)=>({option:y,index:E})),o=s.filter(y=>y.option.type==="transaction"),l=s.filter(y=>y.option.type==="integration"||y.option.type==="external"),c=Ya(o,10),d=Ya(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(y=>y.workflowId))],h=await Wa(u,e),g=new Map(h.map(y=>[y.id,y])),m=T.getMap("transactionOwnerIds")||new Map,p=A.map(async y=>{var et;const{transaction:E,workflowId:b,readOnly:I,index:x}=y,F=g.get(b),k=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const N=m.get(E.id)||void 0,rt=new gc({onMutate:()=>({context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})}),R={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:(et=k==null?void 0:k.workflowConfiguration)==null?void 0:et.singleVariantsRenderable,stateMutationFunc:I?async()=>{throw new z("State mutation is forbidden in read only mode!")}:async X=>(console.log(`LOG: updating transaction with options ${JSON.stringify(X,null,2)}`),console.trace(),this.updateTransactionState({...X,context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})),graphQlClient:()=>rt,readOnly:I,workflow:F,isReloadedTransaction:k.type==="transaction"};if(!I&&k.workflowState){const X=JSON.parse(k.workflowState);R.layouts=Object.values(X.layouts||{}).map(Ut=>Ut.layout),await ir(X),R.reloadedState=X}else R.layouts=yc(R.transaction,R.workflow);return R.renderableContextService=new zl(R.layouts),R.delayWorkflowStateSync=!0,{experienceOptions:R,index:x,options:k}}),f=await Promise.all(p);T.setMap("transactionOwnerIds",m);const w=f.sort((y,E)=>y.index-E.index).map(async y=>{const{experienceOptions:E,options:b}=y,I=new Fr(this,E);return await I.getWorkflowManager().getInitializationPromise(),b.type!=="transaction"&&this.customer&&await I.attachCustomerDetails({email:this.customer.emailAddress}),I}),S=await Promise.all(w);return S.forEach(y=>y.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),S}storeCustomer(t){const e=T.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),T.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){var s,o;const i=(s=(await B.getShadowGraphqlClient().query({query:hs(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProducts;if(!i||i.length===0||!((o=i[0])!=null&&o.id))throw new Error("Integration product not found.");return new Ca(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await B.getShadowGraphqlClient().query({query:gs(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:o.integrationProductFromExternalIds;if(!(s!=null&&s.id))throw new Error("Integration product not found.");return new Ca(s)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(T.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await B.getShadowGraphqlClient().query({query:us,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await B.getShadowGraphqlClient().mutate({mutation:Ds,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const Gr=async(r,t)=>(await B.getShadowGraphqlClient().query({query:Bs,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,vc=async r=>{const e=await B.getShadowGraphqlClient().query({query:As,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Ec=async(r,t)=>{var a;return(a=(await B.getShadowGraphqlClient().query({query:bs,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},bc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Ps,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},Bc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Is,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function qr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const o=r,l=Math.max(t.width/e.width,t.height/e.height);o.zoom=Math.max(l,r.zoom);const c=e.width*o.zoom,d=e.height*o.zoom;return o.x=Se(r.x,t.width-c,0),o.y=Se(r.y,t.height-d,0),o}const s=r;return s.x=Se(s.x,-n,t.width),s.y=Se(s.y,-i,t.height),s}function Se(r,t,e){return Math.min(Math.max(r,t),e)}class Wr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=vn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let s=0;s<n.currentFrameSources.length;s++){const o=n.currentFrameSources[s],l=await Ae(o),c=this.frameData?this.frameData[s]:void 0;Sn(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[s]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Ft.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=$e(this.imageData.svg,this.imageData.colors||{},!1);return Re(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((s,o)=>{const l=(e[o]-this.offsets[o].x)/this.offsets[o].zoom,c=(a[o]-this.offsets[o].y)/this.offsets[o].zoom,d=e[o]-l*t[o],A=a[o]-c*t[o];return{x:d,y:A,zoom:this.imageData.width*t[o]/this.imageData.width}});this.updateOffsets(i,n),this.onZoomChangeListeners.forEach(s=>s(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new z("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(t[o].x===s.x&&t[o].y===s.y&&t[o].zoom===s.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=qr(t[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,i){if(!a||a.length===0||a.some(o=>!o))throw new z("Frame data not set. This is a bug");if(!this.workflowManager)throw new z("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,l)=>{s(new $([new go(o,e,t[l]),new mo(o,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Fa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Ic{updateRecipient(t,e,a,n,i,s,o,l,c,d){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var jr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(jr||{});class Hr extends nt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Wr(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ut.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 n;if(await ut.selectImage(this.step,t,this.manager,a),e){const i=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.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(ke.BackgroundRemover)}async canRemoveBackground(){var t,e,a,n;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((n=(a=this.frameService)==null?void 0:a.getImageData())!=null&&n.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 U.removeBackgroundFromAsset(e);t&&await ut.selectImage(this.step,a,this.manager,!1);const n=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ut.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?ut.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 ut.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){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 U.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 U.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 n;const e=((n=this.getFrameStepStorage())==null?void 0:n.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)}}const Pc=v.gql`
2439
2439
  query GetLoggedInCustomer($email: String!) {
2440
2440
  customer(emailAddress: $email) {
2441
2441
  id