@spiffcommerce/core 32.2.4-beta.2a1f0ff0-c7c4-56e0-afbf-fd744926c42c → 32.2.4-beta.37bc688d-3d85-536a-ba61-02a441df130e

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -2348,7 +2348,7 @@
2348
2348
  />
2349
2349
  </svg>
2350
2350
  `,h={"spiff-fill-shape":{browserValue:o.color||"#000000"}},g=M();return new z({colors:h,id:g,svg:A,type:F.Illustration,y:c.top,x:c.left,rotation:c.rotation,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,immutable:c.immutable},d)},l=a.data.regions;try{return l.map(s)}catch(c){return console.error(c),[]}},ql=async(r,t,e)=>{const a=[],i=t.type===v.ProductOverlay?e||t.data.asset?.fileLink||"":t.data.asset?.fileLink||"",s=i.endsWith(".jpeg")||i.endsWith(".jpg")||i.endsWith(".png")?F.Image:(i.endsWith(".svg"),F.Illustration),l=t.data.regions;if(s==="image")try{l.forEach(c=>{const d=r.find(u=>u.panelId===c.panelId);if(!d)throw new j(c);const A={id:M(),src:i,type:s,y:c.top,x:c.left,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,productOverlay:t.type===v.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:c.rotation,excludeFromExport:t.data.excludeFromPrint,preserveAspectRatio:"none"};a.push(new z(A,d))})}catch(c){console.error(c)}else{const c=await tt(i,!0),d=A=>{const u=/<svg.*?<\/svg>/s,h=A.match(u)||[],g=h?.length>0?h[0]:"",f=lt().parseFromString(g,"image/svg+xml").firstElementChild;if(!f)throw new bt("Failed to read SVG.");return Ue(f),St().serializeToString(f)};l.forEach(A=>{const u=r.find(g=>g.panelId===A.panelId);if(!u)throw new j(A);const h={id:M(),src:i,asset_key:i,svg:d(c),colors:{},type:s,y:A.top,x:A.left,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,scaleX:1,scaleY:1,rotation:A.rotation,productOverlay:t.type===v.ProductOverlay?!0:void 0,excludeFromExport:t.data.excludeFromPrint};a.push(new z(h,u))})}return a},Gl=async(r,t,e,a)=>{const n=[],i=e.data,o=30,s=p=>p.vertical?"center":p.textAlign||"center",l=()=>{const p=a.option;if(!p)return;const f=p.variants?.find(b=>b.id===i.fontVariantId)||ue(p);if(!f||!f.asset)return;t[a.stepName]={selectedVariants:[f]};const S=f.asset.fileLink;if(S)return S},d=await(async()=>{const p=l();if(!p)return;const f=await xt(p);return{assetUrl:p,name:f.names.fullName.en}})(),A=(a.data.replaceableText?a.data.replaceableText.replace("{{}}",i.text):i.text)||"",u=De(A,{vertical:a.data.vertical,uppercase:a.data.uppercase}),h=async p=>{const f=p.colorOption;return f?W.getDefaultVariant(f)?.color:void 0},g=i.color||await h(a.data),m=a.data.regions;for(const p of m){const f=r.find(b=>b.panelId===p.panelId);if(!f)continue;const S={stepName:e.name,id:M(),align:s(a.data),curved:a.data.curved,fill:i.color||g||"#000000",fontData:d,fontSize:a.data.size||o,height:p.height,layer:p.layer,layerIndex:p.layerIndex,paths:a.data.paths,rotation:p.rotation,text:u,type:F.Textbox,vertical:a.data.vertical,verticalAlign:a.data.verticalAlign||"middle",width:p.width,x:p.left,y:p.top};if(d){const[b,P]=Kt(a.data.size||o,d,p,[De(u,{vertical:a.data.vertical,uppercase:a.data.uppercase})],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});n.push(new z({...S,fontSize:b,text:S.curved?S.text:(P||[]).join(`
