@spiffcommerce/core 34.4.1-beta.ba0b3078-f186-5da9-9ea7-a1c70c98b862 → 34.4.1-beta.bf5c28f5-8552-52a0-841f-46d5240fb5bd
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +4 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -1446,7 +1446,7 @@
|
|
|
1446
1446
|
`,f={};f[this.shapeFillId]={browserValue:m};const S=M();return{id:S,region:A,command:new j({stepRegion:A,stepRegionIndex:h,stepName:t.stepName,colors:f,id:S,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},g)}},c=t.data.regions.map(l),d=c.filter(A=>!!A).map(A=>A?.command),u=c.filter(A=>!!A).map((A,h)=>({id:A.id,region:A.region,regionIndex:h}));return{command:new $(d),followup:async()=>{await r.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],u,async()=>{r.updateStorage(t.stepName,{colour:s()})})}}}}}const kt=new nl;class rl{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 xr=new rl,la=(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(`
|
|
1447
1447
|
`)).flat(),o=i.length,s=i.map(d=>pt(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((p,f,S,w)=>f>w[p]?S:p,0),h=i[A];let g=!1,m=h.length;for(;!g&&m>-1;){m=h.lastIndexOf(" ",m-1);const p=[h.slice(0,m),h.slice(m+1)],f=p.map(w=>pt(w,a,r));f[0]<=n.width&&(i=[...i.slice(0,A),...p,...i.slice(A+1)],s=[...s.slice(0,A),...f,...s.slice(A+1)],o+=1,g=!0)}g||(c=!1)}return[null,null]},Kt=(n,t,e,a,r)=>{let i,o;const s=yt(t.assetUrl),l=s.getFont();if(r.size){const A=n/l.unitsPerEm;return[i,o]=la(e,a,n,A,s),[r.size,i,o]}const c=6;let d=c-na;if(a.length>0){let A=a,h=0;for(;(!r.maxSize||d<=r.maxSize)&&A;)d+=na,h=d/l.unitsPerEm,[A,o]=la(e,a,d,h,s)}d>c&&(d-=na),r.minSize&&d<r.minSize&&(d=r.minSize);const u=d/l.unitsPerEm;return[i,o]=la(e,a,d,u,s),[d,i,o]},ca=30;class Te extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Te.name}}const il=["‘","’","“","”",`
|
|
1448
1448
|
`];class Ne extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ne.name}}class ol{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?yt(e.assetUrl):void 0;if(i){const o=a.split("").filter(l=>!il.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=ga.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(`
|
|
1449
|
-
`)||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 Ea(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=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 m=A.getGlobalPropertyConfiguration()?.aspects?.find(p=>p.type===q.Text&&t.globalPropertyAspectConfigurations?.map(f=>f.aspectName).includes(p.name));if(m){const f=A.getGlobalPropertyStateManager().getAspect(m.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=L.getDefaultVariant(r,t.overrideDefaultVariantId);if(h)return this.selectVariantCommand(t,h,{text:u},[],e,()=>{},()=>{},l,d)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map(i=>V(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 br(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 vr(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 Ea(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 oa(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 sa(s.id,o,t.data?.strokeThickness);i(l)}}getProcessedInput(t,e,a){const r=a?t:this.injectReplaceableText(t,e);return ke(r,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,a,r){const i=r.getStepStorage(a.stepName),o=Mt(t,r),s=this.getProcessedInput(o,a.data,i?.customiseAllText??!1),l={command:void 0,helperData:{},errorData:this.getErrorsForText(t,s,a,r)};if(l.errorData)return l;l.helperData.charactersRemaining=a.data.maxLength-s.length;const c=[],d=new Map,u=new Map;for(const A of e){if(!A.fontData)throw new Q("Failed to resolve font data for text.");const[h,g]=Kt(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 m=a.data.curved?s:(g||[]).join(`
|
|
1449
|
+
`)||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 Ea(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);console.log(`log: default ${JSON.stringify(c,null,2)}`);const d=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 m=A.getGlobalPropertyConfiguration()?.aspects?.find(p=>p.type===q.Text&&t.globalPropertyAspectConfigurations?.map(f=>f.aspectName).includes(p.name));if(m){const f=A.getGlobalPropertyStateManager().getAspect(m.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=L.getDefaultVariant(r,t.overrideDefaultVariantId);if(h)return this.selectVariantCommand(t,h,{text:u},[],e,()=>{},()=>{},l,d)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map(i=>V(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 br(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 vr(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 Ea(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 oa(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 sa(s.id,o,t.data?.strokeThickness);i(l)}}getProcessedInput(t,e,a){const r=a?t:this.injectReplaceableText(t,e);return ke(r,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,a,r){const i=r.getStepStorage(a.stepName),o=Mt(t,r),s=this.getProcessedInput(o,a.data,i?.customiseAllText??!1),l={command:void 0,helperData:{},errorData:this.getErrorsForText(t,s,a,r)};if(l.errorData)return l;l.helperData.charactersRemaining=a.data.maxLength-s.length;const c=[],d=new Map,u=new Map;for(const A of e){if(!A.fontData)throw new Q("Failed to resolve font data for text.");const[h,g]=Kt(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 m=a.data.curved?s:(g||[]).join(`
|
|
1450
1450
|
`);c.push(this.generateTextChangeCommandsForRegion(h,a.data,A.id,m))}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 $(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(p=>({id:p.id,region:p.stepRegion,regionIndex:p.stepRegionIndex})),h=r.storage?.color;let g=r.storage?.text;const m=e.getWorkflowExperience().getBundle();if(m&&t.globalPropertyAspectConfigurations){const f=m.getGlobalPropertyConfiguration()?.aspects?.find(S=>S.type===q.Text&&t.globalPropertyAspectConfigurations?.map(w=>w.aspectName).includes(S.name));if(f){const w=m.getGlobalPropertyStateManager().getAspect(f.name);w&&(g=w)}}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 p=s.map(S=>new Ia(S.id,u)),f=new $(p);e.getCommandDispatcher()(f)}),s.length===0&&l){const p=L.getDefaultVariant(l,t.overrideDefaultVariantId);if(p){const f=await this.selectVariantCommand(t,p,{text:g},[],e,()=>{},()=>{});e.getCommandDispatcher()(f.command)}}else{const{command:p}=W.updateInputText(g||"",s,t,e);p&&e.getCommandDispatcher()(p)}}}}else{const c=e.getWorkflowExperience().getBundle();if(c&&t.globalPropertyAspectConfigurations){const u=c.getGlobalPropertyConfiguration()?.aspects?.find(A=>A.type===q.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=L.getDefaultVariant(l,t.overrideDefaultVariantId);if(g){const m=await this.selectVariantCommand(t,g,{text:h},[],e,()=>{},()=>{});e.getCommandDispatcher()(m.command)}}else{const{command:g}=W.updateInputText(h,s,t,e);g&&e.getCommandDispatcher()(g)}}}}}getDefaultColorVariant(t){const e=t.colorOption;if(e)return L.getDefaultVariant(e)}getDefaultColor(t){const e=t.colorOption;return e?L.getDefaultVariant(e)?.color:void 0}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return L.getDefaultVariant(e)}getDefaultStrokeColorVariant(t){const e=t.strokeOption;if(console.log(`log: stroke option for step is ${JSON.stringify(e,null,2)}`),!!e)return L.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ft(t);const a=e.fileLink;if(!a)throw new Qt(e);const r=await Pt(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(m=>new Ia(m.id,u));if(l){const m=r.map(p=>new oa(p.id,l));A.push(...m)}if(c){const m=r.map(p=>new sa(p.id,c,t.data.strokeThickness));A.push(...m)}const h=await this.changeInputTextWithRegion(t,t.data.size||ca,u,a.text||"",a,i,a?.customiseAllText??!1,o,s);return h&&A.push(h),{command:new $(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||ca,u,A[0]?.newElement.input||a.text||t.data.defaultText||"",a,i,a?.customiseAllText??!1,o,s),g=A.flatMap(p=>p.commands);if(l){const p=A.map(f=>new oa(f.regionElement.id,l));g.push(...p)}if(c){const p=r.map(f=>new sa(f.id,c,t.data.strokeThickness));g.push(...p)}return h&&g.push(h),{command:new $(g),followup:async()=>{i.markUpdateCompleted(d)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,a,r,i,o){if(!a||!a.regions)throw new Error("Step data not supplied");const s=i.text||a.defaultText||"",l=Mt(s,o),c=this.getProcessedInput(l,a,!1),d=async(A,h)=>{const m=o.getLayouts().find(f=>f.panelId===A.panelId),p=M();try{if(!m)throw new Ne("Failed to find layout for region: "+A.panelId);const f=a.colorOption;let S;if(f&&f.variants){const k=f.variants.find(H=>H.id===f.defaultVariant?.id)||f.variants[0];S=this.createTextFillSpotColor(f,k),o.updateStorage(t,{colorProfileAssetKey:f.colorProfile?.key})}const w=await this.getDefaultColor(a),x=w||"#000000",v={stepRegion:A,stepRegionIndex:h,stepName:t,align:this.textAlign(a),fill:i.color?i.color:x,fontSize:a.size||ca,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:S},E=[],I=new Map,N=new Map;if(!v.fontData)throw new Q("Failed to resolve font data for text.");const[R,P]=Kt(v.fontSize,v.fontData,{left:v.x,top:v.y,width:v.width,height:v.height,rotation:v.rotation,panelId:""},[c],{size:a.size,minSize:a.minSize,maxSize:a.maxSize});I.set(v.id,R),N.set(v.id,P);const T=a.curved||a.vertical?c:(P||[]).join(`
|
|
1451
1451
|
`);E.push(this.generateTextChangeCommandsForRegion(R,a,v.id,T));const z=new j(v,m);return{regionElement:{id:p,region:A,regionIndex:h},commands:[z,...E],newElement:v,fontData:r}}catch(f){throw console.log(f),new Te("Error adding font to region")}},u=await Promise.all(a.regions.map(d)).catch(A=>{throw A instanceof Te?(xr.setLatestToast("Failed to load font.",me.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 Ir(a,r);if(i.push(o),!e.size){const l=new Er(a,t);i.push(l)}return new $(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=Mt(u,o),h=this.getProcessedInput(A,t.data,s),g=o.getRegionElements(t.stepName),m=new Map,p=new Map;for(const v of g)if(v.region){const[E,I]=Kt(e,a,v.region,[h],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});m.set(v.id,E),p.set(v.id,I)}const S=(()=>{if(t.data&&t.data.maxLength&&h.length>t.data.maxLength)return d&&d(!0),{info:"0"};const v=o.getWorkflowExperience().getProfanityList(),E=ga.split(h.toLowerCase());for(const I of E)for(const N in v){const R=v[N].toLowerCase().replace(/\s/g,"");if(I===R)return l(!0),{error:"Blocked profanity."}}return!t.data.vertical&&!t.data.allowNewlines&&(h.includes(`
|
|
1452
1452
|
`)||h.includes("\r"))?(l(!0),{error:"Cannot span multiple lines."}):!t.data.curved&&!Array.from(p.values()).every(N=>N)?(l(!0),{error:"Does not fit."}):(l(!1),{info:(t.data.maxLength-h.length).toString()})})();if(S.error){c(S.error);return}if(c(`${S.info} characters remaining`||""),d)return;o.updateStorage(t.stepName,{text:u}),o.updateMetadata(t.stepName,{text:this.injectReplaceableText(u,t.data)}),(i.defaultCleared||!t.data.deleteDefaultOnFocus)&&u.trim()!==""&&o.setMandatoryFulfilled(t.stepName,!0);const w=[];for(const v of g){const E=t.data.curved?h:(p.get(v.id)||[]).join(`
|
|
@@ -2529,7 +2529,7 @@
|
|
|
2529
2529
|
}
|
|
2530
2530
|
}
|
|
2531
2531
|
}
|
|
2532
|
-
`;class Yc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Jc{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 jt=new Jc;class ti{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=ln.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(ln.code(e)?.code==="CLP")return"USD0,0"}}const Bn=new ti;class ei{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,Bn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Bn.getPrecisionForCurrency(e))}}const Kc=async(n,t)=>{const e=await y.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&&U.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&U.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&U.cacheAsset(o.asset),o.thumbnail&&U.cacheAsset(o.thumbnail),o.material&&U.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},_c=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},nn=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=Kc(a,t),i=a.map(s=>$t.set({id:s,options:t},_c(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},ai=async(n,t)=>(await nn([n],t))[0],Xc=async n=>{const t=await y.getShadowGraphqlClient().query({query:To,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class Zc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:Qo})}catch(a){throw console.error(a),new mt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ki(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 34.4.1-beta.827901f8-3412-509a-84d5-bf0bf6d771b0"),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&&Kn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!_i())throw new Error("Application key required to use Flow Service.");return new _r}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new ei(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=ni(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(D.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ae.Owner});const a=D.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((D.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=y.getShadowGraphqlClient(),a=await e.query({query:_o,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(D.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ae.Owner});const s=D.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:Xo,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=D.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),D.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await y.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=y.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:jc,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 jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:Wc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await jt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query: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||Qe(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Hc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:ql(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=D.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),D.setMap("bundlePartnerIds",o);const s=D.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),D.setMap("bundleOwnerIds",s);const l=new In(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r,i){const s=D.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const p=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(p);f&&!Qe(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...r?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:$l(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=D.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),D.setMap("bundlePartnerIds",A);const h=new In(this,u,e,a,s,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:r?.readonly},i);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,r){const o={...await ii(t),...r?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Gl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=D.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),D.setMap("bundlePartnerIds",c);const d=D.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),D.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:ec(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:Ul,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=D.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),D.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,a,r){if(t.length===0)throw new mt("No options provided!");const i=t.map((P,T)=>({option:P,index:T})),o=i.filter(P=>P.option.type==="transaction"),s=i.filter(P=>P.option.type==="integration"||P.option.type==="external"||P.option.type==="blank"),l=50,c=ma(o,l),d=ma(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async P=>{if(P.length===0)return[];const T=P.map(H=>H.option.transactionId),z=await A.query({query:No,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=z.data.transactions;if(u=u+k.length,r&&r(u,o.length),k.length!==P.length){const H=z.errors?.[0]?.message||"Unknown error";throw new mt(`Not all transactions were found: ${H}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((H,_e)=>({transaction:H,workflowId:H.workflowId,readOnly:P.find(At=>At.option.transactionId===H.id)?.option.readOnly??!1,index:P[_e].index}))},g=async P=>{if(P.length===0)return[];const T=await A.mutate({mutation:Mo,variables:{inputs:P.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),z=T.data?.transactionCreateMany;if(!z||z.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new mt(`Failed to create transactions: ${k}`)}return u=u+z.length,r&&r(u,o.length),z.map((k,H)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:P[H].index}))},m=(await Promise.all([...c.map(h),...d.map(g)])).flat(),p=[...new Set(m.map(P=>P.transaction.integrationProductId))].filter(P=>P!==void 0),f=[...new Set(m.map(P=>P.workflowId))].filter(P=>P!==void 0),[S,w]=await Promise.all([(async()=>p.length>0?await Xc(p):[])(),(async()=>f.length>0?await nn(f,e):[])()]),x=new Map(S.map(P=>[P.id,P])),v=new Map(w.map(P=>[P.id,P])),E=m.map(async P=>{const{transaction:T,workflowId:z,readOnly:k,index:H}=P,_e=z?v.get(z):void 0,At=t[H];if(T.integrationProductId){const ot=x.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const pe=D.getMap("transactionOwnerIds")||new Map;!pe.get(T.id)&&T.transactionOwnerId&&(pe.set(T.id,T.transactionOwnerId),D.setMap("transactionOwnerIds",pe));const Xe=pe.get(T.id)||void 0,mi=new Yc({onMutate:()=>({context:{transactionOwnerId:Xe,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Xe,bundleOwnerId:e?.bundleOwnerId}})}),fe={workflow:_e,transaction:T,singleVariantsRenderable:At?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new Q("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:Xe,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>mi,readOnly:k,isReloadedTransaction:At.type==="transaction"};if(At.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await ba(ot),fe.reloadedState=ot}else if(!k&&At.workflowState){const ot=JSON.parse(At.workflowState);await ba(ot),fe.reloadedState=ot}return fe.delayWorkflowStateSync=!0,{experienceOptions:fe,index:H,options:At}}),N=(await Promise.all(E)).sort((P,T)=>P.index-T.index);let R=[];for(const P of N){const{experienceOptions:T,options:z}=P,k=new qr(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),z.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=D.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),D.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:zo(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 Da(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:qo(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 Da(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(D.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await y.getShadowGraphqlClient().query({query:Lo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ns,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 ni=async(n,t)=>(await y.getShadowGraphqlClient().query({query:ts,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,td=async n=>{const e=await y.getShadowGraphqlClient().query({query:Uo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},ed=async(n,t)=>(await y.getShadowGraphqlClient().query({query:Zo,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,ad=async n=>(await y.getShadowGraphqlClient().query({query:as,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,nd=async n=>(await y.getShadowGraphqlClient().query({query:es,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function ri(){const n={};try{const t=await this.loggedInBearerToken();n.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([i,o])=>i.startsWith("CognitoIdentityServiceProvider")&&i.endsWith("idToken"))?.[0]||"",r=localStorage.getItem(a);r&&!Qe(r)&&(n.Authorization=`Bearer ${r}`)}return n}async function ii(n){const e=D.getMap("bundleOwnerIds")?.get(n),a=await ri();return{bundleOwnerId:e,...a}}async function rd(n){const e=D.getMap("transactionOwnerIds")?.get(n),a=await ri();return{transactionOwnerId:e,...a}}const id=async n=>{const t=await ii(n),e=await y.getShadowGraphqlClient().mutate({mutation:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)},od=async n=>{const t=await rd(n),e=await y.getShadowGraphqlClient().mutate({mutation:uc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[n]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==n)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function oi(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 si{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Rn(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;te(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=Ge(this.imageData.svg,this.imageData.colors||{},!1);return ze(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 Q("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]=oi(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(l=>!l))throw new Q("Frame data not set. This is a bug");if(!this.workflowManager)throw new Q("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new $([new zs(l,e,t[d]),new qs(l,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]=za(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class sd{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,g,m,p,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}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 li=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(li||{});class ci extends Z{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new si(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return gt.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 gt.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(Oe.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 U.removeBackgroundFromAsset(e);t&&await gt.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){gt.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?gt.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 gt.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 U.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return U.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 ld=C.gql`
|
|
2532
|
+
`;class Yc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Jc{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 jt=new Jc;class ti{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=ln.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(ln.code(e)?.code==="CLP")return"USD0,0"}}const Bn=new ti;class ei{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,Bn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Bn.getPrecisionForCurrency(e))}}const Kc=async(n,t)=>{const e=await y.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&&U.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&U.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&U.cacheAsset(o.asset),o.thumbnail&&U.cacheAsset(o.thumbnail),o.material&&U.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},_c=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},nn=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=Kc(a,t),i=a.map(s=>$t.set({id:s,options:t},_c(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},ai=async(n,t)=>(await nn([n],t))[0],Xc=async n=>{const t=await y.getShadowGraphqlClient().query({query:To,variables:{ids:n},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class Zc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:Qo})}catch(a){throw console.error(a),new mt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ki(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 34.4.1-beta.ba0b3078-f186-5da9-9ea7-a1c70c98b862"),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&&Kn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!_i())throw new Error("Application key required to use Flow Service.");return new _r}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new ei(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=ni(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(D.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ae.Owner});const a=D.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((D.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=y.getShadowGraphqlClient(),a=await e.query({query:_o,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(D.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ae.Owner});const s=D.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:Xo,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=D.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),D.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await y.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=y.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:jc,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 jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:Wc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await jt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query: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||Qe(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Hc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:ql(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=D.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),D.setMap("bundlePartnerIds",o);const s=D.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),D.setMap("bundleOwnerIds",s);const l=new In(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r,i){const s=D.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const p=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(p);f&&!Qe(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...r?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:$l(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=D.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),D.setMap("bundlePartnerIds",A);const h=new In(this,u,e,a,s,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:r?.readonly},i);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,r){const o={...await ii(t),...r?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Gl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=D.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),D.setMap("bundlePartnerIds",c);const d=D.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),D.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:ec(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:Ul,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=D.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),D.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,a,r){if(t.length===0)throw new mt("No options provided!");const i=t.map((P,T)=>({option:P,index:T})),o=i.filter(P=>P.option.type==="transaction"),s=i.filter(P=>P.option.type==="integration"||P.option.type==="external"||P.option.type==="blank"),l=50,c=ma(o,l),d=ma(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async P=>{if(P.length===0)return[];const T=P.map(H=>H.option.transactionId),z=await A.query({query:No,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=z.data.transactions;if(u=u+k.length,r&&r(u,o.length),k.length!==P.length){const H=z.errors?.[0]?.message||"Unknown error";throw new mt(`Not all transactions were found: ${H}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((H,_e)=>({transaction:H,workflowId:H.workflowId,readOnly:P.find(At=>At.option.transactionId===H.id)?.option.readOnly??!1,index:P[_e].index}))},g=async P=>{if(P.length===0)return[];const T=await A.mutate({mutation:Mo,variables:{inputs:P.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),z=T.data?.transactionCreateMany;if(!z||z.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new mt(`Failed to create transactions: ${k}`)}return u=u+z.length,r&&r(u,o.length),z.map((k,H)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:P[H].index}))},m=(await Promise.all([...c.map(h),...d.map(g)])).flat(),p=[...new Set(m.map(P=>P.transaction.integrationProductId))].filter(P=>P!==void 0),f=[...new Set(m.map(P=>P.workflowId))].filter(P=>P!==void 0),[S,w]=await Promise.all([(async()=>p.length>0?await Xc(p):[])(),(async()=>f.length>0?await nn(f,e):[])()]),x=new Map(S.map(P=>[P.id,P])),v=new Map(w.map(P=>[P.id,P])),E=m.map(async P=>{const{transaction:T,workflowId:z,readOnly:k,index:H}=P,_e=z?v.get(z):void 0,At=t[H];if(T.integrationProductId){const ot=x.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const pe=D.getMap("transactionOwnerIds")||new Map;!pe.get(T.id)&&T.transactionOwnerId&&(pe.set(T.id,T.transactionOwnerId),D.setMap("transactionOwnerIds",pe));const Xe=pe.get(T.id)||void 0,mi=new Yc({onMutate:()=>({context:{transactionOwnerId:Xe,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Xe,bundleOwnerId:e?.bundleOwnerId}})}),fe={workflow:_e,transaction:T,singleVariantsRenderable:At?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new Q("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:Xe,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>mi,readOnly:k,isReloadedTransaction:At.type==="transaction"};if(At.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await ba(ot),fe.reloadedState=ot}else if(!k&&At.workflowState){const ot=JSON.parse(At.workflowState);await ba(ot),fe.reloadedState=ot}return fe.delayWorkflowStateSync=!0,{experienceOptions:fe,index:H,options:At}}),N=(await Promise.all(E)).sort((P,T)=>P.index-T.index);let R=[];for(const P of N){const{experienceOptions:T,options:z}=P,k=new qr(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),z.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=D.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),D.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:zo(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 Da(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:qo(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 Da(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(D.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await y.getShadowGraphqlClient().query({query:Lo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ns,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 ni=async(n,t)=>(await y.getShadowGraphqlClient().query({query:ts,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,td=async n=>{const e=await y.getShadowGraphqlClient().query({query:Uo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},ed=async(n,t)=>(await y.getShadowGraphqlClient().query({query:Zo,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,ad=async n=>(await y.getShadowGraphqlClient().query({query:as,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,nd=async n=>(await y.getShadowGraphqlClient().query({query:es,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function ri(){const n={};try{const t=await this.loggedInBearerToken();n.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([i,o])=>i.startsWith("CognitoIdentityServiceProvider")&&i.endsWith("idToken"))?.[0]||"",r=localStorage.getItem(a);r&&!Qe(r)&&(n.Authorization=`Bearer ${r}`)}return n}async function ii(n){const e=D.getMap("bundleOwnerIds")?.get(n),a=await ri();return{bundleOwnerId:e,...a}}async function rd(n){const e=D.getMap("transactionOwnerIds")?.get(n),a=await ri();return{transactionOwnerId:e,...a}}const id=async n=>{const t=await ii(n),e=await y.getShadowGraphqlClient().mutate({mutation:dc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)},od=async n=>{const t=await rd(n),e=await y.getShadowGraphqlClient().mutate({mutation:uc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[n]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==n)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function oi(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 si{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Rn(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;te(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=Ge(this.imageData.svg,this.imageData.colors||{},!1);return ze(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 Q("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]=oi(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(l=>!l))throw new Q("Frame data not set. This is a bug");if(!this.workflowManager)throw new Q("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new $([new zs(l,e,t[d]),new qs(l,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]=za(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class sd{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,g,m,p,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}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 li=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(li||{});class ci extends Z{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new si(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return gt.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 gt.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(Oe.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 U.removeBackgroundFromAsset(e);t&&await gt.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){gt.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?gt.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 gt.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 U.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return U.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 ld=C.gql`
|
|
2533
2533
|
query GetLoggedInCustomer($email: String!) {
|
|
2534
2534
|
customer(emailAddress: $email) {
|
|
2535
2535
|
id
|