@spiffcommerce/core 33.2.0 → 33.2.1-beta.01146196-c06a-5f3e-8bc9-535ef008ae9f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -2401,6 +2401,8 @@ interface GetNewWorkflowExperienceOptionsBase extends GetWorkflowOptionsBase {
2401
2401
  workflowState?: string;
2402
2402
  }
2403
2403
  interface GetWorkflowExperienceFromBlankOptions extends GetNewWorkflowExperienceOptionsBase {
2404
+ quantity?: number;
2405
+ recipient?: any;
2404
2406
  type: "blank";
2405
2407
  }
2406
2408
  interface GetWorkflowExperienceFromIntegrationProductOptions extends GetNewWorkflowExperienceOptionsBase {
@@ -2805,6 +2807,10 @@ interface WorkflowManager {
2805
2807
  [key: string]: any;
2806
2808
  };
2807
2809
  traversableScenes(): Promise<WorkflowScene[]>;
2810
+ /**
2811
+ * Forcibly re-renders all layouts.
2812
+ */
2813
+ renderLayouts(): void;
2808
2814
  }
2809
2815
 
2810
2816
  declare enum AssetType {
@@ -5208,6 +5214,7 @@ declare class DigitalContentStepService implements StepService<DigitalContentSte
5208
5214
  declare const digitalContentStepService: DigitalContentStepService;
5209
5215
 
5210
5216
  declare class MockWorkflowManager implements WorkflowManager {
5217
+ renderLayouts(): void;
5211
5218
  traversableScenes(): Promise<WorkflowScene[]>;
5212
5219
  getMandatoryUnfulfilledSteps: () => string[];
5213
5220
  getTemplatingContext: () => Promise<{
package/dist/index.js CHANGED
@@ -1507,7 +1507,7 @@
1507
1507
  `,m={};m[this.shapeFillId]={browserValue:g};const f=M();return{id:f,region:A,command:new z({stepRegion:A,stepName:t.stepName,colors:m,id:f,svg:p,type:F.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,excludeFromExport:t.data.excludeFromPrint},h)}},c=t.data.regions.map(l),d=c.filter(A=>!!A).map(A=>A?.command),u=c.filter(A=>!!A).map(A=>({id:A.id,region:A.region}));return{command:new R(d),followup:async()=>{await r.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],u,async()=>{r.updateStorage(t.stepName,{colour:s()})})}}}}}const Ft=new $s;class Us{constructor(){this.latestToast=null,this.toastType=null,this.toastCallbacks=[]}addToastCallback(t){t({toastMessage:this.latestToast,toastType:this.toastType}),this.toastCallbacks.push(t)}removeToastCallback(t){this.toastCallbacks=this.toastCallbacks.filter(e=>e!==t)}setLatestToast(t,e){this.latestToast=t,this.toastType=e,this.onToastChange()}onToastChange(){this.toastCallbacks.forEach(t=>t({toastMessage:this.latestToast,toastType:this.toastType}))}}const Cr=new Us,aa=(n,t,e,a,r)=>{if(t.some(d=>d==null))throw new Error(`Failed to autosize lines: ${t.join(", ")}`);let i=t.map(d=>d.split(`
1508
1508
  `)).flat(),o=i.length,s=i.map(d=>mt(d,a,r));const l=r.getApproximateHeight()*a;let c=!0;for(;c;){if(l+(o-1)*e>n.height)return[null,null];const u=Math.max(...s);if(u<=n.width)return[i,u];const A=s.reduce((m,f,w,I)=>f>I[m]?w:m,0),h=i[A];let g=!1,p=h.length;for(;!g&&p>-1;){p=h.lastIndexOf(" ",p-1);const m=[h.slice(0,p),h.slice(p+1)],f=m.map(I=>mt(I,a,r));f[0]<=n.width&&(i=[...i.slice(0,A),...m,...i.slice(A+1)],s=[...s.slice(0,A),...f,...s.slice(A+1)],o+=1,g=!0)}g||(c=!1)}return[null,null]},Jt=(n,t,e,a,r)=>{let i,o;const s=wt(t.assetUrl),l=s.getFont();if(r.size){const A=n/l.unitsPerEm;return[i,o]=aa(e,a,n,A,s),[r.size,i,o]}const c=6;let d=c-_e;if(a.length>0){let A=a,h=0;for(;(!r.maxSize||d<=r.maxSize)&&A;)d+=_e,h=d/l.unitsPerEm,[A,o]=aa(e,a,d,h,s)}d>c&&(d-=_e),r.minSize&&d<r.minSize&&(d=r.minSize);const u=d/l.unitsPerEm;return[i,o]=aa(e,a,d,u,s),[d,i,o]},na=30;class Te extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Te.name}}const Ls=["‘","’","“","”",`
1509
1509
  `];class Ne extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ne.name}}class Vs{constructor(){this.cachedColors=new Map,this.cachedStrokeColors=new Map,this.filterUnsupportedCharacters=(t,e)=>{let a=t.replace(/(\r\n|\r|(\u2665|\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const r=[],i=e?wt(e.assetUrl):void 0;if(i){const o=a.split("").filter(l=>!Ls.includes(l)).join(""),s=o.split("").map(l=>i.getFont().charToGlyph(l));for(let l=0;l<s.length;l++)s[l].name===".notdef"&&r.push(String.fromCharCode(o.charCodeAt(l)))}for(let o=0;o<r.length;o++)a=a.replaceAll(r[o],"");return a},this.textAlign=t=>t.vertical?"center":t.textAlign||"center",this.getErrorsForText=(t,e,a,r)=>{let i;a.data&&a.data.maxLength&&e.length>a.data.maxLength&&(i||(i={}),i.hitCharacterLimit=!0);const o=r.getWorkflowExperience().getProfanityList(),s=la.split(t.toLowerCase());for(const c of s)for(const d in o){const u=o[d].toLowerCase().replace(/\s/g,"");if(c===u){i||(i={}),i.blockedProfanity=!0;break}}return!a.data.allowNewlines&&(t.includes(`
1510
- `)||t.includes("\r"))&&(i||(i={}),i.illegalMultipleLines=!0),i}}async init(t,e,a){const r=t.option;if(!r)return null;if(a)await this.reload(t,e,a);else{const i=this.getDefaultImageFillVariant(t.data),o=i?.asset?.fileLink,s=o?await pa(o):void 0,l=s?{src:s.src,height:s.height,width:s.width,scale:t.data.imageFillScale||1}:void 0,c=this.getDefaultStrokeColorVariant(t.data),d=t.data.strokeEnabled&&c?.color?{browserValue:c.color,pmsValue:c.name}:void 0;let u=t.data.defaultText||"";const A=e.getWorkflowExperience().getBundle();if(A&&t.globalPropertyAspectConfigurations){const p=A.getGlobalPropertyConfiguration()?.aspects?.find(m=>m.type===L.Text&&t.globalPropertyAspectConfigurations?.map(f=>f.aspectName).includes(m.name));if(p){const f=A.getGlobalPropertyStateManager().getAspect(p.name);f&&(u=f)}}e.updateStorage(t.stepName,{text:u,inputText:t.data.defaultText||"",color:this.getDefaultColorVariant(t.data)?.color||this.getDefaultColor(t.data),fillImage:l,strokeColor:d}),e.updateMetadata(t.stepName,{text:u,color:this.getDefaultColorVariant(t.data)?.name||this.getDefaultColor(t.data),fillImage:i?.name,strokeColor:t.data.strokeEnabled?c?.color:void 0});const h=j.getDefaultVariant(r);if(h)return this.selectVariantCommand(t,h,{text:u},[],e,()=>{},()=>{},l,d)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map(i=>U(i.id,t.getAllLayoutData()))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const a=t.data.colorOption;if(a){const r=a.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i}))||[];return this.cachedColors.set(t.stepName,r),r}return[]}changeAlignment(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher();for(const o of a){const s=new gr(o.id,e);i(s)}}async changeFillColor(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher();e.variant?r.updateMetadata(t.stepName,{color:e.variant.name}):r.updateMetadata(t.stepName,{color:e.fill});const o=t.data.colorOption,s=o?this.createTextFillSpotColor(o,e.variant):void 0;o?r.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:o.colorProfile?.key}):r.updateStorage(t.stepName,{color:e.fill});for(const l of a){if(!e.fill)throw new Error("Fill not set on new color selection!");const c=new Ar(l.id,e.fill,s);i(c)}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const a=e.variants?.map(r=>r.asset?.fileLink)?.filter(r=>!!r)||[];return Promise.all(a.map(async r=>{const i=await pa(r);return{src:r,width:i.width,height:i.height,scale:t.data.imageFillScale||1}}))}return Promise.resolve([])}async changeFillImage(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher(),o=t.option?.variants?.find(s=>s.asset?.fileLink===e.src);r.updateMetadata(t.stepName,{fillImage:o?.name}),r.updateStorage(t.stepName,{fillImage:e});for(const s of a){const l=new ta(s.id,e);i(l)}}availableStrokeColors(t){const e=this.cachedStrokeColors.get(t.stepName);if(e)return e;const a=t.data.strokeOption;if(a){const r=a.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i}))||[];return this.cachedStrokeColors.set(t.stepName,r),r}return[]}async changeStrokeColor(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher();e?.variant?r.updateMetadata(t.stepName,{strokeColor:e.variant.name}):r.updateMetadata(t.stepName,{strokeColor:e?.fill});const o=e?{browserValue:e.fill,pmsValue:e.pmsValue}:void 0;r.updateStorage(t.stepName,{strokeColor:o});for(const s of a){const l=new ea(s.id,o,t.data?.strokeThickness);i(l)}}getProcessedInput(t,e,a){const r=a?t:this.injectReplaceableText(t,e);return ke(r,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,a,r){const i=r.getStepStorage(a.stepName),o=kt(t,r),s=this.getProcessedInput(o,a.data,i?.customiseAllText??!1),l={command:void 0,helperData:{},errorData:this.getErrorsForText(t,s,a,r)};if(l.errorData)return l;l.helperData.charactersRemaining=a.data.maxLength-s.length;const c=[],d=new Map,u=new Map;for(const A of e){if(!A.fontData)throw new T("Failed to resolve font data for text.");const[h,g]=Jt(A.fontSize,A.fontData,{left:A.x,top:A.y,width:A.width,height:A.height,rotation:A.rotation},[s],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});d.set(A.id,h),u.set(A.id,g);const p=a.data.curved?s:(g||[]).join(`
1510
+ `)||t.includes("\r"))&&(i||(i={}),i.illegalMultipleLines=!0),i}}async init(t,e,a){const r=t.option;if(!r)return null;if(a)await this.reload(t,e,a);else{const i=this.getDefaultImageFillVariant(t.data),o=i?.asset?.fileLink,s=o?await pa(o):void 0,l=s?{src:s.src,height:s.height,width:s.width,scale:t.data.imageFillScale||1}:void 0,c=this.getDefaultStrokeColorVariant(t.data),d=t.data.strokeEnabled&&c?.color?{browserValue:c.color,pmsValue:c.name}:void 0;let u=t.data.defaultText||"";const A=e.getWorkflowExperience().getBundle();if(A&&t.globalPropertyAspectConfigurations){const p=A.getGlobalPropertyConfiguration()?.aspects?.find(m=>m.type===L.Text&&t.globalPropertyAspectConfigurations?.map(f=>f.aspectName).includes(m.name));if(p){const f=A.getGlobalPropertyStateManager().getAspect(p.name);f&&(u=f)}}e.updateStorage(t.stepName,{text:u,inputText:u,color:this.getDefaultColorVariant(t.data)?.color||this.getDefaultColor(t.data),fillImage:l,strokeColor:d}),e.updateMetadata(t.stepName,{text:u,color:this.getDefaultColorVariant(t.data)?.name||this.getDefaultColor(t.data),fillImage:i?.name,strokeColor:t.data.strokeEnabled?c?.color:void 0});const h=j.getDefaultVariant(r);if(h)return this.selectVariantCommand(t,h,{text:u},[],e,()=>{},()=>{},l,d)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map(i=>U(i.id,t.getAllLayoutData()))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const a=t.data.colorOption;if(a){const r=a.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i}))||[];return this.cachedColors.set(t.stepName,r),r}return[]}changeAlignment(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher();for(const o of a){const s=new gr(o.id,e);i(s)}}async changeFillColor(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher();e.variant?r.updateMetadata(t.stepName,{color:e.variant.name}):r.updateMetadata(t.stepName,{color:e.fill});const o=t.data.colorOption,s=o?this.createTextFillSpotColor(o,e.variant):void 0;o?r.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:o.colorProfile?.key}):r.updateStorage(t.stepName,{color:e.fill});for(const l of a){if(!e.fill)throw new Error("Fill not set on new color selection!");const c=new Ar(l.id,e.fill,s);i(c)}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const a=e.variants?.map(r=>r.asset?.fileLink)?.filter(r=>!!r)||[];return Promise.all(a.map(async r=>{const i=await pa(r);return{src:r,width:i.width,height:i.height,scale:t.data.imageFillScale||1}}))}return Promise.resolve([])}async changeFillImage(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher(),o=t.option?.variants?.find(s=>s.asset?.fileLink===e.src);r.updateMetadata(t.stepName,{fillImage:o?.name}),r.updateStorage(t.stepName,{fillImage:e});for(const s of a){const l=new ta(s.id,e);i(l)}}availableStrokeColors(t){const e=this.cachedStrokeColors.get(t.stepName);if(e)return e;const a=t.data.strokeOption;if(a){const r=a.variants?.map(i=>({fill:i.color,stroke:i.color,variant:i}))||[];return this.cachedStrokeColors.set(t.stepName,r),r}return[]}async changeStrokeColor(t,e,a,r){if(!t.data||!t.data.regions)return;const i=r.getCommandDispatcher();e?.variant?r.updateMetadata(t.stepName,{strokeColor:e.variant.name}):r.updateMetadata(t.stepName,{strokeColor:e?.fill});const o=e?{browserValue:e.fill,pmsValue:e.pmsValue}:void 0;r.updateStorage(t.stepName,{strokeColor:o});for(const s of a){const l=new ea(s.id,o,t.data?.strokeThickness);i(l)}}getProcessedInput(t,e,a){const r=a?t:this.injectReplaceableText(t,e);return ke(r,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,a,r){const i=r.getStepStorage(a.stepName),o=kt(t,r),s=this.getProcessedInput(o,a.data,i?.customiseAllText??!1),l={command:void 0,helperData:{},errorData:this.getErrorsForText(t,s,a,r)};if(l.errorData)return l;l.helperData.charactersRemaining=a.data.maxLength-s.length;const c=[],d=new Map,u=new Map;for(const A of e){if(!A.fontData)throw new T("Failed to resolve font data for text.");const[h,g]=Jt(A.fontSize,A.fontData,{left:A.x,top:A.y,width:A.width,height:A.height,rotation:A.rotation},[s],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});d.set(A.id,h),u.set(A.id,g);const p=a.data.curved?s:(g||[]).join(`
1511
1511
  `);c.push(this.generateTextChangeCommandsForRegion(h,a.data,A.id,p))}return!a.data.curved&&e.length>0&&!Array.from(u.values()).every(h=>h)?(l.errorData||(l.errorData={}),l.errorData.doesNotFit=!0,l):(r.updateStorage(a.stepName,{text:t}),r.updateMetadata(a.stepName,{text:s}),(i?.defaultCleared||!a.data.deleteDefaultOnFocus)&&s.trim()!==""&&r.setMandatoryFulfilled(a.stepName,!0),l.command=new R(c),l)}async selectVariant(t,e,a,r,i){const o=await this.selectVariantCommand(t,e,a.getStepStorage(t.stepName)||{},a.getRegionElements(t.stepName),a,r,i);o&&(o.command&&a.getCommandDispatcher()(o.command),o.followup&&await o.followup())}createTextFillSpotColor(t,e){const a=t.colorProfile;if(a){const r=(a.name||"").replace(/\s/g,"-"),i=r.lastIndexOf("/"),s=r.slice(i+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:s,namedColor:e.namedColor}}}async reload(t,e,a){const r=e.getSerializedStep(t.stepName,a.serializableWorkflow.steps),s=Object.values(a.layouts).map(c=>c.elements).flat().filter(c=>c.stepName===t.stepName),l=t.option;if(r?.selectedVariants){const c=r.selectedVariants[0].id;if(l&&c){const d=l.variants?.find(u=>u.id===c);if(d){const u=await this.fontDataFromVariant(d),A=s.map(m=>({id:m.id,region:m.stepRegion})),h=r.storage?.color;let g=r.storage?.text;const p=e.getWorkflowExperience().getBundle();if(p&&t.globalPropertyAspectConfigurations){const f=p.getGlobalPropertyConfiguration()?.aspects?.find(w=>w.type===L.Text&&t.globalPropertyAspectConfigurations?.map(I=>I.aspectName).includes(w.name));if(f){const I=p.getGlobalPropertyStateManager().getAspect(f.name);I&&(g=I)}}if(await e.setSelectionsAndElements(t.stepName,[d],A,async()=>{e.updateMetadata(t.stepName,{color:h,text:g}),e.updateStorage(t.stepName,{text:g,inputText:g});const m=s.map(w=>new Ca(w.id,u)),f=new R(m);e.getCommandDispatcher()(f)}),s.length===0&&l){const m=j.getDefaultVariant(l);if(m){const f=await this.selectVariantCommand(t,m,{text:g},[],e,()=>{},()=>{});e.getCommandDispatcher()(f.command)}}else{const{command:m}=q.updateInputText(g||"",s,t,e);m&&e.getCommandDispatcher()(m)}}}}else{const c=e.getWorkflowExperience().getBundle();if(c&&t.globalPropertyAspectConfigurations){const u=c.getGlobalPropertyConfiguration()?.aspects?.find(A=>A.type===L.Text&&t.globalPropertyAspectConfigurations?.map(h=>h.aspectName).includes(A.name));if(u){const h=c.getGlobalPropertyStateManager().getAspect(u.name);if(h)if(s.length===0&&l){const g=j.getDefaultVariant(l);if(g){const p=await this.selectVariantCommand(t,g,{text:h},[],e,()=>{},()=>{});e.getCommandDispatcher()(p.command)}}else{const{command:g}=q.updateInputText(h,s,t,e);g&&e.getCommandDispatcher()(g)}}}}}getDefaultColorVariant(t){const e=t.colorOption;if(e)return j.getDefaultVariant(e)}getDefaultColor(t){const e=t.colorOption;return e?j.getDefaultVariant(e)?.color:void 0}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return j.getDefaultVariant(e)}getDefaultStrokeColorVariant(t){const e=t.strokeOption;if(e)return j.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new pt(t);const a=e.fileLink;if(!a)throw new Nt(e);const r=await Bt(a);return{assetUrl:a,name:r.names.fullName.en}}async selectVariantCommand(t,e,a,r,i,o,s,l,c){const d=i.markUpdatePending(),u=await this.fontDataFromVariant(e);if(r.length>0){const A=r.map(p=>new Ca(p.id,u));if(l){const p=r.map(m=>new ta(m.id,l));A.push(...p)}if(c){const p=r.map(m=>new ea(m.id,c,t.data.strokeThickness));A.push(...p)}const h=await this.changeInputTextWithRegion(t,t.data.size||na,u,a.text||"",a,i,a?.customiseAllText??!1,o,s);return h&&A.push(h),{command:new R(A),followup:async()=>{i.markUpdateCompleted(d),await i.setSelectionsAndElements(t.stepName,[e],r)}}}else{const A=await this.createTextboxRegions(t.stepName,e,t.data,u,a,i),h=await this.changeInputTextWithRegion(t,t.data.size||na,u,A[0]?.newElement.input||a.text||t.data.defaultText||"",a,i,a?.customiseAllText??!1,o,s),g=A.flatMap(m=>m.commands);if(l){const m=A.map(f=>new ta(f.regionElement.id,l));g.push(...m)}if(c){const m=r.map(f=>new ea(f.id,c,t.data.strokeThickness));g.push(...m)}return h&&g.push(h),{command:new R(g),followup:async()=>{i.markUpdateCompleted(d)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,a,r,i,o){if(!a||!a.regions)throw new Error("Step data not supplied");const s=i.text||a.defaultText||"",l=kt(s,o),c=this.getProcessedInput(l,a,!1),d=async A=>{const g=o.getLayouts().find(m=>m.panelId===A.panelId),p=M();try{if(!g)throw new Ne("Failed to find layout for region: "+A.panelId);const m=a.colorOption;let f;if(m&&m.variants){const tt=m.variants.find(et=>et.id===m.defaultVariant?.id)||m.variants[0];f=this.createTextFillSpotColor(m,tt),o.updateStorage(t,{colorProfileAssetKey:m.colorProfile?.key})}const w=await this.getDefaultColor(a),I=w||"#000000",x={stepRegion:A,stepName:t,align:this.textAlign(a),fill:i.color?i.color:I,fontSize:a.size||na,fontData:r,id:p,layer:A.layer,layerIndex:A.layerIndex,rotation:A.rotation,text:c,input:s,type:F.Textbox,vertical:a.vertical,x:A.left,y:A.top,height:A.height,width:A.width,immutable:A.immutable,verticalAlign:a.verticalAlign||"middle",curved:a.curved,paths:a.paths,fillSpotColorDefinition:f},y=[],S=new Map,P=new Map;if(!x.fontData)throw new T("Failed to resolve font data for text.");const[b,D]=Jt(x.fontSize,x.fontData,{left:x.x,top:x.y,width:x.width,height:x.height,rotation:x.rotation,panelId:""},[c],{size:a.size,minSize:a.minSize,maxSize:a.maxSize});S.set(x.id,b),P.set(x.id,D);const $=a.curved||a.vertical?c:(D||[]).join(`
1512
1512
  `);y.push(this.generateTextChangeCommandsForRegion(b,a,x.id,$));const N=new z(x,g);return{regionElement:{id:p,region:A},commands:[N,...y],newElement:x,fontData:r}}catch(m){throw console.log(m),new Te("Error adding font to region")}},u=await Promise.all(a.regions.map(d)).catch(A=>{throw A instanceof Te?(Cr.setLatestToast("Failed to load font.",fe.Error),A):A instanceof Ne?A:new Error(A)});return await o.setSelectionsAndElements(t,[e],u.map(A=>A.regionElement),async()=>{o.updateMetadata(t,{text:s}),o.updateStorage(t,{text:s})}),u}generateTextChangeCommandsForRegion(t,e,a,r){const i=[],o=new mr(a,r);if(i.push(o),!e.size){const l=new hr(a,t);i.push(l)}return new R(i)}async changeInputTextWithRegion(t,e,a,r,i,o,s,l,c,d){const u=(r||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),A=kt(u,o),h=this.getProcessedInput(A,t.data,s),g=o.getRegionElements(t.stepName),p=new Map,m=new Map;for(const y of g)if(y.region){const[S,P]=Jt(e,a,y.region,[h],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});p.set(y.id,S),m.set(y.id,P)}const w=(()=>{if(t.data&&t.data.maxLength&&h.length>t.data.maxLength)return d&&d(!0),{info:"0"};const y=o.getWorkflowExperience().getProfanityList(),S=la.split(h.toLowerCase());for(const P of S)for(const b in y){const D=y[b].toLowerCase().replace(/\s/g,"");if(P===D)return l(!0),{error:"Blocked profanity."}}return!t.data.vertical&&!t.data.allowNewlines&&(h.includes(`
1513
1513
  `)||h.includes("\r"))?(l(!0),{error:"Cannot span multiple lines."}):!t.data.curved&&!Array.from(m.values()).every(b=>b)?(l(!0),{error:"Does not fit."}):(l(!1),{info:(t.data.maxLength-h.length).toString()})})();if(w.error){c(w.error);return}if(c(`${w.info} characters remaining`||""),d)return;o.updateStorage(t.stepName,{text:u}),o.updateMetadata(t.stepName,{text:this.injectReplaceableText(u,t.data)}),(i.defaultCleared||!t.data.deleteDefaultOnFocus)&&u.trim()!==""&&o.setMandatoryFulfilled(t.stepName,!0);const I=[];for(const y of g){const S=t.data.curved?h:(m.get(y.id)||[]).join(`
@@ -2246,7 +2246,7 @@
2246
2246
  mutation DeleteBundle($id: String!) {
2247
2247
  bundleDelete(id: $id)
2248
2248
  }
2249
- `;var fe=(n=>(n.Error="Error",n.Warning="Warning",n.Info="Info",n))(fe||{});const Wl=1e3;class mn extends ka{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},Wl)})}}const Hl=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:M(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),Yl=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(r=>r.layout):Hl(t.panels)};class Jl{constructor(t,e,a,r,i,o=!1,s,l=!1,c=!1,d=!1){this.workflowStatePromiseQueue=new Ma(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async A=>{this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.reloadedState?this.layouts=Object.values(this.reloadedState.layouts||{}).map(g=>g.layout):A?this.layouts=Yl(this.experience.getTransaction(),A):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new sl(this.layouts),this.renderableContextService.setWorkflowManager(this),A.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(A),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(g=>{throw console.error(g),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.commandContext.registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()})),h&&await this.injectIntoPreviewService(h,!0)},this.renderLayouts=()=>{if(!this.previewService)return;const A=this.getCommandContext().getAllLayouts(),h=this.getLayoutPreviewService()?.getAll();if(h)for(const[,g]of h)g.render(A)},this.experience=t,this.client=e,this.updateTransaction=a,this.graphQlClient=r,this.reloadedState=i,this.readOnly=o,this.singleVariantsRenderable=c,this.commandContext=new lr,this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.modelContainer=s,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.isReloadedTransaction=l,d&&(this.workflowStatePromiseQueue.enabled=!1);const u=this.experience.getWorkflow();u&&this.setWorkflow(u)}getTemplatingContext(){const t=this.experience.getTransaction().recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const r=a.uniqueIdentifier??a.title??"";a.type===_t.FirstName?e[r]=t?.firstName:a.type===_t.LastName?e[r]=t?.lastName:a.type===_t.Custom&&(a.customFieldIndex===1?e[r]=t?.customField1:a.customFieldIndex===2?e[r]=t?.customField2:a.customFieldIndex===3?e[r]=t?.customField3:a.customFieldIndex===4?e[r]=t?.customField4:a.customFieldIndex===5&&(e[r]=t?.customField5))}),e}async updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,g,p,m,f){const w=this.experience.getTransaction();if(w.recipient?.id)this.experience.getTransaction().recipient={id:w.recipient.id,firstName:t??w.recipient.firstName,lastName:e??w.recipient.lastName,address:a??w.recipient.address,suburb:r??w.recipient.suburb,state:i??w.recipient.state,email:o??w.recipient.email,postalCode:s??w.recipient.postalCode,country:l??w.recipient.country,mobile:c??w.recipient.mobile,company:d??w.recipient.company,apartment:u??w.recipient.apartment,customField1:A??w.recipient.customField1,customField2:h??w.recipient.customField2,customField3:g??w.recipient.customField3,customField4:p??w.recipient.customField4,customField5:m??w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId},await this.graphQlClient().mutate({mutation:ql,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:w.recipient.id,firstName:t||w.recipient.firstName,lastName:e||w.recipient.lastName,address:a||w.recipient.address,suburb:r||w.recipient.suburb,state:i||w.recipient.state,email:o||w.recipient.email,postalCode:s||w.recipient.postalCode,country:l||w.recipient.country,mobile:c||w.recipient.mobile,company:d||w.recipient.company,apartment:u||w.recipient.apartment,customField1:A||w.recipient.customField1,customField2:h||w.recipient.customField2,customField3:g||w.recipient.customField3,customField4:p||w.recipient.customField4,customField5:m||w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId}});else{const I=await this.graphQlClient().mutate({mutation:zl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:r,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f}});w.recipient={id:I?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:r,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f},await this.graphQlClient().mutate({mutation:Gl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,recipientId:I.data?.recipientCreate?.id},context:{transactionOwnerId:this.experience.getTransaction().transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(I=>I(this.experience.getTransaction().recipient))}async fetchConversionConfiguration(){const t=this.experience.getTransaction().recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=await this.graphQlClient().query({query:yo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}});e.data.conversionConfiguration&&(this.recipientConversionConfiguration=e.data.conversionConfiguration)}}async initializeDefaultWorkflowState(t){const e=()=>{const s=t.finalizeStepConfig;if(!s)return;const l=s.lookAtAnimation,c=s.modelAnimation;l&&this.previewService?.executeCameraAnimation(l),c&&this.modelContainer?.executeAnimation(c)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(s=>{this.storage[s.stepName]=s.storage||{}}),await this.fetchConversionConfiguration(),this.allScenes=await Lo(t);const r=St(this.allScenes,this.stepSelections).map(s=>s.silentSteps).flat(),{stepElements:i,commands:o}=await this.stepElementsForIntroducedSilentSteps(r,!!this.reloadedState);this.commandContext.apply(new R(o),!0),this.stepElements={...this.stepElements,...i},await this.ensureStepsAreLoaded(),this.isReloadedTransaction||this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}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.experience.getTransaction().recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(t=>t.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.experience.getWorkflow()?.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!0}),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter(e=>e!==t)}markUpdatePending(){const t=M();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}getMandatoryUnfulfilledSteps(){return St(this.allScenes,this.stepSelections).flatMap(i=>i.renderableSteps).filter(i=>i.mandatory).filter(i=>!this.mandatorySteps[i.stepName]).map(i=>i.stepName)}setStepError(t,e,a){let r=!1;if(!this.validationErrors.steps.has(t)&&a)r=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const i=this.validationErrors.steps.get(t);a&&a!==i.get(e)?(r=!0,i.set(e,a)):a||(r=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}r&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");this.previewService=t;const a=this.experience.getProduct();if(!a?.modelUrl||!this.previewService)return;const r=t.loadModel({model:a.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(r),St(this.allScenes,this.stepSelections).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===E.Model||s.type===E.Material).forEach(s=>{if(!s.option?.id){console.error(`Failed to read option id from step: ${s.stepName}`);return}const l=this.stepSelections[s.stepName]?.selectedVariants||[];if(l.length===0)return;const c=l[0];if(s.type===E.Model){if(!this.modelContainer)throw new T("We should always have a model container when injecting a preview!");const d=c.asset?.fileLink;if(!d){console.error(`Failed to read model url from variant: ${c.id} for step: ${s.stepName}`);return}const u=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:d,contextService:this.getLayoutPreviewService()},u.replaceProductModel||!1)}else{const d=c.material;if(!d){console.error(`Failed to read material from variant: ${c.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new T("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,s.option.id,d)})}}),await r.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(!Zt(a,this.storage)){this.storage=a;const r=new dn(this.constructSerializableWorkflow());this.commandContext.apply(r,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const r={stepName:a.stepName};r.storage=this.storage[a.stepName],r.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(i=>({id:i.id,priceModifier:i.priceModifier})),t.push(r)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new mn(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new mn(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new T("Attempted to serialize state before it was initialized.");const e=bt(t.transaction),a=this.dehydrateState(e);return JSON.stringify(a)}dehydrateState(t){for(const e of Object.values(t.layouts).map(a=>a.elements).flat())e.type==="illustration"&&(delete e.cachedObjectURL,e.src&&delete e.svg),e.type==="frame"&&delete e.pattern?.svg;return this.deleteFieldNameFromObjectRecursive(t,"__typename"),t}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,r)=>Object.keys(a).reduce((i,o)=>{const s=[...a[o]||[]];return r.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),i[o]=s,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.experience.getWorkflow()?.steps.reduce((t,e)=>(Et(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])||[]}getInvalidModelVariants(){return this.experience.getWorkflow()?.steps.reduce((t,e)=>(e.type===E.Model&&!Et(e,this.stepSelections)&&t.push(e.stepName),t),[])||[]}async stepElementsForIntroducedSilentSteps(t,e){const a=this.experience.getProduct();if(!a)return Promise.resolve({stepElements:{},commands:[]});const r=async(c,d,u)=>{if(c.type===E.SilentIllustration){const A=await new un(c,d).trigger();return{step:c,results:A}}else if(c.type===E.ProductOverlay){const A=await new un(c,d,u).trigger();return{step:c,results:A}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||s.push(r(c,this.layouts,a));const l=await Promise.all(s);for(const c of l)o.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),o.commands=[...o.commands,...c.results.map(d=>d.command)];return o}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=t}async updateTransactionStakeholders(){const t=await v.getShadowGraphqlClient().query({query:Io,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=t.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await v.getShadowGraphqlClient().mutate({mutation:Ll,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async rejectTransaction(t){await v.getShadowGraphqlClient().mutate({mutation:Vl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,r){const i=this.experience.getWorkflow();if(!i)throw new Error("Attempted to set selections when no workflow is set!");const o=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((S,P)=>S+P.selectedVariants.map(b=>b.priceModifier||0).reduce((b,D)=>b+D,0),0),i.steps.forEach(S=>{Et(S,this.stepSelections)||(this.stepInitialised[S.stepName]=!1,delete this.stepMetadata[S.stepName],delete this.stepSelections[S.stepName],delete this.storage[S.stepName])});const s=this.allScenes,l=St(s,o),c=St(s,this.stepSelections),d=l.map(S=>S.silentSteps).flat(),A=c.map(S=>S.silentSteps).flat().filter(S=>!d.some(P=>P.stepName===S.stepName));d.forEach(S=>{Et(S,this.stepSelections)||(this.stepInitialised[S.stepName]=!1)});const h=this.getInvalidCanvasRegions(),{stepElements:g,commands:p}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...g,[t]:a},this.removeElements(h);const m=i.steps.find(S=>S.stepName===t);m?.type===E.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(P=>P.id));const f=h.map(S=>new Pt(S.id)),w=new dn(this.constructSerializableWorkflow()),I=[...p,...f,w];I.length>0&&this.commandContext.apply(new R(I),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const x=this.getInvalidModelVariants(),y=this.modelContainer;if(y){const S=x.map(P=>y.applyModelVariant(P,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(S)}await this.onSelectionChange(),r&&await r()}async ensureStepsAreLoaded(){const e=St(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],r=e.flat();for(const l of r)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case E.DigitalContent:a.push($a.init(l,this,this.reloadedState));break;case E.Frame:a.push(ht.init(l,this,this.reloadedState));break;case E.Illustration:a.push(Yt.init(l,this,this.reloadedState));break;case E.Material:a.push(Ua.init(l,this,this.reloadedState));break;case E.Model:a.push(La.init(l,this,this.reloadedState));break;case E.Module:this.stepSpecificServices[l.stepName]={module:await wr(l.data.module)},a.push(Va.init(l,this,this.reloadedState));break;case E.Picture:a.push(za.init(l,this,this.reloadedState));break;case E.Question:a.push(qa.init(l,this,this.reloadedState));break;case E.Shape:a.push(Ft.init(l,this,this.reloadedState));break;case E.Text:a.push(q.init(l,this,this.reloadedState));break}const i=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=i.filter(l=>!!l&&!!l.command).map(l=>l.command),s=i.filter(l=>!!l&&!!l.followup).map(l=>l.followup);o&&o.length>0&&this.commandContext.apply(new R(o),!0);for(const l of s)await l();s.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(t=>t(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(t=>t(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(t=>t(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(t=>t(this.informationResults))}onInitChange(){this.initCallbacks.forEach(t=>t(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(t=>{t(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(t=>t(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(t=>{t(this.stepMetadata)})}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach(e=>e(this.storage[t]))}onStorageChange(){this.storageCallbacks.forEach(t=>t(this.storage))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return qo(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class nt{constructor(t){this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.asset?.versions?.find(t=>t.name==="cdn")?.link}getAssetResource(){return this.variantData.asset}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find(a=>a.name==="thumbnail")?.link,e=this.variantData.thumbnail?.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}const Xt=class Xt{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){Xt.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,t)}getUpdateState(){return!!Xt.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new nt(a)}getAvailableVariants(){return(this.step.option?.variants?.filter(e=>e.enabled)||[]).map(e=>new nt(e))}getAllVariants(){return(this.step.option?.variants||[]).map(e=>new nt(e))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.tags}hasTag(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){const a=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){return this.step.globalPropertyAspectConfigurations?.filter(e=>e.globalPropertyConfigurationId===t&&e.aspectName).map(e=>e.aspectName)??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),r=this.step.data.modelAnimation,i=this.step.data.lookAtAnimation;e?i&&e.executeCameraAnimation(i):console.warn("No preview service available, cannot execute camera animations."),a?r&&a.executeAnimation(r,t):console.warn("No model container available, cannot execute model animations.")}};Xt.updateState=new Map;let _=Xt;class Sr extends _{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Yt.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=U(t[0].id,this.manager.getAllLayoutData()).colors,i=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=i?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=i.channelNumbers.find(d=>d.number===l.channelNumber);if(c){const d=c.id.replace(/\W/g,"");s[l.channelNumber]={browserValue:a[d]?.browserValue||""}}}),s}try{return a}catch(s){console.error(s)}}setColor(t,e,a){const r=new Map,o=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(o?.defaultColorVariants||[]).length!==0?o.channelNumbers.forEach(l=>{if(l.number.toString()===t){const c=l.id.replace(/\W/g,"");a?r.set(c,{browserValue:e,pmsValue:a}):r.set(c,e)}}):a?r.set(t,{browserValue:e,pmsValue:a}):r.set(t,e),Yt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),r)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?Yt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}}class vr extends _{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ua.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Er extends _{constructor(t,e,a){super(t,e,a)}selectVariant(t){return La.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class br extends _{constructor(t,e,a){super(t,e,a)}selectVariant(t){return za.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Ir extends _{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await qa.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class Br extends _{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return Ft.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Ft.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Ft.availableColours(this.step)}setCustomColor(t){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),Ft.setCustomColor(t,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const t=this.manager.getStepStorage(this.step.stepName)?.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}}class Pr extends _{constructor(t,e,a){super(t,e,a)}async selectVariant(t){q.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:fe.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(r=>r.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?q.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return q.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return q.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);q.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,r=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:r,defaultCleared:!1}),this.setText(r)}setText(t){const e={input:t,helperData:{}},a=q.findLayoutElements(this.manager,this.step),r=q.filterUnsupportedCharacters(t,a[0]?.fontData),i=kt(r,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&i>this.step.data.maxLength;o||(e.input=r);const s=a.length<=0,l=s?{inputText:r,text:r}:{inputText:r};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=q.getProcessedInput(r,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:u,errorData:A,helperData:h}=q.updateInputText(r,a,this.step,this.manager);u&&this.manager.getCommandDispatcher()(u),e.helperData=h,e.errorData=A,!o&&!A&&this.manager.updateMetadata(this.step.stepName,{text:d})}return e}getText(){const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&e?.defaultCleared!==void 0&&!e?.defaultCleared?t:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=q.findLayoutElements(this.manager,this.step);return q.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=kt(this.getText(),this.manager);return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}getAvailableStrokeColors(){return this.step.data.strokeEnabled?q.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeStrokeColor(this.step,t,e,this.manager)}}class xr extends _{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Dr extends _{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return $a.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Fr extends _{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=kt(this.getText(),this.manager);return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(t){Va.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:fe.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(r=>r.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class ve{static get(t,e){switch(e.type){case E.DigitalContent:return new Dr(t,e,t.getStepTags(e.stepName));case E.Information:return new xr(t,e,t.getStepTags(e.stepName));case E.Question:return new Ir(t,e,t.getStepTags(e.stepName));case E.Text:return new Pr(t,e,t.getStepTags(e.stepName));case E.Illustration:return new Sr(t,e,t.getStepTags(e.stepName));case E.Picture:return new br(t,e,t.getStepTags(e.stepName));case E.Shape:return new Br(t,e,t.getStepTags(e.stepName));case E.Material:return new vr(t,e,t.getStepTags(e.stepName));case E.Model:return new Er(t,e,t.getStepTags(e.stepName));case E.Frame:return new ti(t,e,t.getStepTags(e.stepName));case E.Module:return new Fr(t,e,t.getStepTags(e.stepName));default:throw new T(`Step type ${e.type} not yet supported in Core SDK`)}}}const kr=C.gql`
2249
+ `;var fe=(n=>(n.Error="Error",n.Warning="Warning",n.Info="Info",n))(fe||{});const Wl=1e3;class mn extends ka{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},Wl)})}}const Hl=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:M(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),Yl=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(r=>r.layout):Hl(t.panels)};class Jl{constructor(t,e,a,r,i,o=!1,s,l=!1,c=!1,d=!1){this.workflowStatePromiseQueue=new Ma(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async A=>{this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.reloadedState?this.layouts=Object.values(this.reloadedState.layouts||{}).map(g=>g.layout):A?this.layouts=Yl(this.experience.getTransaction(),A):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new sl(this.layouts),this.renderableContextService.setWorkflowManager(this),A.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(A),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(g=>{throw console.error(g),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.commandContext.registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()})),h&&await this.injectIntoPreviewService(h,!0)},this.experience=t,this.client=e,this.updateTransaction=a,this.graphQlClient=r,this.reloadedState=i,this.readOnly=o,this.singleVariantsRenderable=c,this.commandContext=new lr,this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.modelContainer=s,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.isReloadedTransaction=l,d&&(this.workflowStatePromiseQueue.enabled=!1);const u=this.experience.getWorkflow();u&&this.setWorkflow(u)}getTemplatingContext(){const t=this.experience.getTransaction().recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const r=a.uniqueIdentifier??a.title??"";a.type===_t.FirstName?e[r]=t?.firstName:a.type===_t.LastName?e[r]=t?.lastName:a.type===_t.Custom&&(a.customFieldIndex===1?e[r]=t?.customField1:a.customFieldIndex===2?e[r]=t?.customField2:a.customFieldIndex===3?e[r]=t?.customField3:a.customFieldIndex===4?e[r]=t?.customField4:a.customFieldIndex===5&&(e[r]=t?.customField5))}),e}async updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,g,p,m,f){const w=this.experience.getTransaction();if(w.recipient?.id)this.experience.getTransaction().recipient={id:w.recipient.id,firstName:t??w.recipient.firstName,lastName:e??w.recipient.lastName,address:a??w.recipient.address,suburb:r??w.recipient.suburb,state:i??w.recipient.state,email:o??w.recipient.email,postalCode:s??w.recipient.postalCode,country:l??w.recipient.country,mobile:c??w.recipient.mobile,company:d??w.recipient.company,apartment:u??w.recipient.apartment,customField1:A??w.recipient.customField1,customField2:h??w.recipient.customField2,customField3:g??w.recipient.customField3,customField4:p??w.recipient.customField4,customField5:m??w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId},await this.graphQlClient().mutate({mutation:ql,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:w.recipient.id,firstName:t||w.recipient.firstName,lastName:e||w.recipient.lastName,address:a||w.recipient.address,suburb:r||w.recipient.suburb,state:i||w.recipient.state,email:o||w.recipient.email,postalCode:s||w.recipient.postalCode,country:l||w.recipient.country,mobile:c||w.recipient.mobile,company:d||w.recipient.company,apartment:u||w.recipient.apartment,customField1:A||w.recipient.customField1,customField2:h||w.recipient.customField2,customField3:g||w.recipient.customField3,customField4:p||w.recipient.customField4,customField5:m||w.recipient.customField5,conversionConfigurationId:f||w.recipient.conversionConfigurationId}});else{const I=await this.graphQlClient().mutate({mutation:zl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:r,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f}});w.recipient={id:I?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:r,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:u,customField1:A,customField2:h,customField3:g,customField4:p,customField5:m,conversionConfigurationId:f},await this.graphQlClient().mutate({mutation:Gl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,recipientId:I.data?.recipientCreate?.id},context:{transactionOwnerId:this.experience.getTransaction().transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(I=>I(this.experience.getTransaction().recipient))}async fetchConversionConfiguration(){const t=this.experience.getTransaction().recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=await this.graphQlClient().query({query:yo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}});e.data.conversionConfiguration&&(this.recipientConversionConfiguration=e.data.conversionConfiguration)}}async initializeDefaultWorkflowState(t){const e=()=>{const s=t.finalizeStepConfig;if(!s)return;const l=s.lookAtAnimation,c=s.modelAnimation;l&&this.previewService?.executeCameraAnimation(l),c&&this.modelContainer?.executeAnimation(c)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(s=>{this.storage[s.stepName]=s.storage||{}}),await this.fetchConversionConfiguration(),this.allScenes=await Lo(t);const r=St(this.allScenes,this.stepSelections).map(s=>s.silentSteps).flat(),{stepElements:i,commands:o}=await this.stepElementsForIntroducedSilentSteps(r,!!this.reloadedState);this.commandContext.apply(new R(o),!0),this.stepElements={...this.stepElements,...i},await this.ensureStepsAreLoaded(),this.isReloadedTransaction||this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}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.experience.getTransaction().recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(t=>t.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.experience.getWorkflow()?.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!0}),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter(e=>e!==t)}markUpdatePending(){const t=M();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}getMandatoryUnfulfilledSteps(){return St(this.allScenes,this.stepSelections).flatMap(i=>i.renderableSteps).filter(i=>i.mandatory).filter(i=>!this.mandatorySteps[i.stepName]).map(i=>i.stepName)}setStepError(t,e,a){let r=!1;if(!this.validationErrors.steps.has(t)&&a)r=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const i=this.validationErrors.steps.get(t);a&&a!==i.get(e)?(r=!0,i.set(e,a)):a||(r=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}r&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");this.previewService=t;const a=this.experience.getProduct();if(!a?.modelUrl||!this.previewService)return;const r=t.loadModel({model:a.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(r),St(this.allScenes,this.stepSelections).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===E.Model||s.type===E.Material).forEach(s=>{if(!s.option?.id){console.error(`Failed to read option id from step: ${s.stepName}`);return}const l=this.stepSelections[s.stepName]?.selectedVariants||[];if(l.length===0)return;const c=l[0];if(s.type===E.Model){if(!this.modelContainer)throw new T("We should always have a model container when injecting a preview!");const d=c.asset?.fileLink;if(!d){console.error(`Failed to read model url from variant: ${c.id} for step: ${s.stepName}`);return}const u=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:d,contextService:this.getLayoutPreviewService()},u.replaceProductModel||!1)}else{const d=c.material;if(!d){console.error(`Failed to read material from variant: ${c.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new T("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,s.option.id,d)})}}),await r.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(!Zt(a,this.storage)){this.storage=a;const r=new dn(this.constructSerializableWorkflow());this.commandContext.apply(r,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const r={stepName:a.stepName};r.storage=this.storage[a.stepName],r.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(i=>({id:i.id,priceModifier:i.priceModifier})),t.push(r)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new mn(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}))}renderLayouts(){if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,a]of e)a.render(t)}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new mn(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new T("Attempted to serialize state before it was initialized.");const e=bt(t.transaction),a=this.dehydrateState(e);return JSON.stringify(a)}dehydrateState(t){for(const e of Object.values(t.layouts).map(a=>a.elements).flat())e.type==="illustration"&&(delete e.cachedObjectURL,e.src&&delete e.svg),e.type==="frame"&&delete e.pattern?.svg;return this.deleteFieldNameFromObjectRecursive(t,"__typename"),t}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,r)=>Object.keys(a).reduce((i,o)=>{const s=[...a[o]||[]];return r.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),i[o]=s,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.experience.getWorkflow()?.steps.reduce((t,e)=>(Et(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])||[]}getInvalidModelVariants(){return this.experience.getWorkflow()?.steps.reduce((t,e)=>(e.type===E.Model&&!Et(e,this.stepSelections)&&t.push(e.stepName),t),[])||[]}async stepElementsForIntroducedSilentSteps(t,e){const a=this.experience.getProduct();if(!a)return Promise.resolve({stepElements:{},commands:[]});const r=async(c,d,u)=>{if(c.type===E.SilentIllustration){const A=await new un(c,d).trigger();return{step:c,results:A}}else if(c.type===E.ProductOverlay){const A=await new un(c,d,u).trigger();return{step:c,results:A}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||s.push(r(c,this.layouts,a));const l=await Promise.all(s);for(const c of l)o.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),o.commands=[...o.commands,...c.results.map(d=>d.command)];return o}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=t}async updateTransactionStakeholders(){const t=await v.getShadowGraphqlClient().query({query:Io,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=t.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await v.getShadowGraphqlClient().mutate({mutation:Ll,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async rejectTransaction(t){await v.getShadowGraphqlClient().mutate({mutation:Vl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:t}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,r){const i=this.experience.getWorkflow();if(!i)throw new Error("Attempted to set selections when no workflow is set!");const o=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((S,P)=>S+P.selectedVariants.map(b=>b.priceModifier||0).reduce((b,D)=>b+D,0),0),i.steps.forEach(S=>{Et(S,this.stepSelections)||(this.stepInitialised[S.stepName]=!1,delete this.stepMetadata[S.stepName],delete this.stepSelections[S.stepName],delete this.storage[S.stepName])});const s=this.allScenes,l=St(s,o),c=St(s,this.stepSelections),d=l.map(S=>S.silentSteps).flat(),A=c.map(S=>S.silentSteps).flat().filter(S=>!d.some(P=>P.stepName===S.stepName));d.forEach(S=>{Et(S,this.stepSelections)||(this.stepInitialised[S.stepName]=!1)});const h=this.getInvalidCanvasRegions(),{stepElements:g,commands:p}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...g,[t]:a},this.removeElements(h);const m=i.steps.find(S=>S.stepName===t);m?.type===E.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(P=>P.id));const f=h.map(S=>new Pt(S.id)),w=new dn(this.constructSerializableWorkflow()),I=[...p,...f,w];I.length>0&&this.commandContext.apply(new R(I),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const x=this.getInvalidModelVariants(),y=this.modelContainer;if(y){const S=x.map(P=>y.applyModelVariant(P,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(S)}await this.onSelectionChange(),r&&await r()}async ensureStepsAreLoaded(){const e=St(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],r=e.flat();for(const l of r)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case E.DigitalContent:a.push($a.init(l,this,this.reloadedState));break;case E.Frame:a.push(ht.init(l,this,this.reloadedState));break;case E.Illustration:a.push(Yt.init(l,this,this.reloadedState));break;case E.Material:a.push(Ua.init(l,this,this.reloadedState));break;case E.Model:a.push(La.init(l,this,this.reloadedState));break;case E.Module:this.stepSpecificServices[l.stepName]={module:await wr(l.data.module)},a.push(Va.init(l,this,this.reloadedState));break;case E.Picture:a.push(za.init(l,this,this.reloadedState));break;case E.Question:a.push(qa.init(l,this,this.reloadedState));break;case E.Shape:a.push(Ft.init(l,this,this.reloadedState));break;case E.Text:a.push(q.init(l,this,this.reloadedState));break}const i=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=i.filter(l=>!!l&&!!l.command).map(l=>l.command),s=i.filter(l=>!!l&&!!l.followup).map(l=>l.followup);o&&o.length>0&&this.commandContext.apply(new R(o),!0);for(const l of s)await l();s.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(t=>t(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(t=>t(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(t=>t(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(t=>t(this.informationResults))}onInitChange(){this.initCallbacks.forEach(t=>t(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(t=>{t(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(t=>t(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(t=>{t(this.stepMetadata)})}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach(e=>e(this.storage[t]))}onStorageChange(){this.storageCallbacks.forEach(t=>t(this.storage))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return qo(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class nt{constructor(t){this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.asset?.versions?.find(t=>t.name==="cdn")?.link}getAssetResource(){return this.variantData.asset}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find(a=>a.name==="thumbnail")?.link,e=this.variantData.thumbnail?.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}const Xt=class Xt{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){Xt.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,t)}getUpdateState(){return!!Xt.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new nt(a)}getAvailableVariants(){return(this.step.option?.variants?.filter(e=>e.enabled)||[]).map(e=>new nt(e))}getAllVariants(){return(this.step.option?.variants||[]).map(e=>new nt(e))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.tags}hasTag(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){const a=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){return this.step.globalPropertyAspectConfigurations?.filter(e=>e.globalPropertyConfigurationId===t&&e.aspectName).map(e=>e.aspectName)??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),r=this.step.data.modelAnimation,i=this.step.data.lookAtAnimation;e?i&&e.executeCameraAnimation(i):console.warn("No preview service available, cannot execute camera animations."),a?r&&a.executeAnimation(r,t):console.warn("No model container available, cannot execute model animations.")}};Xt.updateState=new Map;let _=Xt;class Sr extends _{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Yt.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=U(t[0].id,this.manager.getAllLayoutData()).colors,i=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=i?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=i.channelNumbers.find(d=>d.number===l.channelNumber);if(c){const d=c.id.replace(/\W/g,"");s[l.channelNumber]={browserValue:a[d]?.browserValue||""}}}),s}try{return a}catch(s){console.error(s)}}setColor(t,e,a){const r=new Map,o=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(o?.defaultColorVariants||[]).length!==0?o.channelNumbers.forEach(l=>{if(l.number.toString()===t){const c=l.id.replace(/\W/g,"");a?r.set(c,{browserValue:e,pmsValue:a}):r.set(c,e)}}):a?r.set(t,{browserValue:e,pmsValue:a}):r.set(t,e),Yt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),r)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?Yt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}}class vr extends _{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ua.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Er extends _{constructor(t,e,a){super(t,e,a)}selectVariant(t){return La.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class br extends _{constructor(t,e,a){super(t,e,a)}selectVariant(t){return za.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Ir extends _{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await qa.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class Br extends _{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return Ft.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return Ft.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Ft.availableColours(this.step)}setCustomColor(t){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),Ft.setCustomColor(t,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const t=this.manager.getStepStorage(this.step.stepName)?.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}}class Pr extends _{constructor(t,e,a){super(t,e,a)}async selectVariant(t){q.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:fe.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(r=>r.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?q.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return q.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return q.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);q.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,r=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:r,defaultCleared:!1}),this.setText(r)}setText(t){const e={input:t,helperData:{}},a=q.findLayoutElements(this.manager,this.step),r=q.filterUnsupportedCharacters(t,a[0]?.fontData),i=kt(r,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&i>this.step.data.maxLength;o||(e.input=r);const s=a.length<=0,l=s?{inputText:r,text:r}:{inputText:r};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=q.getProcessedInput(r,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:u,errorData:A,helperData:h}=q.updateInputText(r,a,this.step,this.manager);u&&this.manager.getCommandDispatcher()(u),e.helperData=h,e.errorData=A,!o&&!A&&this.manager.updateMetadata(this.step.stepName,{text:d})}return e}getText(){const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&e?.defaultCleared!==void 0&&!e?.defaultCleared?t:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=q.findLayoutElements(this.manager,this.step);return q.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=kt(this.getText(),this.manager);return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}getAvailableStrokeColors(){return this.step.data.strokeEnabled?q.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeStrokeColor(this.step,t,e,this.manager)}}class xr extends _{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class Dr extends _{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return $a.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Fr extends _{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=kt(this.getText(),this.manager);return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(t){Va.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:fe.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(r=>r.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class ve{static get(t,e){switch(e.type){case E.DigitalContent:return new Dr(t,e,t.getStepTags(e.stepName));case E.Information:return new xr(t,e,t.getStepTags(e.stepName));case E.Question:return new Ir(t,e,t.getStepTags(e.stepName));case E.Text:return new Pr(t,e,t.getStepTags(e.stepName));case E.Illustration:return new Sr(t,e,t.getStepTags(e.stepName));case E.Picture:return new br(t,e,t.getStepTags(e.stepName));case E.Shape:return new Br(t,e,t.getStepTags(e.stepName));case E.Material:return new vr(t,e,t.getStepTags(e.stepName));case E.Model:return new Er(t,e,t.getStepTags(e.stepName));case E.Frame:return new ti(t,e,t.getStepTags(e.stepName));case E.Module:return new Fr(t,e,t.getStepTags(e.stepName));default:throw new T(`Step type ${e.type} not yet supported in Core SDK`)}}}const kr=C.gql`
2250
2250
  fragment CreateDesignTransaction on Transaction {
2251
2251
  id
2252
2252
  designName
@@ -2640,7 +2640,7 @@
2640
2640
  }
2641
2641
  }
2642
2642
  }
2643
- `;class Fc{constructor(t,e=v.getShadowGraphqlClient.bind(v)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class kc{init(t,e,a){this.cognitoClient=new Ce.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new Ce.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new Ce.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new Ce.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Gt=new kc;class Hr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return mi(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Za.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Za.code(e)?.code==="CLP")return"USD0,0"}}const fn=new Hr;class Yr{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,fn.getPrecisionForCurrency(e))}}const Mc=async(n,t)=>{const e=await v.getShadowGraphqlClient().query({query:ko(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&O.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&O.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&O.cacheAsset(o.asset),o.thumbnail&&O.cacheAsset(o.thumbnail),o.material&&O.cacheMaterial(o.material)}),Ot.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},Tc=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},Ja=async(n,t)=>{const e=n.map(s=>Ot.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=Mc(a,t),i=a.map(s=>Ot.set({id:s,options:t},Tc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},Jr=async(n,t)=>(await Ja([n],t))[0];class Nc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return v.getShadowGraphqlClient().mutate({...e,mutation:fo})}catch(a){throw console.error(a),new gt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ti(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 33.2.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ut.setHubUrl(t.hubUrl),ut.setServerUrl(t.serverUrl),ut.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&&Vn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Gt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return O}getFlowService(){if(!Ni())throw new Error("Application key required to use Flow Service.");return new Gr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await v.getShadowGraphqlClient().query({query:Uo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new Yr(o,s,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Kr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}async authenticateBundleFromLocalStorage(t){if(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=v.getShadowGraphqlClient(),a=await e.query({query:Mo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const A=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(A)return Promise.resolve({success:!0,stakeholderType:A.type})}const c=(await e.query({query:To,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await v.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=v.getShadowGraphqlClient(),r=(await e.query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:Pc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await Gt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await v.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await v.getShadowGraphqlClient().mutate({mutation:xc,variables:{emailAddress:t}}),await Gt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await Gt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await v.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),r=new Date().getTime()/1e3,i=!a?.AccessToken||Kt(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await Gt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await v.getShadowGraphqlClient().query({query:Dc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await v.getShadowGraphqlClient().mutate({mutation:bl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!i?.id)throw new Error("Unable to create bundle");const o=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new ra(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const p=Object.entries(localStorage).find(([f,w])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",m=localStorage.getItem(p);m&&!Kt(m)&&(s.Authorization=`Bearer ${m}`)}const l={bundleOwnerId:o,...s,...r?.graphql?.additionalHeaders},c=await v.getShadowGraphqlClient().query({query:wl(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],u=k.getMap("bundlePartnerIds")||new Map;u.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",u);const A=new ra(this,d,e,a,o,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:r?.readonly});return await A.getInitializationPromise(),A}async duplicateBundle(t,e,a,r){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const A=await this.loggedInBearerToken();o.Authorization=`Bearer ${A}`}catch{const g=Object.entries(localStorage).find(([m,f])=>m.startsWith("CognitoIdentityServiceProvider")&&m.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(g);p&&!Kt(p)&&(o.Authorization=`Bearer ${p}`)}const s={bundleOwnerId:i,...o,...r?.graphql?.additionalHeaders},c=(await v.getShadowGraphqlClient().mutate({mutation:Il(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const u=k.getMap("bundleOwnerIds")||new Map;return u.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",u),async()=>{const A=new ra(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await A.getInitializationPromise(),A}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await v.getShadowGraphqlClient().query({query:Rl(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await v.getShadowGraphqlClient().query({query:yl,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],r=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",r),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),r=a[0],i=r.getWorkflow();return e&&!i&&console.error("No workflow instantiated when trying to create preview service."),e&&i&&await r.getWorkflowManager().injectIntoPreviewService(e(i)),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new gt("No options provided!");const a=v.getShadowGraphqlClient(),r=async y=>{if(y.length===0)return[];const S=y.map(D=>D.option.transactionId),P=await a.query({query:po,variables:{ids:S},errorPolicy:"all",fetchPolicy:"no-cache"}),b=P.data.transactions;if(b.length!==y.length){const D=P.errors?.[0]?.message||"Unknown error";throw new gt(`Not all transactions were found: ${D}`)}return!this.activeIntegration&&b[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(b[0].integrationProduct.integration)),b.map((D,$)=>({transaction:D,workflowId:D.workflowId,readOnly:y.find(N=>N.option.transactionId===D.id)?.option.readOnly??!1,index:y[$].index}))},i=async y=>{if(y.length===0)return[];const S=await a.mutate({mutation:mo,variables:{inputs:y.map(b=>({integrationProductId:b.option.type==="integration"?b.option.integrationProductId:void 0,externalIntegrationId:b.option.type==="external"?b.option.externalIntegrationId:void 0,externalProductId:b.option.type==="external"?b.option.externalProductId:void 0,workflowId:b.option.workflowId,designName:b.option.designName,claim:!0,quantity:b.option.type==="integration"?b.option.quantity:void 0,recipient:b.option.type==="integration"?b.option.recipient:void 0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),P=S.data?.transactionCreateMany;if(!P||P.length===0){const b=S.errors?.[0]?.message||"Unknown error";throw new gt(`Failed to create transactions: ${b}`)}return P.map((b,D)=>({transaction:b,workflowId:b.workflowId,readOnly:!1,index:y[D].index}))},o=t.map((y,S)=>({option:y,index:S})),s=o.filter(y=>y.option.type==="transaction"),l=o.filter(y=>y.option.type==="integration"||y.option.type==="external"||y.option.type==="blank"),c=50,d=Xa(s,c),u=Xa(l,c),A=(await Promise.all([...d.map(r),...u.map(i)])).flat(),h=[...new Set(A.map(y=>y.workflowId))].filter(y=>y!==void 0),g=h.length>0?await Ja(h,e):[],p=new Map(g.map(y=>[y.id,y])),m=k.getMap("transactionOwnerIds")||new Map,f=A.map(async y=>{const{transaction:S,workflowId:P,readOnly:b,index:D}=y,$=P?p.get(P):void 0,N=t[D];!m.get(S.id)&&S.transactionOwnerId&&m.set(S.id,S.transactionOwnerId);const tt=m.get(S.id)||void 0,et=new Fc({onMutate:()=>({context:{transactionOwnerId:tt,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:tt,bundleOwnerId:e?.bundleOwnerId}})}),ot={workflow:$,transaction:S,singleVariantsRenderable:N?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:b?async()=>{throw new T("State mutation is forbidden in read only mode!")}:async K=>this.updateTransactionState({...K,context:{transactionOwnerId:tt,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>et,readOnly:b,isReloadedTransaction:N.type==="transaction"};if(N.type==="transaction"&&S.workflowState){const K=JSON.parse(S.workflowState);await fa(K),ot.reloadedState=K}else if(!b&&N.workflowState){const K=JSON.parse(N.workflowState);await fa(K),ot.reloadedState=K}return ot.delayWorkflowStateSync=!0,{experienceOptions:ot,index:D,options:N}}),w=await Promise.all(f);k.setMap("transactionOwnerIds",m);const I=w.sort((y,S)=>y.index-S.index);let x=[];for(const y of I){const{experienceOptions:S,options:P}=y,b=new Rr(this,S);await b.getWorkflowManager().getInitializationPromise(),P.type!=="transaction"&&this.customer&&await b.attachCustomerDetails({email:this.customer.emailAddress}),x=[...x,b],b.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return x}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await v.getShadowGraphqlClient().query({query:Eo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new va(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await v.getShadowGraphqlClient().query({query:bo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new va(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await v.getShadowGraphqlClient().query({query:vo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await v.getShadowGraphqlClient().mutate({mutation:$o,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 Kr=async(n,t)=>(await v.getShadowGraphqlClient().query({query:Qo,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,Qc=async n=>{const e=await v.getShadowGraphqlClient().query({query:So,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Rc=async(n,t)=>(await v.getShadowGraphqlClient().query({query:No,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,Oc=async n=>(await v.getShadowGraphqlClient().query({query:Oo,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,$c=async n=>(await v.getShadowGraphqlClient().query({query:Ro,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,Uc=async n=>{const t=await v.getShadowGraphqlClient().mutate({mutation:jl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n}});if(t.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${t.errors}`)};function _r(n,t,e,a){const r=e.width*n.zoom,i=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Ie(n.x,t.width-c,0),s.y=Ie(n.y,t.height-d,0),s}const o=n;return o.x=Ie(o.x,-r,t.width),o.y=Ie(o.y,-i,t.height),o}function Ie(n,t,e){return Math.min(Math.max(n,t),e)}class Xr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Pn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await ge(s),c=this.frameData?this.frameData[o]:void 0;Zt(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const r=Dt.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=ze(this.imageData.svg,this.imageData.colors||{},!1);return Le(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new T("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=_r(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,r,i){if(!a||a.length===0||a.some(s=>!s))throw new T("Frame data not set. This is a bug");if(!this.workflowManager)throw new T("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new R([new Es(s,e,t[l]),new bs(s,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,r)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Na(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Lc{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,g,p,m,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}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 Zr=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Zr||{});class ti extends _{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new Xr(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await ht.selectImage(this.step,t,this.manager,a),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Qe.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await O.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await it(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,r){return r&&r.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return O.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return O.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Vc=C.gql`
2643
+ `;class Fc{constructor(t,e=v.getShadowGraphqlClient.bind(v)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class kc{init(t,e,a){this.cognitoClient=new Ce.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new Ce.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new Ce.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new Ce.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Gt=new kc;class Hr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return mi(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Za.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Za.code(e)?.code==="CLP")return"USD0,0"}}const fn=new Hr;class Yr{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,fn.getPrecisionForCurrency(e))}}const Mc=async(n,t)=>{const e=await v.getShadowGraphqlClient().query({query:ko(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&O.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&O.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&O.cacheAsset(o.asset),o.thumbnail&&O.cacheAsset(o.thumbnail),o.material&&O.cacheMaterial(o.material)}),Ot.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},Tc=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},Ja=async(n,t)=>{const e=n.map(s=>Ot.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=Mc(a,t),i=a.map(s=>Ot.set({id:s,options:t},Tc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},Jr=async(n,t)=>(await Ja([n],t))[0];class Nc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return v.getShadowGraphqlClient().mutate({...e,mutation:fo})}catch(a){throw console.error(a),new gt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ti(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 33.2.1-beta.608a39d6-d415-5e24-9212-3d6b4823b699"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ut.setHubUrl(t.hubUrl),ut.setServerUrl(t.serverUrl),ut.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&&Vn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Gt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return O}getFlowService(){if(!Ni())throw new Error("Application key required to use Flow Service.");return new Gr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await v.getShadowGraphqlClient().query({query:Uo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new Yr(o,s,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Kr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}async authenticateBundleFromLocalStorage(t){if(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=v.getShadowGraphqlClient(),a=await e.query({query:Mo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const A=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(A)return Promise.resolve({success:!0,stakeholderType:A.type})}const c=(await e.query({query:To,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await v.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=v.getShadowGraphqlClient(),r=(await e.query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:Pc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await Gt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await v.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await v.getShadowGraphqlClient().mutate({mutation:xc,variables:{emailAddress:t}}),await Gt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await Gt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await v.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),r=new Date().getTime()/1e3,i=!a?.AccessToken||Kt(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await Gt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await v.getShadowGraphqlClient().query({query:Dc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await v.getShadowGraphqlClient().mutate({mutation:bl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!i?.id)throw new Error("Unable to create bundle");const o=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new ra(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const p=Object.entries(localStorage).find(([f,w])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",m=localStorage.getItem(p);m&&!Kt(m)&&(s.Authorization=`Bearer ${m}`)}const l={bundleOwnerId:o,...s,...r?.graphql?.additionalHeaders},c=await v.getShadowGraphqlClient().query({query:wl(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],u=k.getMap("bundlePartnerIds")||new Map;u.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",u);const A=new ra(this,d,e,a,o,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:r?.readonly});return await A.getInitializationPromise(),A}async duplicateBundle(t,e,a,r){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const A=await this.loggedInBearerToken();o.Authorization=`Bearer ${A}`}catch{const g=Object.entries(localStorage).find(([m,f])=>m.startsWith("CognitoIdentityServiceProvider")&&m.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(g);p&&!Kt(p)&&(o.Authorization=`Bearer ${p}`)}const s={bundleOwnerId:i,...o,...r?.graphql?.additionalHeaders},c=(await v.getShadowGraphqlClient().mutate({mutation:Il(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const u=k.getMap("bundleOwnerIds")||new Map;return u.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",u),async()=>{const A=new ra(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await A.getInitializationPromise(),A}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await v.getShadowGraphqlClient().query({query:Rl(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await v.getShadowGraphqlClient().query({query:yl,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],r=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",r),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),r=a[0],i=r.getWorkflow();return e&&!i&&console.error("No workflow instantiated when trying to create preview service."),e&&i&&await r.getWorkflowManager().injectIntoPreviewService(e(i)),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new gt("No options provided!");const a=v.getShadowGraphqlClient(),r=async y=>{if(y.length===0)return[];const S=y.map(D=>D.option.transactionId),P=await a.query({query:po,variables:{ids:S},errorPolicy:"all",fetchPolicy:"no-cache"}),b=P.data.transactions;if(b.length!==y.length){const D=P.errors?.[0]?.message||"Unknown error";throw new gt(`Not all transactions were found: ${D}`)}return!this.activeIntegration&&b[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(b[0].integrationProduct.integration)),b.map((D,$)=>({transaction:D,workflowId:D.workflowId,readOnly:y.find(N=>N.option.transactionId===D.id)?.option.readOnly??!1,index:y[$].index}))},i=async y=>{if(y.length===0)return[];const S=await a.mutate({mutation:mo,variables:{inputs:y.map(b=>({integrationProductId:b.option.type==="integration"?b.option.integrationProductId:void 0,externalIntegrationId:b.option.type==="external"?b.option.externalIntegrationId:void 0,externalProductId:b.option.type==="external"?b.option.externalProductId:void 0,workflowId:b.option.workflowId,designName:b.option.designName,claim:!0,quantity:b.option.type==="integration"||b.option.type==="blank"?b.option.quantity:void 0,recipient:b.option.type==="integration"||b.option.type==="blank"?b.option.recipient:void 0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),P=S.data?.transactionCreateMany;if(!P||P.length===0){const b=S.errors?.[0]?.message||"Unknown error";throw new gt(`Failed to create transactions: ${b}`)}return P.map((b,D)=>({transaction:b,workflowId:b.workflowId,readOnly:!1,index:y[D].index}))},o=t.map((y,S)=>({option:y,index:S})),s=o.filter(y=>y.option.type==="transaction"),l=o.filter(y=>y.option.type==="integration"||y.option.type==="external"||y.option.type==="blank"),c=50,d=Xa(s,c),u=Xa(l,c),A=(await Promise.all([...d.map(r),...u.map(i)])).flat(),h=[...new Set(A.map(y=>y.workflowId))].filter(y=>y!==void 0),g=h.length>0?await Ja(h,e):[],p=new Map(g.map(y=>[y.id,y])),m=k.getMap("transactionOwnerIds")||new Map,f=A.map(async y=>{const{transaction:S,workflowId:P,readOnly:b,index:D}=y,$=P?p.get(P):void 0,N=t[D];!m.get(S.id)&&S.transactionOwnerId&&m.set(S.id,S.transactionOwnerId);const tt=m.get(S.id)||void 0,et=new Fc({onMutate:()=>({context:{transactionOwnerId:tt,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:tt,bundleOwnerId:e?.bundleOwnerId}})}),ot={workflow:$,transaction:S,singleVariantsRenderable:N?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:b?async()=>{throw new T("State mutation is forbidden in read only mode!")}:async K=>this.updateTransactionState({...K,context:{transactionOwnerId:tt,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>et,readOnly:b,isReloadedTransaction:N.type==="transaction"};if(N.type==="transaction"&&S.workflowState){const K=JSON.parse(S.workflowState);await fa(K),ot.reloadedState=K}else if(!b&&N.workflowState){const K=JSON.parse(N.workflowState);await fa(K),ot.reloadedState=K}return ot.delayWorkflowStateSync=!0,{experienceOptions:ot,index:D,options:N}}),w=await Promise.all(f);k.setMap("transactionOwnerIds",m);const I=w.sort((y,S)=>y.index-S.index);let x=[];for(const y of I){const{experienceOptions:S,options:P}=y,b=new Rr(this,S);await b.getWorkflowManager().getInitializationPromise(),P.type!=="transaction"&&this.customer&&await b.attachCustomerDetails({email:this.customer.emailAddress}),x=[...x,b],b.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return x}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await v.getShadowGraphqlClient().query({query:Eo(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new va(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await v.getShadowGraphqlClient().query({query:bo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new va(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await v.getShadowGraphqlClient().query({query:vo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await v.getShadowGraphqlClient().mutate({mutation:$o,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 Kr=async(n,t)=>(await v.getShadowGraphqlClient().query({query:Qo,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,Qc=async n=>{const e=await v.getShadowGraphqlClient().query({query:So,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Rc=async(n,t)=>(await v.getShadowGraphqlClient().query({query:No,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,Oc=async n=>(await v.getShadowGraphqlClient().query({query:Oo,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,$c=async n=>(await v.getShadowGraphqlClient().query({query:Ro,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,Uc=async n=>{const t=await v.getShadowGraphqlClient().mutate({mutation:jl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n}});if(t.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${t.errors}`)};function _r(n,t,e,a){const r=e.width*n.zoom,i=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Ie(n.x,t.width-c,0),s.y=Ie(n.y,t.height-d,0),s}const o=n;return o.x=Ie(o.x,-r,t.width),o.y=Ie(o.y,-i,t.height),o}function Ie(n,t,e){return Math.min(Math.max(n,t),e)}class Xr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Pn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await ge(s),c=this.frameData?this.frameData[o]:void 0;Zt(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const r=Dt.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=ze(this.imageData.svg,this.imageData.colors||{},!1);return Le(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new T("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=_r(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,r,i){if(!a||a.length===0||a.some(s=>!s))throw new T("Frame data not set. This is a bug");if(!this.workflowManager)throw new T("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new R([new Es(s,e,t[l]),new bs(s,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,r)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Na(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Lc{renderLayouts(){throw new Error("Method not implemented.")}traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,g,p,m,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}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 Zr=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Zr||{});class ti extends _{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new Xr(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await ht.selectImage(this.step,t,this.manager,a),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Qe.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await O.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await it(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,r){return r&&r.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return O.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return O.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Vc=C.gql`
2644
2644
  query GetLoggedInCustomer($email: String!) {
2645
2645
  customer(emailAddress: $email) {
2646
2646
  id