2351
- `)},f))}else n.push(new z(S,f))}return n},Wl=(r,t)=>r.conditions?r.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const n=a.selectedVariants;return e.requiredVariantSelections.some(i=>n.find(o=>o.id===i)!==void 0)}return!1}):!0,Mr=async(r,t,e,a)=>{const n=[],i={};for(const o of r){const s=t.steps.find(l=>l.stepName===o.name);if(s)switch(s.type){case v.DigitalContent:n.push(...await Ol(e,o,s));break;case v.Frame:case v.Photo:n.push(...await $l(e,i,o,s));break;case v.Illustration:n.push(...await Ul(e,i,o,s));break;case v.Module:n.push(...await Ll(e,o,s));break;case v.Picture:n.push(...await Vl(e,i,o,s));break;case v.Shape:n.push(...await zl(e,i,o,s));break;case v.Text:n.push(...await Gl(e,i,o,s));break}}for(const o of t.steps)o.type!==v.SilentIllustration&&o.type!==v.ProductOverlay||Wl(o,i)&&n.push(...await ql(e,o,a));return n};class jl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Jl(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Hl=()=>new Promise((r,t)=>{try{const a=ft().getContext("webgl2");r(!!a)}catch{r(!1)}}),Yl=Hl();class Jl{constructor(t,e,a,n,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Da(2),this.id=t,this.name=e,this.service=a,this.panelSize=n,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=It(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new Kl(this.getID(),a,await Yl,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class Kl extends xa{constructor(t,e,a,n,i,o){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=n,this.layouts=i,this.getWorkflowManager=o}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,n=e/t.height,i=Math.min(a,n);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){const t=this.layouts.find(g=>g.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,n=t.layoutState.layout.height,i=a===1||n===1?{width:1,height:1}:this.getDynamicTextureResolution(),o=i.width,s=i.height;let l,c;if(this.nonPOTSupport){const g=o/s;a/n<g?(l=o,c=n*(o/a)):(l=a*(s/n),c=s);const p=this.resizeFit({width:l,height:c});l=p.width,c=p.height}else l=i.width,c=i.height;const d=this.getWorkflowManager?.()?.getTemplatingContext(),A=qe(t.layoutState.layout,e,{renderingConfiguration:{purpose:Nt.ThreeD,templatingContext:d}}),u=Nn(A),h=await Sa.Pith.from(this.ctx,u,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:ft,createImage:le,DOMParser:Ba(),fetch});h.resize(l,c),await h.render(),this.onRender()}}const _l=(r,t)=>{const e=[];return r.forEach(a=>{const n=t.steps.find(i=>i.stepName===a.stepName);n?.type===v.Text&&a.stepAspectType==="Text"&&e.push({name:n.stepName,data:{text:a.value}})}),e},Xl=async(r,t,e,a)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};n=new Q(e.map(l=>new Na(l))).apply(n);const o=await Mr(r,t,e,a);return new Q(o).apply(n)};class Zl{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(e=>this.getHandle(e)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const n=e.aspects.find(i=>i.name===a.targetAspectName);return n?a.requiredVariantSelections.some(i=>i===n.value):!1})}async createHandle(t){switch(t.type){case U.FileUpload:return new Tr(this.bundle,t).initialize();case U.ColorOption:return new Ca(this.bundle,t,t.entityId?await W.getOption(t.entityId):void 0);case U.Option:{const e=t.entityId?await W.getOption(t.entityId):void 0;return e?.type==="Color"?new Ca(this.bundle,t,e):new za(this.bundle,t,e)}case U.Text:return new Nr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Ge{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(n=>n.getStepsConditionallyActive().filter(i=>i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:i.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Tr extends Ge{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await W.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await tt(t?.fileLink),a=await Ma(t?.fileLink),n=a.width,i=a.height,o=await ot(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{o.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:n,height:i,aspect:n/i,svg:o.svg,colors:o.colors};dt.set(t?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Te.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await R.removeBackgroundFromAsset(e),o={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return R.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?$e(Le(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return R.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return R.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if(n?.useOriginalAsset===t)return;const i={...n,useOriginalAsset:t},o=t?n?.originalAssetKey:n?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",i)];if(t)s.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};s.push(l())}s.push(this.loadImageData()),await Promise.all(s),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await R.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const i=new Map(n.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);this.getSharedSteps(t).forEach(o=>{o.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await ot(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(i=>{i.changeColors(a)});const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([i,o])=>({key:i,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const o=this.getSharedSteps(e).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;n.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Nr extends Ge{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(n)}}class za extends Ge{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new rt(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(a=>a.id===t);return e?new rt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new rt(e):void 0}}getAvailableVariants(){return(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.optionResource?.variants||[]).map(e=>new rt(e))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(n=>n.id===e);return a?this.applyVariantSelection(new rt(a),t):Promise.resolve()}async applyVariantSelection(t,e){const n=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(n)}}class Ca extends za{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),{},e),this.applyColorVariant(t,void 0,e)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(i=>i.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new rt(a),t);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;n&&this.setCustomColor(n)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(o=>{switch(o.getType()){case v.Shape:return o.selectVariant(t);case v.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case v.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const tc=(r,t,e,a)=>r.flatMap(n=>n.getSteps()).filter(n=>n.getGlobalPropertyAspects(t).includes(e)&&n.getType()===a),ec=(r,t,e)=>{const n=tc(r,t,e,v.Illustration).map(i=>{const o=i.getCurrentVariant()?.getAssetResource(),s=i.getColors();return!o?.assetConfiguration||!s?0:Object.getOwnPropertyNames(s).length});return Math.max(...n)};function Qr(r){const t=new Map;return r?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}class ac{constructor(t,e,a,n,i){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const o=i?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=o,this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=s,this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=n}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=Qr(this.globalPropertyState)}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=It(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},this.recalculateMandatoryStates(),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(a=>a.name===t&&a.channel===e)?.storage}async setAspect(t,e,a,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=It(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(n){const l=s.find(c=>c.channel===n);if(l)l.value=e,l.type=i.type,l.channel=n,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(n===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n})}}else{const l=s[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(o,this.globalPropertyState)}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(s=>s.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=It(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(s=>s.name===t);if(o.length>0)if(a){const s=o.find(l=>l.channel===a);s&&(s.storage=e!==null?e:void 0,s.type=n.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await y.getShadowGraphqlClient().mutate({mutation:Ws,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let a=e.type&&e.storage?{}:void 0;if(a)switch(e.type){case U.FileUpload:{a.fileUpload=e.storage;break}case U.Option:{a.option=e.storage;break}case U.ColorOption:{a=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:a,channel:e.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateUpdate)this.globalPropertyState=t.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:Gs,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class nc{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find(o=>o.transactionId===t.getWorkflowManager().getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const n=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=n.position,i.rotation=n.rotation,i.scale=n.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(o=>o.transactionId===n);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:n,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer()||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,n=this.state.transactions.find(l=>l.transactionId===a),i=n?.transforms?.[e];if(!i)return;const o=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),s=t.getWorkflowManager().getModelContainer();s.position=o.position,s.rotation=o.rotation,s.scale=o.scale,n.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const rc=w.gql`
2351
+ `)},f))}else n.push(new z(S,f))}return n},Wl=(r,t)=>r.conditions?r.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const n=a.selectedVariants;return e.requiredVariantSelections.some(i=>n.find(o=>o.id===i)!==void 0)}return!1}):!0,Mr=async(r,t,e,a)=>{const n=[],i={};for(const o of r){const s=t.steps.find(l=>l.stepName===o.name);if(s)switch(s.type){case v.DigitalContent:n.push(...await Ol(e,o,s));break;case v.Frame:case v.Photo:n.push(...await $l(e,i,o,s));break;case v.Illustration:n.push(...await Ul(e,i,o,s));break;case v.Module:n.push(...await Ll(e,o,s));break;case v.Picture:n.push(...await Vl(e,i,o,s));break;case v.Shape:n.push(...await zl(e,i,o,s));break;case v.Text:n.push(...await Gl(e,i,o,s));break}}for(const o of t.steps)o.type!==v.SilentIllustration&&o.type!==v.ProductOverlay||Wl(o,i)&&n.push(...await ql(e,o,a));return n};class jl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Jl(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Hl=()=>new Promise((r,t)=>{try{const a=ft().getContext("webgl2");r(!!a)}catch{r(!1)}}),Yl=Hl();class Jl{constructor(t,e,a,n,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Da(2),this.id=t,this.name=e,this.service=a,this.panelSize=n,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=It(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new Kl(this.getID(),a,await Yl,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class Kl extends xa{constructor(t,e,a,n,i,o){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=n,this.layouts=i,this.getWorkflowManager=o}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,n=e/t.height,i=Math.min(a,n);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){const t=this.layouts.find(g=>g.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,n=t.layoutState.layout.height,i=a===1||n===1?{width:1,height:1}:this.getDynamicTextureResolution(),o=i.width,s=i.height;let l,c;if(this.nonPOTSupport){const g=o/s;a/n<g?(l=o,c=n*(o/a)):(l=a*(s/n),c=s);const p=this.resizeFit({width:l,height:c});l=p.width,c=p.height}else l=i.width,c=i.height;const d=this.getWorkflowManager?.()?.getTemplatingContext(),A=qe(t.layoutState.layout,e,{renderingConfiguration:{purpose:Nt.ThreeD,templatingContext:d}}),u=Nn(A),h=await Sa.Pith.from(this.ctx,u,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:ft,createImage:le,DOMParser:Ba(),fetch});h.resize(l,c),await h.render(),this.onRender()}}const _l=(r,t)=>{const e=[];return r.forEach(a=>{const n=t.steps.find(i=>i.stepName===a.stepName);n?.type===v.Text&&a.stepAspectType==="Text"&&e.push({name:n.stepName,data:{text:a.value}})}),e},Xl=async(r,t,e,a)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};n=new Q(e.map(l=>new Na(l))).apply(n);const o=await Mr(r,t,e,a);return new Q(o).apply(n)};class Zl{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){if(!this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration)return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(e=>this.getHandle(e)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const n=e.aspects.find(i=>i.name===a.targetAspectName);return n?a.requiredVariantSelections.some(i=>i===n.value):!1})}async createHandle(t){switch(t.type){case U.FileUpload:return new Tr(this.bundle,t).initialize();case U.ColorOption:return new Ca(this.bundle,t,t.entityId?await W.getOption(t.entityId):void 0);case U.Option:{const e=t.entityId?await W.getOption(t.entityId):void 0;return e?.type==="Color"?new Ca(this.bundle,t,e):new za(this.bundle,t,e)}case U.Text:return new Nr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Ge{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(n=>n.getStepsConditionallyActive().filter(i=>i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:i.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Tr extends Ge{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await W.getOption(this.property.data?.fileUpload?.colorOptionId)),await this.loadImageData(),this}async loadImageData(){const t=await this.getImage();if(t?.fileLink)if(t?.fileLink.endsWith(".svg")){const e=await tt(t?.fileLink),a=await Ma(t?.fileLink),n=a.width,i=a.height,o=await ot(e);this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.colors?.forEach(c=>{o.colors[c.key]={browserValue:c.browserValue,pmsValue:c.pmsValue}});const l={src:t?.fileLink,width:n,height:i,aspect:n/i,svg:o.svg,colors:o.colors};dt.set(t?.fileLink,l),this.imageData=l}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Te.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await R.removeBackgroundFromAsset(e),o={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,o):a.setAspectStorage(this.property.name,o)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(o),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return R.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?$e(Le(this.imageData.svg,this.imageData.colors??{},!1)):this.imageData?.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.originalAssetKey)return R.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return R.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.useOriginalAsset??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if(n?.useOriginalAsset===t)return;const i={...n,useOriginalAsset:t},o=t?n?.originalAssetKey:n?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",i)];if(t)s.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};s.push(l())}s.push(this.loadImageData()),await Promise.all(s),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await R.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const i=new Map(n.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);this.getSharedSteps(t).forEach(o=>{o.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){return this.property.data?.fileUpload?.colorPickerEnabled?this.colorOption?.variants?.map(t=>({fill:t.color,stroke:t.color,variant:t,pmsValue:t.name}))??[]:[]}getCurrentColors(){return this.imageData?.colors}isColorPickerEnabled(){return this.property.data?.fileUpload?.colorPickerEnabled??!1}isPmsPickerEnabled(){return this.property.data?.fileUpload?.pmsPickerEnabled??!1}async getOriginalColors(){return this.imageData?.svg?(await ot(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(i=>{i.changeColors(a)});const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([i,o])=>({key:i,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const o=this.getSharedSteps(e).map(s=>{const l=s;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(o)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;n.getRaw().globalPropertyAspectConfigurations?.some(o=>o.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&o.aspectName===this.property.name)&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Nr extends Ge{constructor(t,e){super(t,e)}isTemplatingEnabled(){return this.property.data?.text?.templatingEnabled||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(n)}}class za extends Ge{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new rt(t))}getCurrentVariant(){if(!this.optionResource)return;const t=this.getStateValue();if(t){const e=this.optionResource.variants?.find(a=>a.id===t);return e?new rt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new rt(e):void 0}}getAvailableVariants(){return(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.optionResource?.variants||[]).map(e=>new rt(e))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(n=>n.id===e);return a?this.applyVariantSelection(new rt(a),t):Promise.resolve()}async applyVariantSelection(t,e){const n=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(n)}}class Ca extends za{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();const a=this.optionResource?.variants?.find(i=>i.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new rt(a),t);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;n&&this.setCustomColor(n)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(o=>{switch(o.getType()){case v.Shape:return o.selectVariant(t);case v.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case v.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){return this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor||this.getCurrentVariant()?.getColor()||"#ffffff"}}const tc=(r,t,e,a)=>r.flatMap(n=>n.getSteps()).filter(n=>n.getGlobalPropertyAspects(t).includes(e)&&n.getType()===a),ec=(r,t,e)=>{const n=tc(r,t,e,v.Illustration).map(i=>{const o=i.getCurrentVariant()?.getAssetResource(),s=i.getColors();return!o?.assetConfiguration||!s?0:Object.getOwnPropertyNames(s).length});return Math.max(...n)};function Qr(r){const t=new Map;return r?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}class ac{constructor(t,e,a,n,i){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const o=i?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=o,this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=s,this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=n}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=Qr(this.globalPropertyState)}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=It(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},this.recalculateMandatoryStates(),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return this.globalPropertyState.aspects.find(a=>a.name===t&&a.channel===e)?.storage}async setAspect(t,e,a,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=It(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(l=>l.name===t);if(s.length>0)if(n){const l=s.find(c=>c.channel===n);if(l)l.value=e,l.type=i.type,l.channel=n,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(n===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n})}}else{const l=s[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(o,this.globalPropertyState)}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(s=>s.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=It(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(s=>s.name===t);if(o.length>0)if(a){const s=o.find(l=>l.channel===a);s&&(s.storage=e!==null?e:void 0,s.type=n.type)}else{const s=o[0];s.storage=e!==null?e:void 0,s.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await y.getShadowGraphqlClient().mutate({mutation:Ws,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(e=>{let a=e.type&&e.storage?{}:void 0;if(a)switch(e.type){case U.FileUpload:{a.fileUpload=e.storage;break}case U.Option:{a.option=e.storage;break}case U.ColorOption:{a=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:a,channel:e.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateUpdate)this.globalPropertyState=t.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:Gs,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}});if(t.data?.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class nc{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){if(!this.state||!t?.getWorkflowManager()?.getModelContainer())return;const e=this.state.transactions.find(o=>o.transactionId===t.getWorkflowManager().getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const n=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=n.position,i.rotation=n.rotation,i.scale=n.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(o=>o.transactionId===n);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:n,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){if(!t?.getWorkflowManager()?.getModelContainer()||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,n=this.state.transactions.find(l=>l.transactionId===a),i=n?.transforms?.[e];if(!i)return;const o=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),s=t.getWorkflowManager().getModelContainer();s.position=o.position,s.rotation=o.rotation,s.scale=o.scale,n.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const rc=w.gql`
2352
2352
  query GetManyMetafields($entityIds: [String!]!) {
2353
2353
  metafieldsMany(entityIds: $entityIds) {
2354
2354
  id
@@ -2530,7 +2530,7 @@
2530
2530
  }
2531
2531
  }
2532
2532
  }
2533
- `;class Cc{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 wc{init(t,e,a){this.cognitoClient=new fe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const n=await this.cognitoClient?.send(new fe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return n?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new wc;class qr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return di(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ka.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Ka.code(e)?.code==="CLP")return"USD0,0"}}const hn=new qr;class Gr{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,hn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,hn.getPrecisionForCurrency(e))}}const yc=async(r,t)=>{const e=await y.getShadowGraphqlClient().query({query:bo(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:r}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(n=>console.error(n)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(n=>{n.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&R.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&R.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&R.cacheAsset(o.asset),o.thumbnail&&R.cacheAsset(o.thumbnail),o.material&&R.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),n.finalizeStepConfig||(n.finalizeStepConfig={}),n.finalizeStepConfig.termsMarkdown=n.finalizeStepConfig.termsMarkdown||n.partner.termsMarkdown}),a},Sc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},ja=async(r,t)=>{const e=r.map(s=>$t.get({id:s,options:t})),a=r.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=yc(a,t),i=a.map(s=>$t.set({id:s,options:t},Sc(s,n))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},vc=async(r,t)=>(await ja([r],t))[0],Ec=r=>r.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})),bc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):Ec(t.panels)};class Bc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:Ao})}catch(a){throw console.error(a),new gt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Pi(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 32.2.4"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&On(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return R}getFlowService(){if(!xi())throw new Error("Application key required to use Flow Service.");return new Lr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:Mo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new Gr(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=Wr(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 n=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(n)&&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:Bo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const n=a.data.transactions[0];if(!n.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const u=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(u)return Promise.resolve({success:!0,stakeholderType:u.type})}const c=(await e.query({query:Io,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await y.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.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(),n=(await e.query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const s=(await e.mutate({mutation:mc,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(n);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),i=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:ve,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:pc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:ve,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),n=new Date().getTime()/1e3,i=!a?.AccessToken||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||i){const o=await Wt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:fc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:tl(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 aa(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const m=Object.entries(localStorage).find(([f,S])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(m);p&&!_t(p)&&(s.Authorization=`Bearer ${p}`)}const l={bundleOwnerId:o,...s,...n?.graphql?.additionalHeaders},c=await y.getShadowGraphqlClient().query({query:Js(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],A=k.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",A);const u=new aa(this,d,e,a,o,{additionalHeaders:n?.graphql?.additionalHeaders,eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:n?.readonly});return await u.getInitializationPromise(),u}async duplicateBundle(t,e,a,n){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const u=await this.loggedInBearerToken();o.Authorization=`Bearer ${u}`}catch{const g=Object.entries(localStorage).find(([p,f])=>p.startsWith("CognitoIdentityServiceProvider")&&p.endsWith("idToken"))?.[0]||"",m=localStorage.getItem(g);m&&!_t(m)&&(o.Authorization=`Bearer ${m}`)}const s={bundleOwnerId:i,...o,...n?.graphql?.additionalHeaders},c=(await y.getShadowGraphqlClient().mutate({mutation:el(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const A=k.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",A),async()=>{const u=new aa(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await u.getInitializationPromise(),u}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:hl(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:Ks,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||[],n=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&n.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new gt("No options provided!");const a=y.getShadowGraphqlClient(),n=async C=>{if(C.length===0)return[];const E=C.map(D=>D.option.transactionId),x=await a.query({query:co,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),B=x.data.transactions;if(B.length!==C.length){const D=x.errors?.[0]?.message||"Unknown error";throw new gt(`Not all transactions were found: ${D}`)}return!this.activeIntegration&&B[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(B[0].integrationProduct.integration)),B.map((D,O)=>({transaction:D,workflowId:D.workflowId,readOnly:C.find(T=>T.option.transactionId===D.id)?.option.readOnly??!1,index:C[O].index}))},i=async C=>{if(C.length===0)return[];const E=await a.mutate({mutation:lo,variables:{inputs:C.map(B=>({integrationProductId:B.option.type==="integration"?B.option.integrationProductId:void 0,externalIntegrationId:B.option.type==="external"?B.option.externalIntegrationId:void 0,externalProductId:B.option.type==="external"?B.option.externalProductId:void 0,workflowId:B.option.workflowId,designName:B.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),x=E.data?.transactionCreateMany;if(!x||x.length===0){const B=E.errors?.[0]?.message||"Unknown error";throw new gt(`Failed to create transactions: ${B}`)}return x.map((B,D)=>({transaction:B,workflowId:B.workflowId,readOnly:!1,index:C[D].index}))},o=t.map((C,E)=>({option:C,index:E})),s=o.filter(C=>C.option.type==="transaction"),l=o.filter(C=>C.option.type==="integration"||C.option.type==="external"),c=Ja(s,10),d=Ja(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(C=>C.workflowId))],h=await ja(u,e),g=new Map(h.map(C=>[C.id,C])),m=k.getMap("transactionOwnerIds")||new Map,p=A.map(async C=>{const{transaction:E,workflowId:x,readOnly:B,index:D}=C,O=g.get(x),T=t[D];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const et=m.get(E.id)||void 0,at=new Cc({onMutate:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}})}),H={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:T?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:B?async()=>{throw new L("State mutation is forbidden in read only mode!")}:async Y=>this.updateTransactionState({...Y,context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>at,readOnly:B,workflow:O,isReloadedTransaction:T.type==="transaction"};if(T.type==="transaction"&&E.workflowState){const Y=JSON.parse(E.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await ma(Y),H.reloadedState=Y}else if(!B&&T.workflowState){const Y=JSON.parse(T.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await ma(Y),H.reloadedState=Y}else H.layouts=bc(H.transaction,H.workflow);return H.renderableContextService=new jl(H.layouts),H.delayWorkflowStateSync=!0,{experienceOptions:H,index:D,options:T}}),f=await Promise.all(p);k.setMap("transactionOwnerIds",m);const b=f.sort((C,E)=>C.index-E.index).map(async C=>{const{experienceOptions:E,options:x}=C,B=new kr(this,E);return await B.getWorkflowManager().getInitializationPromise(),x.type!=="transaction"&&this.customer&&await B.attachCustomerDetails({email:this.customer.emailAddress}),B}),P=await Promise.all(b);return P.forEach(C=>C.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),P}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:po(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 wa(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:fo(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 wa(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,n=await y.getShadowGraphqlClient().query({query:mo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ko,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 Wr=async(r,t)=>(await y.getShadowGraphqlClient().query({query:xo,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,Ic=async r=>{const e=await y.getShadowGraphqlClient().query({query:go,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Pc=async(r,t)=>(await y.getShadowGraphqlClient().query({query:Po,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,xc=async r=>(await y.getShadowGraphqlClient().query({query:Fo,errorPolicy:"all",variables:{id:r}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Dc=async r=>(await y.getShadowGraphqlClient().query({query:Do,errorPolicy:"all",variables:{id:r}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;function jr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const s=r,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,r.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Ee(r.x,t.width-c,0),s.y=Ee(r.y,t.height-d,0),s}const o=r;return o.x=Ee(o.x,-n,t.width),o.y=Ee(o.y,-i,t.height),o}function Ee(r,t,e){return Math.min(Math.max(r,t),e)}class Hr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=bn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let o=0;o<n.currentFrameSources.length;o++){const s=n.currentFrameSources[o],l=await he(s),c=this.frameData?this.frameData[o]:void 0;En(l,c)||(this.frameData||(this.frameData=new Array(n.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 n=Ft.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=Le(this.imageData.svg,this.imageData.colors||{},!1);return $e(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],A=a[s]-c*t[s];return{x:d,y:A,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,n),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 n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new L("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=jr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,i){if(!a||a.length===0||a.some(s=>!s))throw new L("Frame data not set. This is a bug");if(!this.workflowManager)throw new L("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new Q([new ps(s,e,t[l]),new fs(s,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=ka(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Fc{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,n,i,o,s,l,c,d,A,u,h,g,m,p,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Yr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(Yr||{});class Jr extends X{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Hr(n.forceImageCover,n.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 n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Te.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await R.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return R.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return R.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const n=await this.getBackgroundRemovedImageSelection();if(!n)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(n,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const kc=w.gql`
2533
+ `;class Cc{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 wc{init(t,e,a){this.cognitoClient=new fe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const n=await this.cognitoClient?.send(new fe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return n?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new wc;class qr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return di(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ka.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Ka.code(e)?.code==="CLP")return"USD0,0"}}const hn=new qr;class Gr{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,hn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,hn.getPrecisionForCurrency(e))}}const yc=async(r,t)=>{const e=await y.getShadowGraphqlClient().query({query:bo(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:r}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(n=>console.error(n)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(n=>{n.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&R.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&R.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&R.cacheAsset(o.asset),o.thumbnail&&R.cacheAsset(o.thumbnail),o.material&&R.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),n.finalizeStepConfig||(n.finalizeStepConfig={}),n.finalizeStepConfig.termsMarkdown=n.finalizeStepConfig.termsMarkdown||n.partner.termsMarkdown}),a},Sc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},ja=async(r,t)=>{const e=r.map(s=>$t.get({id:s,options:t})),a=r.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=yc(a,t),i=a.map(s=>$t.set({id:s,options:t},Sc(s,n))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},vc=async(r,t)=>(await ja([r],t))[0],Ec=r=>r.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})),bc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):Ec(t.panels)};class Bc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:Ao})}catch(a){throw console.error(a),new gt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Pi(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 32.2.4-beta.2a1f0ff0-c7c4-56e0-afbf-fd744926c42c"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&On(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return R}getFlowService(){if(!xi())throw new Error("Application key required to use Flow Service.");return new Lr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:Mo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new Gr(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=Wr(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 n=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(n)&&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:Bo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const n=a.data.transactions[0];if(!n.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const u=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(u)return Promise.resolve({success:!0,stakeholderType:u.type})}const c=(await e.query({query:Io,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await y.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.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(),n=(await e.query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const s=(await e.mutate({mutation:mc,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(n);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),i=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:ve,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:pc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:ve,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),n=new Date().getTime()/1e3,i=!a?.AccessToken||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||i){const o=await Wt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:fc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:tl(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 aa(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const m=Object.entries(localStorage).find(([f,S])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(m);p&&!_t(p)&&(s.Authorization=`Bearer ${p}`)}const l={bundleOwnerId:o,...s,...n?.graphql?.additionalHeaders},c=await y.getShadowGraphqlClient().query({query:Js(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],A=k.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",A);const u=new aa(this,d,e,a,o,{additionalHeaders:n?.graphql?.additionalHeaders,eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:n?.readonly});return await u.getInitializationPromise(),u}async duplicateBundle(t,e,a,n){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const u=await this.loggedInBearerToken();o.Authorization=`Bearer ${u}`}catch{const g=Object.entries(localStorage).find(([p,f])=>p.startsWith("CognitoIdentityServiceProvider")&&p.endsWith("idToken"))?.[0]||"",m=localStorage.getItem(g);m&&!_t(m)&&(o.Authorization=`Bearer ${m}`)}const s={bundleOwnerId:i,...o,...n?.graphql?.additionalHeaders},c=(await y.getShadowGraphqlClient().mutate({mutation:el(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const A=k.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",A),async()=>{const u=new aa(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await u.getInitializationPromise(),u}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:hl(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:Ks,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||[],n=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&n.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new gt("No options provided!");const a=y.getShadowGraphqlClient(),n=async C=>{if(C.length===0)return[];const E=C.map(D=>D.option.transactionId),x=await a.query({query:co,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),B=x.data.transactions;if(B.length!==C.length){const D=x.errors?.[0]?.message||"Unknown error";throw new gt(`Not all transactions were found: ${D}`)}return!this.activeIntegration&&B[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(B[0].integrationProduct.integration)),B.map((D,O)=>({transaction:D,workflowId:D.workflowId,readOnly:C.find(T=>T.option.transactionId===D.id)?.option.readOnly??!1,index:C[O].index}))},i=async C=>{if(C.length===0)return[];const E=await a.mutate({mutation:lo,variables:{inputs:C.map(B=>({integrationProductId:B.option.type==="integration"?B.option.integrationProductId:void 0,externalIntegrationId:B.option.type==="external"?B.option.externalIntegrationId:void 0,externalProductId:B.option.type==="external"?B.option.externalProductId:void 0,workflowId:B.option.workflowId,designName:B.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),x=E.data?.transactionCreateMany;if(!x||x.length===0){const B=E.errors?.[0]?.message||"Unknown error";throw new gt(`Failed to create transactions: ${B}`)}return x.map((B,D)=>({transaction:B,workflowId:B.workflowId,readOnly:!1,index:C[D].index}))},o=t.map((C,E)=>({option:C,index:E})),s=o.filter(C=>C.option.type==="transaction"),l=o.filter(C=>C.option.type==="integration"||C.option.type==="external"),c=Ja(s,10),d=Ja(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(C=>C.workflowId))],h=await ja(u,e),g=new Map(h.map(C=>[C.id,C])),m=k.getMap("transactionOwnerIds")||new Map,p=A.map(async C=>{const{transaction:E,workflowId:x,readOnly:B,index:D}=C,O=g.get(x),T=t[D];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const et=m.get(E.id)||void 0,at=new Cc({onMutate:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}})}),H={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:T?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:B?async()=>{throw new L("State mutation is forbidden in read only mode!")}:async Y=>this.updateTransactionState({...Y,context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>at,readOnly:B,workflow:O,isReloadedTransaction:T.type==="transaction"};if(T.type==="transaction"&&E.workflowState){const Y=JSON.parse(E.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await ma(Y),H.reloadedState=Y}else if(!B&&T.workflowState){const Y=JSON.parse(T.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await ma(Y),H.reloadedState=Y}else H.layouts=bc(H.transaction,H.workflow);return H.renderableContextService=new jl(H.layouts),H.delayWorkflowStateSync=!0,{experienceOptions:H,index:D,options:T}}),f=await Promise.all(p);k.setMap("transactionOwnerIds",m);const b=f.sort((C,E)=>C.index-E.index).map(async C=>{const{experienceOptions:E,options:x}=C,B=new kr(this,E);return await B.getWorkflowManager().getInitializationPromise(),x.type!=="transaction"&&this.customer&&await B.attachCustomerDetails({email:this.customer.emailAddress}),B}),P=await Promise.all(b);return P.forEach(C=>C.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),P}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:po(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 wa(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:fo(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 wa(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,n=await y.getShadowGraphqlClient().query({query:mo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ko,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 Wr=async(r,t)=>(await y.getShadowGraphqlClient().query({query:xo,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,Ic=async r=>{const e=await y.getShadowGraphqlClient().query({query:go,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Pc=async(r,t)=>(await y.getShadowGraphqlClient().query({query:Po,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,xc=async r=>(await y.getShadowGraphqlClient().query({query:Fo,errorPolicy:"all",variables:{id:r}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Dc=async r=>(await y.getShadowGraphqlClient().query({query:Do,errorPolicy:"all",variables:{id:r}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;function jr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const s=r,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,r.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Ee(r.x,t.width-c,0),s.y=Ee(r.y,t.height-d,0),s}const o=r;return o.x=Ee(o.x,-n,t.width),o.y=Ee(o.y,-i,t.height),o}function Ee(r,t,e){return Math.min(Math.max(r,t),e)}class Hr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=bn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let o=0;o<n.currentFrameSources.length;o++){const s=n.currentFrameSources[o],l=await he(s),c=this.frameData?this.frameData[o]:void 0;En(l,c)||(this.frameData||(this.frameData=new Array(n.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 n=Ft.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=Le(this.imageData.svg,this.imageData.colors||{},!1);return $e(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],A=a[s]-c*t[s];return{x:d,y:A,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,n),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 n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new L("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=jr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,i){if(!a||a.length===0||a.some(s=>!s))throw new L("Frame data not set. This is a bug");if(!this.workflowManager)throw new L("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new Q([new ps(s,e,t[l]),new fs(s,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=ka(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Fc{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,n,i,o,s,l,c,d,A,u,h,g,m,p,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Yr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(Yr||{});class Jr extends X{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Hr(n.forceImageCover,n.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 n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Te.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await R.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return R.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return R.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const n=await this.getBackgroundRemovedImageSelection();if(!n)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(n,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const kc=w.gql`
2534
2534
  query GetLoggedInCustomer($email: String!) {
2535
2535
  customer(emailAddress: $email) {
2536
2536
  id