@spiffcommerce/core 40.0.1 → 40.1.0

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/CHANGELOG.md CHANGED
@@ -14,6 +14,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
14
14
  - `Fixed` for any bug fixes.
15
15
  - `Security` in case of vulnerabilities.
16
16
 
17
+ ## [40.1.0] - 19-03-2026
18
+
19
+ ### Changed
20
+
21
+ - Global property handles will now be considered "silent" if the current bundle's state has the aspect marked as "hidden", in addition to the current behaviour.
22
+
17
23
  ## [40.0.0] - 17-03-2026
18
24
 
19
25
  ### Changed
package/dist/index.cjs CHANGED
@@ -1453,6 +1453,7 @@
1453
1453
  value
1454
1454
  type
1455
1455
  channel
1456
+ hidden
1456
1457
  storage {
1457
1458
  ... on GlobalPropertyStateColorOptionStorage {
1458
1459
  customColor
@@ -2298,7 +2299,7 @@
2298
2299
  }
2299
2300
  }
2300
2301
  }
2301
- `;var Re=(i=>(i.PriceBreakChanged="PriceBreakChanged",i.ProductChanged="ProductChanged",i.QuantityChanged="QuantityChanged",i.RecipientChanged="RecipientChanged",i.SelectionChanged="SelectionChanged",i))(Re||{});class _i{constructor(t,e){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=Ln(async()=>{await xe.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async a=>new Promise((n,r)=>{try{a.toBlob(o=>{if(o){const s=URL.createObjectURL(o);n(s)}})}catch(o){r(o)}}),this.client=t,this.transaction=e.transaction,this.workflow=e.workflow,this.profanityList=this.transaction.product?.profanities?.map(a=>a.word)||[],this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Ta(this,t,a=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(a)},e.graphQlClient,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(a=>{const n=a.traversableScenes.map(r=>{const o=r.renderableSteps.map(s=>s.stepName);return{id:r.name,title:r.title,renderableSteps:o,workflowScene:r}});this.renderableScenes=n,this.renderableSceneCallbacks.forEach(r=>r(n)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.transaction.product}getProfanityList(){return this.profanityList}async setProduct(t){this.workflow=void 0;const e=await this.graphQlClient().mutate({mutation:Dn,variables:{id:this.getTransaction().id,integrationProductId:t}}),a=e.data?.transactionUpdateIntegrationProduct.product;if(!a)throw new O("Failed to set product. No product returned from server.");if(!this.bundle)throw new O("Cannot set product on experience that is not part of a bundle.");this.transaction.product={...this.transaction.product,...e.data?.transactionUpdateIntegrationProduct.product},this.transaction.integrationProduct={...this.transaction.integrationProduct,...e.data?.transactionUpdateIntegrationProduct.integrationProduct},this.transaction.workflowState=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged");const n=(await this.bundle.getProductCollection().fetchProducts()).find(r=>r.getId()===a.id);try{const r=n?.getDefaultWorkflow();if(r){const o=await lr(r.getId());await this.setWorkflow(o),console.log("Setting Product - Workflow set to default for product.")}}catch{console.log("Setting Product - No default workflow available, must be set manually.")}}async clearProduct(){if(!this.bundle)throw new O("Cannot clear product on experience that is not part of a bundle.");this.workflow=void 0,this.transaction.workflowState=void 0,this.transaction.product=void 0,this.transaction.integrationProduct=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged"),await this.graphQlClient().mutate({mutation:Dn,variables:{id:this.getTransaction().id}})}getWorkflow(){return this.workflow}async setWorkflow(t){return this.workflow=t,await this.graphQlClient().mutate({mutation:jo,variables:{id:this.getTransaction().id,workflowId:t.id}}),this.workflowManager.setWorkflow(t)}async attachAddress(t,e,a,n,r,o){await this.graphQlClient().mutate({mutation:Fc,variables:{transactionId:this.getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:r||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:Dc,variables:{transactionId:this.getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.workflowManager.getCommandContext()}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.getWorkflow(),n=a?.finalizeStepConfig?.lookAtAnimation;if(!a)throw new Error("Failed to generate cart preview image! No workflow is set.");if(t){if(!n)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,n)||""}let r=2048;e&&e<=2048&&(r=e);const o=St(r,r),s=this.workflowManager.getCommandContext().getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=s.find(w=>w.layoutState?.layout.panelId===c?.name)||s[0],u=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},A=this.workflowManager.getCommandContext().getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new Le("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),p=Xe(A.layoutState.layout,A.layoutState.elements,{renderingConfiguration:{purpose:Ot.Print,region:{left:u.x,top:u.y,width:u.width,height:u.height},templatingContext:g}}),m=Zn(p);await(await $a.Pith.from(h,m,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:St,createImage:de,DOMParser:qa(),fetch})).render();const S=await this.getCanvasObjectURLAsync(o);return o.toDataURL(S)}getStepById(t){const e=this.getWorkflow()?.steps.find(r=>r.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const n=be.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,n),n}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}async getStepsConditionallyActive(){const t=this.getScenes();return(await Promise.all(t.map(async a=>{const n=this.getStepsByScene(a),r=await Promise.all(n.map(o=>Ct(o.getRaw(),this.getWorkflowManager().getStepSelections())));return n.filter((o,s)=>r[s])}))).flat()}getScenes(){return(this.getWorkflow()?.stepGroups||[]).map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let a=0;return Object.values(e).forEach(n=>{a+=n.selections.reduce((r,o)=>r+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,e);if(t){const n=this.getAdditionalProductPriceSubunits(e)||0;return a+n}return a}getAdditionalProductPriceSubunits(t){const e=this.getTransaction().integrationProduct;if(e?.additionalIntegrationProduct?.product){const a=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(a,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),n=t*a;return Math.ceil(n)}priceBreakToBeApplied(){const t=(this.getProduct()?.priceBreaks||[]).sort((n,r)=>-(n.minQty-r.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((n,r)=>n+r.getQuantity(),0);for(const n of t)if(n.minQty<=a)return n.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(t=>{const e=t.getTransaction().id,a=this.getTransaction().id,n=t.getProduct()?.id,r=this.getProduct()?.id;return e!==a&&n===r})}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const n=await t.getGlobalProperties(),r=a?.map(c=>c.getId()),o=this.getSteps().filter(c=>r===void 0||r.includes(c.getId())),s=e.getSteps(),l=c=>n.find(d=>d.getRawProperty().name===c.aspectName);o.forEach(c=>{const d=new Set,u=c.getRaw().globalPropertyAspectConfigurations;u!==void 0&&(u.forEach(A=>d.add(JSON.stringify(A))),s.forEach(A=>{const h=A.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const p=l(g),m=d.has(JSON.stringify(g));if(m&&p?.getType()==="Option"){const C=A.getCurrentVariant();if(!C)return;c.selectVariant(C),d.delete(JSON.stringify(g))}else if(m&&p?.getType()==="Text"){const C=A.getText();c.setText(C),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflow()?.steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return be.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflow()?.steps.filter(e=>e.type===t).map(e=>be.get(this.getWorkflowManager(),e))||[]}getStepsByScene(t){const e=this.getWorkflow();if(!e?.stepGroups.find(n=>n.name===t.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map(n=>e.steps.find(r=>r.stepName===n)).filter(n=>!!n&&this.stepHasHandle(n)).map(n=>be.get(this.getWorkflowManager(),n))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:xc,variables:{id:this.getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(n=>n.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const n=Q.getMap("transactionCustomerIds")||new Map;n.set(this.getTransaction().id,a.customer.id),Q.setMap("transactionCustomerIds",n)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){const e=this.getProduct(),a=this.getWorkflow(),n=this.getCommandContext().getState();if(!e)throw new O("Product undefined!");if(!a)throw new O("Workflow undefined!");if(!n)throw new O("State undefined!");const o={title:await(async()=>{if(t)return t;const s=this.getTransaction().id,c=(await xe.getSavedDesigns()).find(d=>d.transactionId===s)?.title;return c||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getTransaction().id,productId:e.id,integrationProductId:this.getTransaction().integrationProduct.id,workflowName:a.name,workflowId:a.id,lastEdited:new Date};return await xe.addDesign(o),o}async copy(){const t=Pt(this.getCommandContext().getState());if(!t)throw new O("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflow();if(!a)throw new O("Workflow is undefined! Cannot copy experience!");const n=this.getTransaction().integrationProduct?.id;if(!n)throw new O("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:n,workflowId:a.id,workflowState:e})}async onDesignFinished(t=!0){const e=this.getTransaction(),a=this.getProduct(),n=this.getWorkflow();if(!a)throw new O("Product undefined! Cannot finish an experience without a product.");if(!n)throw new O("Workflow undefined! Cannot finish an experience without a workflow.");if(e.isOrdered)return{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:e.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""};const r=await Ki([{workflowManager:this.workflowManager,workflow:n,layouts:this.workflowManager.getLayouts(),getReducerState:()=>this.workflowManager.getCommandContext().getState(),product:a,transaction:e,workflowSelections:this.workflowManager.getWorkflowSelections(),workflowMetadata:this.workflowManager.getWorkflowMetadata(),designName:n.name}],o=>t?this.createPreviewImage(o,1024):Promise.resolve(void 0));return e.completed&&await this.graphQlClient().mutate({mutation:Zo,variables:{transactionId:e.id}}),r[0]}stepHasHandle(t){return t.type!==E.SilentIllustration&&t.type!==E.ProductOverlay}async getExportedStepData(){const t=this.getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),n=[];for(const r of t?.steps||[]){const o=r.stepName,s=e[o],l=a[o]?.selections[0],c={stepId:o,title:r.stepTitle,properties:[]};if(l&&await Mc(r,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){n.push(c);continue}switch(r.type){case E.Frame:{const d=r.data,u=s;u.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case E.Illustration:{const d=r.data,u=s;if(u&&u.colors&&u.colors.length>0&&d.displayColorsOnFinishStep){const A=u.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:A,priceModifier:0})}}break;case E.Module:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case E.Text:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0}),u&&u.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:u.color,priceModifier:0})}}n.push(c)}return n.filter(r=>r.properties&&r.properties.length>0)}getQuantity(){return this.getTransaction().quantity||1}async setQuantity(t){if(t<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getTransaction();await this.graphQlClient().mutate({mutation:Go,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const a=this.eventCallbacks.get(t)||[];a.push(e),this.eventCallbacks.set(t,a)}removeEventListener(t,e){const a=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,a.filter(n=>n!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const kc=i=>{if([E.Question,E.Frame,E.Illustration,E.Material,E.Model,E.Picture,E.Shape,E.Text].includes(i.type)){const e=i.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Mc=async(i,t)=>{if(!kc(i))return!1;const e=await P.getOptionForStep(i);if(e&&(e.variants||[]).length>1){const a=t[i.stepName];return!!(a&&a.selections.length>0)}return!1};class Tc{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 t?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.conditionMode===qn.AND?Array.prototype.every.bind(t.conditions):Array.prototype.some.bind(t.conditions))(n=>{const r=e.aspects.find(o=>o.name===n.targetAspectName);return r?n.requiredVariantSelections.some(o=>o===r.value):!1})}async createHandle(t){switch(t.type){case z.FileUpload:return new Xi(this.bundle,t).initialize();case z.ColorOption:return new Na(this.bundle,t,t.entityId?await P.getOption(t.entityId):void 0);case z.Option:{const e=t.entityId?await P.getOption(t.entityId):void 0;return e?.type==="Color"?new Na(this.bundle,t,e):new nn(this.bundle,t,e)}case z.Text:return new Zi(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class ea{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)}isSilent(){return!!this.property.silent}async getSharedSteps(t){const e=t??this.bundle.getWorkflowExperiences();return(await Promise.all(e.map(r=>r.getStepsConditionallyActive()))).map(r=>r.filter(o=>o.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:o.getRaw().globalPropertyAspectConfigurations?.some(s=>s.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&s.aspectName===this.property.name))).flat()}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Xi extends ea{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await P.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 et(t?.fileLink),a=await Wa(t?.fileLink),n=a.width,r=a.height,o=await rt(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:r,aspect:n/r,svg:o.svg,colors:o.colors};ht.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,vectorizedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseAdvancedImageManipulation(){return this.bundle.getClient().canUseAddon(Ue.AdvancedImageManipulation)}async removeBackgroundFromImage(t=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Advanced Image Manipulation addon. Please call canUseAdvancedImageManipulation 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 G.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}async vectorizeImage(t=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Advanced Image Manipulation addon. Please call canUseAdvancedImageManipulation 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 vectorize the image.");const a=this.bundle.getGlobalPropertyStateManager(),n=await G.vectorizeAsset(e),o={...a.getAspectStorage(this.property.name),vectorizedAssetKey: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 G.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Ge(He(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 G.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return G.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 r={...n,useOriginalAsset:t},o=t?n?.originalAssetKey:n?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",r)];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(r)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await G.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 r=new Map(n.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);await Promise.all((await this.getSharedSteps(t)).map(async o=>{await o.changeColors(r)}))}}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 rt(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));await Promise.all((await e).map(async r=>{await r.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(([r,o])=>({key:r,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const o=(await 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 Zi extends ea{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=(await this.getSharedSteps(e)).map(r=>{r.setText(t)});await Promise.all(n)}}class nn extends ea{constructor(t,e,a){super(t,e),this.optionResource=a}async ensureOptionLoaded(){if(this.optionResource?.variants)return this.optionResource;if(!this.property.entityId)return this.optionResource;const t=await P.getOption(this.property.entityId);return t&&(this.optionResource=t),this.optionResource}async initDefaultVariant(){await this.ensureOptionLoaded();const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new nt(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 nt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new nt(e):void 0}}async getAvailableVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new nt(e))}async getAllVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants||[]).map(e=>new nt(e))}async selectVariant(t,e){await this.applyVariantSelection(t),await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(n=>n.id===e);if(a)return this.applyVariantSelection(new nt(a),t)}async applyVariantSelection(t,e){const n=(await this.getSharedSteps(e)).map(r=>r.selectVariant(t));await Promise.all(n)}}class Na extends nn{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),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(r=>r.id===e);if(!a)return;await this.applyColorVariant(new nt(a),t);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;n&&await this.setCustomColor(n)}async applyColorVariant(t,e,a){const r=(await this.getSharedSteps(e)).map(o=>{switch(o.getType()){case E.Shape:return o.selectVariant(t);case E.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case E.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(r)}async setCustomColor(t){const e=this.getCurrentVariant()?.getColor();e&&e.toLowerCase()==="#custom"&&(await this.getSharedSteps()).forEach(n=>n.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 Nc=(i,t,e)=>{const a=i.getWorkflowExperiences(),n=i.getGlobalPropertyConfiguration();return n?a.flatMap(o=>o.getSteps()).filter(o=>o.getGlobalPropertyAspects(n.id).includes(t)&&o.getType()===e):[]},tr=(i,t)=>{const a=Nc(i,t,E.Illustration).map(n=>{if(!n.getCurrentVariant()?.getAssetResource()?.assetConfiguration)return 0;const o=n.getColors();return o?Object.getOwnPropertyNames(o).length:0});return Math.max(...a)};function Qa(i,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!Oc(a))return a;if(Array.isArray(a))return Qa(a,t);let n={};for(const[r,o]of Object.entries(a))n[r]=Qc(o)?o:Qa(o,t);return Lr(n,t)}return Array.isArray(i)?i.map(e):e(i)}function Qc(i){return i==null}function Oc(i){return typeof i=="object"&&!Array.isArray(i)&&i!==null}function er(i){const t=new Map;return i?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}class Rc extends Ke{constructor(t){super(),this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},1e3)})}}function pa(i){return Qa(i,["__typename"])}class $c{constructor(t,e,a,n,r){this.stateUpdateQueue=new _e(1),this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=r;const o=r?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=pa(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=pa(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=n}async clearAspects(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects;this.globalPropertyState.aspects=e.filter(a=>!t.includes(a.name))}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=er(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=Pt(this.globalPropertyState);this.globalPropertyState={...pa(t),id:e.id},this.recalculateMandatoryStates(),this.queueGlobalPropertyStateUpdate(),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 r=this.configuration.aspects.find(l=>l.name===t);if(!r)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const o=Pt(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=r.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:r.type,storage:a!==null?a:void 0,channel:n})}}else{const l=s[0];l.value=e,l.type=r.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:r.type,storage:a!==null?a:void 0,channel:n});ae(o,this.globalPropertyState)||(this.queueGlobalPropertyStateUpdate(),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 r=Pt(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});ae(r,this.globalPropertyState)||(this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(r,this.globalPropertyState))}queueGlobalPropertyStateUpdate(){this.stateUpdateQueue.enqueue(new Rc(async()=>{await this.updateGlobalPropertyState()}))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!(await y.getShadowGraphqlClient().mutate({mutation:$l,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 z.FileUpload:{a.fileUpload=e.storage;break}case z.Option:{a.option=e.storage;break}case z.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}}})).data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:Rl,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 Uc{constructor(t){this.setState(t||'{"transactions": []}')}setState(t){t&&(this.state=JSON.parse(t))}getState(){return this.state}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)}}const Vc=f.gql`
2302
+ `;var Re=(i=>(i.PriceBreakChanged="PriceBreakChanged",i.ProductChanged="ProductChanged",i.QuantityChanged="QuantityChanged",i.RecipientChanged="RecipientChanged",i.SelectionChanged="SelectionChanged",i))(Re||{});class _i{constructor(t,e){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=Ln(async()=>{await xe.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async a=>new Promise((n,r)=>{try{a.toBlob(o=>{if(o){const s=URL.createObjectURL(o);n(s)}})}catch(o){r(o)}}),this.client=t,this.transaction=e.transaction,this.workflow=e.workflow,this.profanityList=this.transaction.product?.profanities?.map(a=>a.word)||[],this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Ta(this,t,a=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(a)},e.graphQlClient,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(a=>{const n=a.traversableScenes.map(r=>{const o=r.renderableSteps.map(s=>s.stepName);return{id:r.name,title:r.title,renderableSteps:o,workflowScene:r}});this.renderableScenes=n,this.renderableSceneCallbacks.forEach(r=>r(n)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.transaction.product}getProfanityList(){return this.profanityList}async setProduct(t){this.workflow=void 0;const e=await this.graphQlClient().mutate({mutation:Dn,variables:{id:this.getTransaction().id,integrationProductId:t}}),a=e.data?.transactionUpdateIntegrationProduct.product;if(!a)throw new O("Failed to set product. No product returned from server.");if(!this.bundle)throw new O("Cannot set product on experience that is not part of a bundle.");this.transaction.product={...this.transaction.product,...e.data?.transactionUpdateIntegrationProduct.product},this.transaction.integrationProduct={...this.transaction.integrationProduct,...e.data?.transactionUpdateIntegrationProduct.integrationProduct},this.transaction.workflowState=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged");const n=(await this.bundle.getProductCollection().fetchProducts()).find(r=>r.getId()===a.id);try{const r=n?.getDefaultWorkflow();if(r){const o=await lr(r.getId());await this.setWorkflow(o),console.log("Setting Product - Workflow set to default for product.")}}catch{console.log("Setting Product - No default workflow available, must be set manually.")}}async clearProduct(){if(!this.bundle)throw new O("Cannot clear product on experience that is not part of a bundle.");this.workflow=void 0,this.transaction.workflowState=void 0,this.transaction.product=void 0,this.transaction.integrationProduct=void 0,this.currentPriceBreak=this.priceBreakToBeApplied(),this.callEvent("ProductChanged"),await this.graphQlClient().mutate({mutation:Dn,variables:{id:this.getTransaction().id}})}getWorkflow(){return this.workflow}async setWorkflow(t){return this.workflow=t,await this.graphQlClient().mutate({mutation:jo,variables:{id:this.getTransaction().id,workflowId:t.id}}),this.workflowManager.setWorkflow(t)}async attachAddress(t,e,a,n,r,o){await this.graphQlClient().mutate({mutation:Fc,variables:{transactionId:this.getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:r||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:Dc,variables:{transactionId:this.getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.workflowManager.getCommandContext()}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.getWorkflow(),n=a?.finalizeStepConfig?.lookAtAnimation;if(!a)throw new Error("Failed to generate cart preview image! No workflow is set.");if(t){if(!n)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,n)||""}let r=2048;e&&e<=2048&&(r=e);const o=St(r,r),s=this.workflowManager.getCommandContext().getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=s.find(w=>w.layoutState?.layout.panelId===c?.name)||s[0],u=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},A=this.workflowManager.getCommandContext().getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new Le("Failed to obtain 2D context for preview image creation");const g=this.workflowManager.getTemplatingContext(),p=Xe(A.layoutState.layout,A.layoutState.elements,{renderingConfiguration:{purpose:Ot.Print,region:{left:u.x,top:u.y,width:u.width,height:u.height},templatingContext:g}}),m=Zn(p);await(await $a.Pith.from(h,m,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:St,createImage:de,DOMParser:qa(),fetch})).render();const S=await this.getCanvasObjectURLAsync(o);return o.toDataURL(S)}getStepById(t){const e=this.getWorkflow()?.steps.find(r=>r.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const n=be.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,n),n}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}async getStepsConditionallyActive(){const t=this.getScenes();return(await Promise.all(t.map(async a=>{const n=this.getStepsByScene(a),r=await Promise.all(n.map(o=>Ct(o.getRaw(),this.getWorkflowManager().getStepSelections())));return n.filter((o,s)=>r[s])}))).flat()}getScenes(){return(this.getWorkflow()?.stepGroups||[]).map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let a=0;return Object.values(e).forEach(n=>{a+=n.selections.reduce((r,o)=>r+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,e);if(t){const n=this.getAdditionalProductPriceSubunits(e)||0;return a+n}return a}getAdditionalProductPriceSubunits(t){const e=this.getTransaction().integrationProduct;if(e?.additionalIntegrationProduct?.product){const a=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(a,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),n=t*a;return Math.ceil(n)}priceBreakToBeApplied(){const t=(this.getProduct()?.priceBreaks||[]).sort((n,r)=>-(n.minQty-r.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((n,r)=>n+r.getQuantity(),0);for(const n of t)if(n.minQty<=a)return n.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){return(this.bundle?.getWorkflowExperiences()||[]).filter(t=>{const e=t.getTransaction().id,a=this.getTransaction().id,n=t.getProduct()?.id,r=this.getProduct()?.id;return e!==a&&n===r})}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const n=await t.getGlobalProperties(),r=a?.map(c=>c.getId()),o=this.getSteps().filter(c=>r===void 0||r.includes(c.getId())),s=e.getSteps(),l=c=>n.find(d=>d.getRawProperty().name===c.aspectName);o.forEach(c=>{const d=new Set,u=c.getRaw().globalPropertyAspectConfigurations;u!==void 0&&(u.forEach(A=>d.add(JSON.stringify(A))),s.forEach(A=>{const h=A.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const p=l(g),m=d.has(JSON.stringify(g));if(m&&p?.getType()==="Option"){const C=A.getCurrentVariant();if(!C)return;c.selectVariant(C),d.delete(JSON.stringify(g))}else if(m&&p?.getType()==="Text"){const C=A.getText();c.setText(C),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflow()?.steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return be.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflow()?.steps.filter(e=>e.type===t).map(e=>be.get(this.getWorkflowManager(),e))||[]}getStepsByScene(t){const e=this.getWorkflow();if(!e?.stepGroups.find(n=>n.name===t.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map(n=>e.steps.find(r=>r.stepName===n)).filter(n=>!!n&&this.stepHasHandle(n)).map(n=>be.get(this.getWorkflowManager(),n))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:xc,variables:{id:this.getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(n=>n.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const n=Q.getMap("transactionCustomerIds")||new Map;n.set(this.getTransaction().id,a.customer.id),Q.setMap("transactionCustomerIds",n)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){const e=this.getProduct(),a=this.getWorkflow(),n=this.getCommandContext().getState();if(!e)throw new O("Product undefined!");if(!a)throw new O("Workflow undefined!");if(!n)throw new O("State undefined!");const o={title:await(async()=>{if(t)return t;const s=this.getTransaction().id,c=(await xe.getSavedDesigns()).find(d=>d.transactionId===s)?.title;return c||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getTransaction().id,productId:e.id,integrationProductId:this.getTransaction().integrationProduct.id,workflowName:a.name,workflowId:a.id,lastEdited:new Date};return await xe.addDesign(o),o}async copy(){const t=Pt(this.getCommandContext().getState());if(!t)throw new O("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflow();if(!a)throw new O("Workflow is undefined! Cannot copy experience!");const n=this.getTransaction().integrationProduct?.id;if(!n)throw new O("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:n,workflowId:a.id,workflowState:e})}async onDesignFinished(t=!0){const e=this.getTransaction(),a=this.getProduct(),n=this.getWorkflow();if(!a)throw new O("Product undefined! Cannot finish an experience without a product.");if(!n)throw new O("Workflow undefined! Cannot finish an experience without a workflow.");if(e.isOrdered)return{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:e.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""};const r=await Ki([{workflowManager:this.workflowManager,workflow:n,layouts:this.workflowManager.getLayouts(),getReducerState:()=>this.workflowManager.getCommandContext().getState(),product:a,transaction:e,workflowSelections:this.workflowManager.getWorkflowSelections(),workflowMetadata:this.workflowManager.getWorkflowMetadata(),designName:n.name}],o=>t?this.createPreviewImage(o,1024):Promise.resolve(void 0));return e.completed&&await this.graphQlClient().mutate({mutation:Zo,variables:{transactionId:e.id}}),r[0]}stepHasHandle(t){return t.type!==E.SilentIllustration&&t.type!==E.ProductOverlay}async getExportedStepData(){const t=this.getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),n=[];for(const r of t?.steps||[]){const o=r.stepName,s=e[o],l=a[o]?.selections[0],c={stepId:o,title:r.stepTitle,properties:[]};if(l&&await Mc(r,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){n.push(c);continue}switch(r.type){case E.Frame:{const d=r.data,u=s;u.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case E.Illustration:{const d=r.data,u=s;if(u&&u.colors&&u.colors.length>0&&d.displayColorsOnFinishStep){const A=u.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:A,priceModifier:0})}}break;case E.Module:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case E.Text:{const d=r.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0}),u&&u.color&&d.displayColorOnFinishStep&&c.properties.push({type:"color",value:u.color,priceModifier:0})}}n.push(c)}return n.filter(r=>r.properties&&r.properties.length>0)}getQuantity(){return this.getTransaction().quantity||1}async setQuantity(t){if(t<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getTransaction();await this.graphQlClient().mutate({mutation:Go,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const a=this.eventCallbacks.get(t)||[];a.push(e),this.eventCallbacks.set(t,a)}removeEventListener(t,e){const a=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,a.filter(n=>n!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const kc=i=>{if([E.Question,E.Frame,E.Illustration,E.Material,E.Model,E.Picture,E.Shape,E.Text].includes(i.type)){const e=i.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Mc=async(i,t)=>{if(!kc(i))return!1;const e=await P.getOptionForStep(i);if(e&&(e.variants||[]).length>1){const a=t[i.stepName];return!!(a&&a.selections.length>0)}return!1};class Tc{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 t?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.conditionMode===qn.AND?Array.prototype.every.bind(t.conditions):Array.prototype.some.bind(t.conditions))(n=>{const r=e.aspects.find(o=>o.name===n.targetAspectName);return r?n.requiredVariantSelections.some(o=>o===r.value):!1})}async createHandle(t){switch(t.type){case z.FileUpload:return new Xi(this.bundle,t).initialize();case z.ColorOption:return new Na(this.bundle,t,t.entityId?await P.getOption(t.entityId):void 0);case z.Option:{const e=t.entityId?await P.getOption(t.entityId):void 0;return e?.type==="Color"?new Na(this.bundle,t,e):new nn(this.bundle,t,e)}case z.Text:return new Zi(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class ea{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)}isSilent(){return!!this.property.silent||this.bundle.getGlobalPropertyStateManager().getAspectHidden(this.property.name)}async getSharedSteps(t){const e=t??this.bundle.getWorkflowExperiences();return(await Promise.all(e.map(r=>r.getStepsConditionallyActive()))).map(r=>r.filter(o=>o.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:o.getRaw().globalPropertyAspectConfigurations?.some(s=>s.globalPropertyConfigurationId===this.bundle.getProductCollection()?.getResource().globalPropertyConfiguration?.id&&s.aspectName===this.property.name))).flat()}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Xi extends ea{constructor(t,e){super(t,e)}async initialize(){return this.property.data?.fileUpload?.colorOptionId&&(this.colorOption=await P.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 et(t?.fileLink),a=await Wa(t?.fileLink),n=a.width,r=a.height,o=await rt(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:r,aspect:n/r,svg:o.svg,colors:o.colors};ht.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,vectorizedAssetKey:void 0,useOriginalAsset:void 0},void 0),this.applyImageSelection(t),this.loadImageData()])}async canUseAdvancedImageManipulation(){return this.bundle.getClient().canUseAddon(Ue.AdvancedImageManipulation)}async removeBackgroundFromImage(t=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Advanced Image Manipulation addon. Please call canUseAdvancedImageManipulation 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 G.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}async vectorizeImage(t=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Advanced Image Manipulation addon. Please call canUseAdvancedImageManipulation 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 vectorize the image.");const a=this.bundle.getGlobalPropertyStateManager(),n=await G.vectorizeAsset(e),o={...a.getAspectStorage(this.property.name),vectorizedAssetKey: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 G.getLocalOrFromServer(t)}async getImageWithColors(){return await this.loadImageData(),this.imageData?.svg?Ge(He(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 G.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t?.backgroundRemovedAssetKey)return G.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 r={...n,useOriginalAsset:t},o=t?n?.originalAssetKey:n?.backgroundRemovedAssetKey,s=[a.setAspect(this.property.name,o||"",r)];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(r)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await G.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 r=new Map(n.colors.map(o=>[o.key,{browserValue:o.browserValue,pmsValue:o.pmsValue}])??[]);await Promise.all((await this.getSharedSteps(t)).map(async o=>{await o.changeColors(r)}))}}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 rt(this.imageData.svg)).colors:void 0}async changeColors(t){if(!this.imageData?.svg)return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));await Promise.all((await e).map(async r=>{await r.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(([r,o])=>({key:r,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const o=(await 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 Zi extends ea{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=(await this.getSharedSteps(e)).map(r=>{r.setText(t)});await Promise.all(n)}}class nn extends ea{constructor(t,e,a){super(t,e),this.optionResource=a}async ensureOptionLoaded(){if(this.optionResource?.variants)return this.optionResource;if(!this.property.entityId)return this.optionResource;const t=await P.getOption(this.property.entityId);return t&&(this.optionResource=t),this.optionResource}async initDefaultVariant(){await this.ensureOptionLoaded();const t=this.optionResource?.variants?.find(e=>e.id===this.optionResource?.defaultVariant?.id);t&&await this.selectVariant(new nt(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 nt(e):void 0}else{const e=this.optionResource.variants?.find(a=>a.id===this.optionResource?.defaultVariant?.id);return e?new nt(e):void 0}}async getAvailableVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants?.filter(e=>e.enabled)||[]).map(e=>new nt(e))}async getAllVariants(){return await this.ensureOptionLoaded(),(this.optionResource?.variants||[]).map(e=>new nt(e))}async selectVariant(t,e){await this.applyVariantSelection(t),await this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(n=>n.id===e);if(a)return this.applyVariantSelection(new nt(a),t)}async applyVariantSelection(t,e){const n=(await this.getSharedSteps(e)).map(r=>r.selectVariant(t));await Promise.all(n)}}class Na extends nn{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),await this.applyColorVariant(t,void 0,e)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;await this.ensureOptionLoaded();const a=this.optionResource?.variants?.find(r=>r.id===e);if(!a)return;await this.applyColorVariant(new nt(a),t);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name)?.customColor;n&&await this.setCustomColor(n)}async applyColorVariant(t,e,a){const r=(await this.getSharedSteps(e)).map(o=>{switch(o.getType()){case E.Shape:return o.selectVariant(t);case E.Text:return o.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case E.Illustration:return o.setColor(a?.toString()||"",t.getColor()||"")}});await Promise.all(r)}async setCustomColor(t){const e=this.getCurrentVariant()?.getColor();e&&e.toLowerCase()==="#custom"&&(await this.getSharedSteps()).forEach(n=>n.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 Nc=(i,t,e)=>{const a=i.getWorkflowExperiences(),n=i.getGlobalPropertyConfiguration();return n?a.flatMap(o=>o.getSteps()).filter(o=>o.getGlobalPropertyAspects(n.id).includes(t)&&o.getType()===e):[]},tr=(i,t)=>{const a=Nc(i,t,E.Illustration).map(n=>{if(!n.getCurrentVariant()?.getAssetResource()?.assetConfiguration)return 0;const o=n.getColors();return o?Object.getOwnPropertyNames(o).length:0});return Math.max(...a)};function Qa(i,t){function e(a){if(typeof a>"u"||!Array.isArray(a)&&!Oc(a))return a;if(Array.isArray(a))return Qa(a,t);let n={};for(const[r,o]of Object.entries(a))n[r]=Qc(o)?o:Qa(o,t);return Lr(n,t)}return Array.isArray(i)?i.map(e):e(i)}function Qc(i){return i==null}function Oc(i){return typeof i=="object"&&!Array.isArray(i)&&i!==null}function er(i){const t=new Map;return i?.aspects?.forEach(e=>{e.value!==""&&t.set(e.name,!0)}),t}class Rc extends Ke{constructor(t){super(),this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},1e3)})}}function pa(i){return Qa(i,["__typename"])}class $c{constructor(t,e,a,n,r){this.stateUpdateQueue=new _e(1),this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=r;const o=r?.existingGlobalPropertyState;this.initPromise=o?Promise.resolve(o).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=pa(o),this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(s=>{console.log("Setting global property state to new state."),this.globalPropertyState=pa(s),this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=n}async clearAspects(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects;this.globalPropertyState.aspects=e.filter(a=>!t.includes(a.name))}recalculateMandatoryStates(){this.mandatoryFulfilledAspects=er(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=Pt(this.globalPropertyState);this.globalPropertyState={...pa(t),id:e.id},this.recalculateMandatoryStates(),this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects.get(t)}getAspectHidden(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");return!!this.globalPropertyState.aspects.find(e=>e.name===t)?.hidden}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,r){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 o=this.configuration.aspects.find(c=>c.name===t);if(!o)throw new Error(`Failed to find configuration aspect with name: ${t}`);this.mandatoryFulfilledAspects.set(t,e!=="");const s=Pt(this.globalPropertyState),l=this.globalPropertyState.aspects.filter(c=>c.name===t);if(l.length>0)if(n){const c=l.find(d=>d.channel===n);if(c)c.value=e,c.type=o.type,c.channel=n,c.hidden=r??c.hidden,a!==void 0&&(c.storage=a!==null?a:void 0);else{let d;if(n===1){const u=this.globalPropertyState.aspects.findIndex(A=>!A.channel&&A.name===t);u&&u>0&&(d=this.globalPropertyState.aspects.splice(u,1)[0].hidden)}this.globalPropertyState.aspects.push({name:t,value:e,type:o.type,storage:a!==null?a:void 0,channel:n,hidden:r??d})}}else{const c=l[0];c.value=e,c.type=o.type,c.hidden=r??c.hidden,a!==void 0&&(c.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:o.type,storage:a!==null?a:void 0,channel:n,hidden:r});ae(s,this.globalPropertyState)||(this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(s,this.globalPropertyState))}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(s=>s.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const r=Pt(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});ae(r,this.globalPropertyState)||(this.queueGlobalPropertyStateUpdate(),await this.onGlobalPropertyStateChange(r,this.globalPropertyState))}queueGlobalPropertyStateUpdate(){this.stateUpdateQueue.enqueue(new Rc(async()=>{await this.updateGlobalPropertyState()}))}async updateGlobalPropertyState(){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!(await y.getShadowGraphqlClient().mutate({mutation:$l,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 z.FileUpload:{a.fileUpload=e.storage;break}case z.Option:{a.option=e.storage;break}case z.ColorOption:{a=e.storage;break}}return{name:e.name,value:e.value,type:e.type,storage:a,channel:e.channel,hidden:e.hidden}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...this.bundleOptions?.additionalHeaders}}})).data?.globalPropertyStateUpdate)throw new Error("Unable to update global property state")}async createGlobalPropertyState(){const t=await y.getShadowGraphqlClient().mutate({mutation:Rl,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 Uc{constructor(t){this.setState(t||'{"transactions": []}')}setState(t){t&&(this.state=JSON.parse(t))}getState(){return this.state}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)}}const Vc=f.gql`
2302
2303
  query GetManyMetafields($entityIds: [String!]!) {
2303
2304
  metafieldsMany(entityIds: $entityIds) {
2304
2305
  id
@@ -2352,7 +2353,7 @@
2352
2353
  quoteId
2353
2354
  }
2354
2355
  }
2355
- `;class kn{constructor(t,e,a,n,r,o,s){this.workflowExperiences=[],this.eventEmitter=new Gc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=r,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Uc(e.bundleStateData);const l=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=l?.id,this.globalPropertyStateManager=new $c(this.id,this.ownerId,l,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new Tc(this),this.setPreviewService(a),this.initializationPromise=(async()=>{if(!o?.readonly){const c=this.bundleStateManager.getState();if(c.integrationProductIds&&c.integrationProductIds.length>0){const d=await y.getShadowGraphqlClient().query({query:pi,variables:{ids:c.integrationProductIds},errorPolicy:"all",fetchPolicy:"no-cache"});if(d.errors)throw new Error(`Failed to fetch integration products for Bundle ${e.id}`);const u=d.data.integrationProducts?.filter(h=>!!h.product?.id&&c.integrationProductIds.includes(h.id)).map(h=>h.product.id);c.integrationProductIds=[],c.productIds=Array.from(new Set([...c.productIds||[],...u||[]]));const A=JSON.stringify(c);this.bundleStateManager.setState(A),await y.getShadowGraphqlClient().mutate({mutation:Ee,variables:{id:this.id,bundleStateData:A},context:{bundleOwnerId:r}})}}return Promise.all([this.loadExistingWorkflowExperiences(e.transactionIds||[],{...n,bundleOwnerId:r},s),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>new Promise((c,d)=>{if(o?.readonly){c([]);return}console.log("Setting default global variants."),this.initializeUninitializedHandles().then(c).catch(d)}))})(),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}async initializeUninitializedHandles(){const t=this.globalPropertyStateManager.getGlobalPropertyState();if(!t)return console.log("Attempted to set global default variant before state was initialized."),[];const a=(await this.globalPropertyHandleService.getHandles()).map(async n=>{if(n.getType()===z.ColorOption||n.getType()===z.Option){const r=n;if(!t.aspects.find(s=>s.name===r.getName()))try{return await r.initDefaultVariant()}catch(s){console.error(`Failed to initialize default global variant - ${s}`)}}});return Promise.all(a)}getProductIds(){return this.bundleStateManager.getState()?.productIds}async addProductId(t){const e=this.bundleStateManager.getState();if(e){if(!e.productIds)e.productIds=[];else if(e.productIds.some(n=>n===t)){this.fireEvent("bundle-products-added",{productIds:e.productIds,added:[]});return}e.productIds=[...e.productIds,t];const a=JSON.stringify(e);this.bundleStateManager.setState(a),this.fireEvent("bundle-products-added",{productIds:e.productIds,added:[t]}),await y.getShadowGraphqlClient().mutate({mutation:Ee,variables:{id:this.id,bundleStateData:a},context:{bundleOwnerId:this.ownerId}})}}async removeProductIds(t){const e=this.bundleStateManager.getState();if(e){const a=t.filter(r=>(e.productIds??[]).includes(r));if(a.length===0)return;e.productIds=(e.productIds??[]).filter(r=>!a.includes(r));const n=JSON.stringify(e);this.bundleStateManager.setState(n),this.fireEvent("bundle-products-removed",{productIds:e.productIds,removed:a}),await y.getShadowGraphqlClient().mutate({mutation:Ee,variables:{id:this.id,bundleStateData:n},context:{bundleOwnerId:this.ownerId}})}}getTemplate(){return this.template}async generateQuoteId(){const e=(await y.getShadowGraphqlClient().mutate({mutation:Wc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,n,r,o){await y.getShadowGraphqlClient().mutate({mutation:jc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:r||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await y.getShadowGraphqlClient().mutate({mutation:Hc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const a of t.aspects){const n=a?.name;await this.getGlobalPropertyStateManager().setAspect(n,a.value)}for(const a of t.aspects){const n=a?.name,r=e.find(o=>o.getName()===n);if(r)switch(a.type){case z.FileUpload:{const o=r,s=await De([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case z.ColorOption:{const o=r,l=(await o.getAllVariants()).find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case z.Option:{const o=r,l=(await o.getAllVariants()).find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case z.Text:{await r.setText(a.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===z.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,n)=>a+n,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new rn(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(E.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const n of a){const r=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===n);if(r&&r.type===z.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=tr(this,n),d=[...new Set(s.map(A=>A.number))];if(d.length>c)for(const A of d){const h=this.getGlobalPropertyStateManager(),g=l.find(p=>p.channelNumber===A);g&&await h.setAspect(n,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getTransaction().id),a=e.map(s=>this.workflowExperiences.find(l=>l.getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getTransaction().id).join(", "));const n=Q.getMap("transactionOwnerIds")||new Map,r=e.map(s=>n.get(s));await y.getShadowGraphqlClient().mutate({mutation:Kl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:r},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),await this.initializeUninitializedHandles(),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getTransaction().id;if(this.workflowExperiences.find(s=>s.getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(Q.getMap("transactionOwnerIds")||new Map).get(a);await y.getShadowGraphqlClient().mutate({mutation:Jl,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const n=this.workflowExperiences.find(r=>r.getTransaction().id===e.id);if(n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await y.getShadowGraphqlClient().mutate({mutation:_l,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,o])=>({key:r,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const r=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:r})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(n=>this.workflowExperiences.findIndex(r=>r.getTransaction().id===n.id));if(e.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((n,r)=>e[r]===-1).map(n=>n.id).join(", "));const a=t.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(r=>r.getTransaction().id===n.id),1)[0]);a.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&a.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),t.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await y.getShadowGraphqlClient().mutate({mutation:Xl,variables:{id:this.id,transactionIds:t.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,r])=>({key:n,value:r})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(n=>n.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getTransaction().id===e.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(r=>r.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const a=await y.getShadowGraphqlClient().mutate({mutation:Zl,variables:{id:this.id,details:t,type:e||Va.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const n=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async removeStakeholder(t){if(!(await y.getShadowGraphqlClient().mutate({mutation:tc,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ec,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await y.getShadowGraphqlClient().query({query:Pn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await y.getShadowGraphqlClient().query({query:Pn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){this.completed&&await y.getShadowGraphqlClient().mutate({mutation:oc,variables:{bundleId:this.id}});const a=await Ki(this.workflowExperiences.map(n=>{const r=n.getWorkflow();if(!r)throw new Error("Unable to create designs - Workflow not found!");const o=n.getProduct();if(!o)throw new Error("Unable to create designs - Product not found!");return{workflowManager:n.getWorkflowManager(),workflow:r,layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:o,transaction:n.getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:r.name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()}}),e?(n,r)=>{const o=this.workflowExperiences.find(s=>s.getTransaction().id===r);return o?e(o,n):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+r),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getTransaction().id,amountToOrder:e.getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}async assignGlobalPropertyConfiguration(t){await y.getShadowGraphqlClient().mutate({mutation:ic,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await y.getShadowGraphqlClient().mutate({mutation:nc(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),await this.globalPropertyHandleService.getHandles(),this.globalConfigurationPropertyId=a?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const n=t.metadata.get("workflowManager").getWorkflowExperience().getTransaction(),r=this.workflowExperiences.find(o=>o.getTransaction().id===n.id);r&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:r})}}async injectExperienceIntoPreviewService(t){this.previewService&&await t.getWorkflowManager().injectIntoPreviewService(this.previewService)}async loadExistingWorkflowExperiences(t,e,a){if(t.length===0)return;const n=await this.client.getWorkflowExperiences(t.map(r=>({type:"transaction",transactionId:r})),e,void 0,a);if(n.forEach(r=>r.setBundle(this)),n.forEach(r=>r.checkForPriceBreakChanges()),this.workflowExperiences=n,this.previewService)for(const r of n)await this.injectExperienceIntoPreviewService(r);if(!this.globalPropertyStateManager.getBundleOptions()?.readonly){const r=this.getProductIds()||[],o=this.getProductCollection();if(o&&r.length>0){await o.fetchProducts();const s=o.getProducts(),l=[],c=[];for(const u of r)if(!s.find(h=>h.getId()===u)){for(const h of n)h.getProduct()?.id===u&&c.push(h);l.push(u)}const d=[];l.length>0&&d.push(this.removeProductIds(l)),c.length>0&&d.push(Promise.all(c.map(u=>u.clearProduct()))),d.length>0&&await Promise.all(d)}}}async updateBundle(){if(!(await y.getShadowGraphqlClient().mutate({mutation:Ee,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await y.getShadowGraphqlClient().mutate({mutation:ac,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const a=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(a,t),r=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(n,r),this.checkMandatoryHandlesChanged(t,r);const o=this.getGlobalPropertyStateManager();let s=[];for(const u of a)r.find(A=>A.getName()==u.getName())||(s=[...s,u.getName()]);await o.clearAspects(s);const l=r.map(u=>{if(u.getType()===z.ColorOption||u.getType()===z.Option){const A=u;if(!e.aspects.find(g=>g.name===A.getName()))return A.initDefaultVariant()}});await Promise.all(l),await Promise.all(r.map(u=>u.applyGlobalState()));const c=this.globalPropertyStateManager.getGlobalPropertyState(),d=this.globalPropertyHandleService.applyConditionsFromState(a,c);ae(r.sort(),d.sort())||(this.checkConditionalHandlesChanged(r,d),this.checkMandatoryHandlesChanged(c,d),await this.onGlobalPropertiesChanged(e,c))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let r=0;r<t.length;r++)if(t[r].getName()!==e[r].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],n=[],r=[],o=er(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?n.push(s):r.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:n,remaining:r})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await y.getShadowGraphqlClient().mutate({mutation:sc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await y.getShadowGraphqlClient().mutate({mutation:lc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const Yc=f.gql`
2356
+ `;class kn{constructor(t,e,a,n,r,o,s){this.workflowExperiences=[],this.eventEmitter=new Gc,this.updatesLocked=!1,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=r,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Uc(e.bundleStateData);const l=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=l?.id,this.globalPropertyStateManager=new $c(this.id,this.ownerId,l,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new Tc(this),this.setPreviewService(a),this.initializationPromise=(async()=>{if(!o?.readonly){const c=this.bundleStateManager.getState();if(c.integrationProductIds&&c.integrationProductIds.length>0){const d=await y.getShadowGraphqlClient().query({query:pi,variables:{ids:c.integrationProductIds},errorPolicy:"all",fetchPolicy:"no-cache"});if(d.errors)throw new Error(`Failed to fetch integration products for Bundle ${e.id}`);const u=d.data.integrationProducts?.filter(h=>!!h.product?.id&&c.integrationProductIds.includes(h.id)).map(h=>h.product.id);c.integrationProductIds=[],c.productIds=Array.from(new Set([...c.productIds||[],...u||[]]));const A=JSON.stringify(c);this.bundleStateManager.setState(A),await y.getShadowGraphqlClient().mutate({mutation:Ee,variables:{id:this.id,bundleStateData:A},context:{bundleOwnerId:r}})}}return Promise.all([this.loadExistingWorkflowExperiences(e.transactionIds||[],{...n,bundleOwnerId:r},s),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>new Promise((c,d)=>{if(o?.readonly){c([]);return}console.log("Setting default global variants."),this.initializeUninitializedHandles().then(c).catch(d)}))})(),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}async initializeUninitializedHandles(){const t=this.globalPropertyStateManager.getGlobalPropertyState();if(!t)return console.log("Attempted to set global default variant before state was initialized."),[];const a=(await this.globalPropertyHandleService.getHandles()).map(async n=>{if(n.getType()===z.ColorOption||n.getType()===z.Option){const r=n;if(!t.aspects.find(s=>s.name===r.getName()))try{return await r.initDefaultVariant()}catch(s){console.error(`Failed to initialize default global variant - ${s}`)}}});return Promise.all(a)}getProductIds(){return this.bundleStateManager.getState()?.productIds}async addProductId(t){const e=this.bundleStateManager.getState();if(e){if(!e.productIds)e.productIds=[];else if(e.productIds.some(n=>n===t)){this.fireEvent("bundle-products-added",{productIds:e.productIds,added:[]});return}e.productIds=[...e.productIds,t];const a=JSON.stringify(e);this.bundleStateManager.setState(a),this.fireEvent("bundle-products-added",{productIds:e.productIds,added:[t]}),await y.getShadowGraphqlClient().mutate({mutation:Ee,variables:{id:this.id,bundleStateData:a},context:{bundleOwnerId:this.ownerId}})}}async removeProductIds(t){const e=this.bundleStateManager.getState();if(e){const a=t.filter(r=>(e.productIds??[]).includes(r));if(a.length===0)return;e.productIds=(e.productIds??[]).filter(r=>!a.includes(r));const n=JSON.stringify(e);this.bundleStateManager.setState(n),this.fireEvent("bundle-products-removed",{productIds:e.productIds,removed:a}),await y.getShadowGraphqlClient().mutate({mutation:Ee,variables:{id:this.id,bundleStateData:n},context:{bundleOwnerId:this.ownerId}})}}getTemplate(){return this.template}async generateQuoteId(){const e=(await y.getShadowGraphqlClient().mutate({mutation:Wc,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,n,r,o){await y.getShadowGraphqlClient().mutate({mutation:jc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:r||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await y.getShadowGraphqlClient().mutate({mutation:Hc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){this.updatesLocked=!0;const e=await this.globalPropertyHandleService.getHandles();try{for(const a of t.aspects){const n=a?.name;await this.getGlobalPropertyStateManager().setAspect(n,a.value,void 0,void 0,a.hidden)}for(const a of t.aspects){const n=a?.name,r=e.find(o=>o.getName()===n);if(r)switch(a.type){case z.FileUpload:{const o=r,s=await De([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case z.ColorOption:{const o=r,l=(await o.getAllVariants()).find(d=>d.getId()===a.value),c=a.storage?a.storage:void 0;l&&await o.selectVariant(l),c?.customColor&&o.setCustomColor(c.customColor);break}case z.Option:{const o=r,l=(await o.getAllVariants()).find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case z.Text:{await r.setText(a.value);break}}}}finally{this.updatesLocked=!1,this.onGlobalPropertiesChanged(void 0,this.globalPropertyStateManager.getGlobalPropertyState())}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===z.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,n)=>a+n,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new rn(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(E.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const n of a){const r=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===n);if(r&&r.type===z.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=tr(this,n),d=[...new Set(s.map(A=>A.number))];if(d.length>c)for(const A of d){const h=this.getGlobalPropertyStateManager(),g=l.find(p=>p.channelNumber===A);g&&await h.setAspect(n,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getTransaction().id),a=e.map(s=>this.workflowExperiences.find(l=>l.getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getTransaction().id).join(", "));const n=Q.getMap("transactionOwnerIds")||new Map,r=e.map(s=>n.get(s));await y.getShadowGraphqlClient().mutate({mutation:Kl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:r},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),await this.initializeUninitializedHandles(),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getTransaction().id;if(this.workflowExperiences.find(s=>s.getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(Q.getMap("transactionOwnerIds")||new Map).get(a);await y.getShadowGraphqlClient().mutate({mutation:Jl,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const n=this.workflowExperiences.find(r=>r.getTransaction().id===e.id);if(n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await y.getShadowGraphqlClient().mutate({mutation:_l,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([r,o])=>({key:r,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const r=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:r})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(n=>this.workflowExperiences.findIndex(r=>r.getTransaction().id===n.id));if(e.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((n,r)=>e[r]===-1).map(n=>n.id).join(", "));const a=t.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(r=>r.getTransaction().id===n.id),1)[0]);a.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&a.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),t.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await y.getShadowGraphqlClient().mutate({mutation:Xl,variables:{id:this.id,transactionIds:t.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,r])=>({key:n,value:r})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(n=>n.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getTransaction().id===e.getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(r=>r.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const a=await y.getShadowGraphqlClient().mutate({mutation:Zl,variables:{id:this.id,details:t,type:e||Va.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const n=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async removeStakeholder(t){if(!(await y.getShadowGraphqlClient().mutate({mutation:tc,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ec,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await y.getShadowGraphqlClient().query({query:Pn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await y.getShadowGraphqlClient().query({query:Pn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){this.completed&&await y.getShadowGraphqlClient().mutate({mutation:oc,variables:{bundleId:this.id}});const a=await Ki(this.workflowExperiences.map(n=>{const r=n.getWorkflow();if(!r)throw new Error("Unable to create designs - Workflow not found!");const o=n.getProduct();if(!o)throw new Error("Unable to create designs - Product not found!");return{workflowManager:n.getWorkflowManager(),workflow:r,layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:o,transaction:n.getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:r.name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()}}),e?(n,r)=>{const o=this.workflowExperiences.find(s=>s.getTransaction().id===r);return o?e(o,n):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+r),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getTransaction().id,amountToOrder:e.getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}async assignGlobalPropertyConfiguration(t){await y.getShadowGraphqlClient().mutate({mutation:ic,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await y.getShadowGraphqlClient().mutate({mutation:nc(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),await this.globalPropertyHandleService.getHandles(),this.globalConfigurationPropertyId=a?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const n=t.metadata.get("workflowManager").getWorkflowExperience().getTransaction(),r=this.workflowExperiences.find(o=>o.getTransaction().id===n.id);r&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:r})}}async injectExperienceIntoPreviewService(t){this.previewService&&await t.getWorkflowManager().injectIntoPreviewService(this.previewService)}async loadExistingWorkflowExperiences(t,e,a){if(t.length===0)return;const n=await this.client.getWorkflowExperiences(t.map(r=>({type:"transaction",transactionId:r})),e,void 0,a);if(n.forEach(r=>r.setBundle(this)),n.forEach(r=>r.checkForPriceBreakChanges()),this.workflowExperiences=n,this.previewService)for(const r of n)await this.injectExperienceIntoPreviewService(r);if(!this.globalPropertyStateManager.getBundleOptions()?.readonly){const r=this.getProductIds()||[],o=this.getProductCollection();if(o&&r.length>0){await o.fetchProducts();const s=o.getProducts(),l=[],c=[];for(const u of r)if(!s.find(h=>h.getId()===u)){for(const h of n)h.getProduct()?.id===u&&c.push(h);l.push(u)}const d=[];l.length>0&&d.push(this.removeProductIds(l)),c.length>0&&d.push(Promise.all(c.map(u=>u.clearProduct()))),d.length>0&&await Promise.all(d)}}}async updateBundle(){if(!(await y.getShadowGraphqlClient().mutate({mutation:Ee,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await y.getShadowGraphqlClient().mutate({mutation:ac,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){if(this.updatesLocked)return;const a=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(a,t),r=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(n,r),this.checkMandatoryHandlesChanged(t,r);const o=this.getGlobalPropertyStateManager();let s=[];for(const u of a)r.find(A=>A.getName()==u.getName())||(s=[...s,u.getName()]);await o.clearAspects(s);const l=r.map(u=>{if(u.getType()===z.ColorOption||u.getType()===z.Option){const A=u;if(!e.aspects.find(g=>g.name===A.getName()))return A.initDefaultVariant()}});await Promise.all(l),await Promise.all(r.map(u=>u.applyGlobalState()));const c=this.globalPropertyStateManager.getGlobalPropertyState(),d=this.globalPropertyHandleService.applyConditionsFromState(a,c);ae(r.sort(),d.sort())||(this.checkConditionalHandlesChanged(r,d),this.checkMandatoryHandlesChanged(c,d),await this.onGlobalPropertiesChanged(e,c))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let r=0;r<t.length;r++)if(t[r].getName()!==e[r].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],n=[],r=[],o=er(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?n.push(s):r.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:n,remaining:r})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await y.getShadowGraphqlClient().mutate({mutation:sc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await y.getShadowGraphqlClient().mutate({mutation:lc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const Yc=f.gql`
2356
2357
  mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
2357
2358
  processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
2358
2359
  id
@@ -2481,7 +2482,7 @@
2481
2482
  }
2482
2483
  }
2483
2484
  }
2484
- `;class td{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 ed{init(t,e,a){this.cognitoClient=new we.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new we.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 we.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 we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new ed;class or{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return $r(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=An.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(An.code(e)?.code==="CLP")return"USD0,0"}}const Mn=new or;class sr{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,Mn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Mn.getPrecisionForCurrency(e))}}const ad=async(i,t)=>{const e=await y.getShadowGraphqlClient().query({query:is(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:i}});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!==i.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(n=>{n.finalizeStepConfig||(n.finalizeStepConfig={}),n.finalizeStepConfig.termsMarkdown=n.finalizeStepConfig.termsMarkdown||n.partner.termsMarkdown}),a},nd=async(i,t)=>{const a=(await t).find(n=>n.id===i);if(!a)throw new Error(`Workflow not found: ${i}`);return a},ln=async(i,t)=>{const e=i.map(s=>oe.get({id:s,options:t})),a=i.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=ad(a,t),r=a.map(s=>oe.set({id:s,options:t},nd(s,n))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},lr=async(i,t)=>(await ln([i],t))[0],id=async i=>{const t=await y.getShadowGraphqlClient().query({query:pi,variables:{ids:i},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class rd{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:qo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&no(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 40.0.1"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){gt.setHubUrl(t.hubUrl),gt.setServerUrl(t.serverUrl),gt.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&&ai(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return G}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!io())throw new Error("Application key required to use Flow Service.");return new nr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await y.getShadowGraphqlClient().query({query:ds,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new sr(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=cr(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}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Q.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),Q.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await y.getShadowGraphqlClient().query({query:Ie,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:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const s=(await e.mutate({mutation:_c,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 r=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:r}}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),r=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<r-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:Ie,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:Xc,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:Ie,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,r=!a?.AccessToken||Oe(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||r){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:Zc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await y.getShadowGraphqlClient().mutate({mutation:Wl(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(!r?.id)throw new Error("Unable to create bundle");const o=Q.getMap("bundlePartnerIds")||new Map;o.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",o);const s=Q.getMap("bundleOwnerIds")||new Map;s.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",s);const l=new kn(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n,r){const s=Q.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const m=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",C=localStorage.getItem(m);C&&!Oe(C)&&(l.Authorization=`Bearer ${C}`)}const c={bundleOwnerId:s,...l,...n?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:zl(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=Q.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),Q.setMap("bundlePartnerIds",A);const h=new kn(this,u,e,a,s,{additionalHeaders:n?.graphql?.additionalHeaders,eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:n?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,n){const o={...await ur(t),...n?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Yl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:rc(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:ql,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=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&n.set(r.bundle.id,r.bundle.partner.id)}),Q.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],r=n.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await n.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,n){if(t.length===0)throw new ft("No options provided!");const r=t.map((x,T)=>({option:x,index:T})),o=r.filter(x=>x.option.type==="transaction"),s=r.filter(x=>x.option.type==="integration"||x.option.type==="external"||x.option.type==="blank"),l=50,c=wa(o,l),d=wa(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:zo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,n&&n(u,o.length),k.length!==x.length){const X=L.errors?.[0]?.message||"Unknown error";throw new ft(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((X,It)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(mt=>mt.option.transactionId===X.id)?.option.readOnly??!1,index:x[It].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:Lo,variables:{inputs:x.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new ft(`Failed to create transactions: ${k}`)}return u=u+L.length,n&&n(u,o.length),L.map((k,X)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:x[X].index}))},p=(await Promise.all([...c.map(h),...d.map(g)])).flat(),m=[...new Set(p.map(x=>x.transaction.integrationProductId))].filter(x=>x!==void 0),C=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[S,w]=await Promise.all([(async()=>m.length>0?await id(m):[])(),(async()=>C.length>0?await ln(C,e):[])()]),F=new Map(S.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,It=L?b.get(L):void 0,mt=t[X];if(T.integrationProductId){const ot=F.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const fe=Q.getMap("transactionOwnerIds")||new Map;!fe.get(T.id)&&T.transactionOwnerId&&(fe.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",fe));const aa=fe.get(T.id)||void 0,Sr=new td({onMutate:()=>({context:{transactionOwnerId:aa,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:aa,bundleOwnerId:e?.bundleOwnerId}})}),Ce={workflow:It,transaction:T,singleVariantsRenderable:mt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:aa,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>Sr,readOnly:k,isReloadedTransaction:mt.type==="transaction"};if(mt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await Da(ot),Ce.reloadedState=ot}else if(!k&&mt.workflowState){const ot=JSON.parse(mt.workflowState);await Da(ot),Ce.reloadedState=ot}return Ce.delayWorkflowStateSync=!0,{experienceOptions:Ce,index:X,options:mt}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let R=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new _i(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await y.getShadowGraphqlClient().query({query:Ko(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new Oa(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:_o(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 Oa(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(Q.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await y.getShadowGraphqlClient().query({query:Yo,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:cs,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 cr=async(i,t)=>(await y.getShadowGraphqlClient().query({query:os,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":i},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,od=async i=>{const e=await y.getShadowGraphqlClient().query({query:Wo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:i}});if(e.data.transactions.length!==0)return e.data.transactions[0]},sd=async(i,t)=>(await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{themeConfigurationId:i,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,ld=async i=>(await y.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",variables:{id:i}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,cd=async i=>(await y.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",variables:{id:i}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function dr(){const i={};try{const t=await this.loggedInBearerToken();i.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,o])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",n=localStorage.getItem(a);n&&!Oe(n)&&(i.Authorization=`Bearer ${n}`)}return i}async function ur(i){const e=Q.getMap("bundleOwnerIds")?.get(i),a=await dr();return{bundleOwnerId:e,...a}}async function dd(i){const e=Q.getMap("transactionOwnerIds")?.get(i),a=await dr();return{transactionOwnerId:e,...a}}const ud=async i=>{const t=await ur(i),e=await y.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i},context:{headers:t}});if(e.data?.bundleDelete!==i)throw new Error(`Failed to delete bundle: ${e.errors}`)},Ad=async i=>{const t=await dd(i),e=await y.getShadowGraphqlClient().mutate({mutation:mc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[i]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==i)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function Ar(i,t,e,a){const n=e.width*i.zoom,r=e.height*i.zoom;if(a){const s=i,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,i.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Be(i.x,t.width-c,0),s.y=Be(i.y,t.height-d,0),s}const o=i;return o.x=Be(o.x,-n,t.width),o.y=Be(o.y,-r,t.height),o}function Be(i,t,e){return Math.min(Math.max(i,t),e)}class hr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Ln(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 r=!1;for(let o=0;o<n.currentFrameSources.length;o++){const s=n.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;ae(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[o]=l,r=!0)}r&&(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=Mt.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=He(this.imageData.svg,this.imageData.colors||{},!1);return Ge(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 r=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(r,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 O("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]=Ar(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,r){if(!a||a.length===0||a.some(l=>!l))throw new O("Frame data not set. This is a bug");if(!this.workflowManager)throw new O("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new U([new Ws(l,e,t[d]),new Ys(l,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),r&&r()}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 r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=r,this.maxZoomScale[n]=r*2.5):(this.minZoomScale[n]=r/10,this.maxZoomScale[n]=r*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]=Ha(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class hd{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,n,r,o,s,l,c,d,u,A,h,g,p,m,C){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Promise(()=>new Set)}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 gr=(i=>(i.SelectFrame="SelectFrame",i.SelectImage="SelectImage",i.Position="Position",i))(gr||{});class mr extends Z{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 pt.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 pt.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 canUseAdvancedImageManipulation(){return this.manager.getClient().canUseAddon(Ue.AdvancedImageManipulation)}async canRemoveBackground(){return await this.canUseAdvancedImageManipulation()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseAdvancedImageManipulation 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 G.removeBackgroundFromAsset(e);t&&await pt.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}async vectorize(t,e=void 0){const a=t??await this.getOriginalImageSelection();if(!a)throw new Error("You must supply an image selection before attempting to vectorize the image.");const n=await G.vectorizeAsset(a,e);await this.selectImage(n,t!==void 0);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,vectorizedAssetKey:n.key,useOriginalAsset:!1}}),n}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return G.getLocalOrFromServer(t)}async getVectorizedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.vectorizedAssetKey;if(t)return G.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}async changeColors(t){await pt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?pt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await rt(t.svg)).colors:void 0}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return pt.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 G.getLocalOrFromServer(t)}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)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const gd=f.gql`
2485
+ `;class td{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 ed{init(t,e,a){this.cognitoClient=new we.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new we.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 we.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 we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new ed;class or{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return $r(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=An.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(An.code(e)?.code==="CLP")return"USD0,0"}}const Mn=new or;class sr{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,Mn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,Mn.getPrecisionForCurrency(e))}}const ad=async(i,t)=>{const e=await y.getShadowGraphqlClient().query({query:is(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:i}});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!==i.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(n=>{n.finalizeStepConfig||(n.finalizeStepConfig={}),n.finalizeStepConfig.termsMarkdown=n.finalizeStepConfig.termsMarkdown||n.partner.termsMarkdown}),a},nd=async(i,t)=>{const a=(await t).find(n=>n.id===i);if(!a)throw new Error(`Workflow not found: ${i}`);return a},ln=async(i,t)=>{const e=i.map(s=>oe.get({id:s,options:t})),a=i.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=ad(a,t),r=a.map(s=>oe.set({id:s,options:t},nd(s,n))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},lr=async(i,t)=>(await ln([i],t))[0],id=async i=>{const t=await y.getShadowGraphqlClient().query({query:pi,variables:{ids:i},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class rd{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:qo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&no(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 40.1.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){gt.setHubUrl(t.hubUrl),gt.setServerUrl(t.serverUrl),gt.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&&ai(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return G}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!io())throw new Error("Application key required to use Flow Service.");return new nr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await y.getShadowGraphqlClient().query({query:ds,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new sr(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=cr(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}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Q.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),Q.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await y.getShadowGraphqlClient().query({query:Ie,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:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const s=(await e.mutate({mutation:_c,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 r=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:r}}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),r=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<r-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:Ie,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:Xc,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:Ie,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,r=!a?.AccessToken||Oe(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||r){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:Zc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await y.getShadowGraphqlClient().mutate({mutation:Wl(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(!r?.id)throw new Error("Unable to create bundle");const o=Q.getMap("bundlePartnerIds")||new Map;o.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",o);const s=Q.getMap("bundleOwnerIds")||new Map;s.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",s);const l=new kn(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n,r){const s=Q.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const m=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",C=localStorage.getItem(m);C&&!Oe(C)&&(l.Authorization=`Bearer ${C}`)}const c={bundleOwnerId:s,...l,...n?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:zl(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=Q.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),Q.setMap("bundlePartnerIds",A);const h=new kn(this,u,e,a,s,{additionalHeaders:n?.graphql?.additionalHeaders,eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:n?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,n){const o={...await ur(t),...n?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Yl(),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:rc(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:ql,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=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&n.set(r.bundle.id,r.bundle.partner.id)}),Q.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],r=n.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await n.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,n){if(t.length===0)throw new ft("No options provided!");const r=t.map((x,T)=>({option:x,index:T})),o=r.filter(x=>x.option.type==="transaction"),s=r.filter(x=>x.option.type==="integration"||x.option.type==="external"||x.option.type==="blank"),l=50,c=wa(o,l),d=wa(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:zo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,n&&n(u,o.length),k.length!==x.length){const X=L.errors?.[0]?.message||"Unknown error";throw new ft(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((X,It)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(mt=>mt.option.transactionId===X.id)?.option.readOnly??!1,index:x[It].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:Lo,variables:{inputs:x.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new ft(`Failed to create transactions: ${k}`)}return u=u+L.length,n&&n(u,o.length),L.map((k,X)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:x[X].index}))},p=(await Promise.all([...c.map(h),...d.map(g)])).flat(),m=[...new Set(p.map(x=>x.transaction.integrationProductId))].filter(x=>x!==void 0),C=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[S,w]=await Promise.all([(async()=>m.length>0?await id(m):[])(),(async()=>C.length>0?await ln(C,e):[])()]),F=new Map(S.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,It=L?b.get(L):void 0,mt=t[X];if(T.integrationProductId){const ot=F.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const fe=Q.getMap("transactionOwnerIds")||new Map;!fe.get(T.id)&&T.transactionOwnerId&&(fe.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",fe));const aa=fe.get(T.id)||void 0,Sr=new td({onMutate:()=>({context:{transactionOwnerId:aa,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:aa,bundleOwnerId:e?.bundleOwnerId}})}),Ce={workflow:It,transaction:T,singleVariantsRenderable:mt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:aa,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>Sr,readOnly:k,isReloadedTransaction:mt.type==="transaction"};if(mt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await Da(ot),Ce.reloadedState=ot}else if(!k&&mt.workflowState){const ot=JSON.parse(mt.workflowState);await Da(ot),Ce.reloadedState=ot}return Ce.delayWorkflowStateSync=!0,{experienceOptions:Ce,index:X,options:mt}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let R=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new _i(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await y.getShadowGraphqlClient().query({query:Ko(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new Oa(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:_o(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 Oa(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(Q.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await y.getShadowGraphqlClient().query({query:Yo,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:cs,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 cr=async(i,t)=>(await y.getShadowGraphqlClient().query({query:os,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":i},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,od=async i=>{const e=await y.getShadowGraphqlClient().query({query:Wo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:i}});if(e.data.transactions.length!==0)return e.data.transactions[0]},sd=async(i,t)=>(await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{themeConfigurationId:i,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,ld=async i=>(await y.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",variables:{id:i}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,cd=async i=>(await y.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",variables:{id:i}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function dr(){const i={};try{const t=await this.loggedInBearerToken();i.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,o])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",n=localStorage.getItem(a);n&&!Oe(n)&&(i.Authorization=`Bearer ${n}`)}return i}async function ur(i){const e=Q.getMap("bundleOwnerIds")?.get(i),a=await dr();return{bundleOwnerId:e,...a}}async function dd(i){const e=Q.getMap("transactionOwnerIds")?.get(i),a=await dr();return{transactionOwnerId:e,...a}}const ud=async i=>{const t=await ur(i),e=await y.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i},context:{headers:t}});if(e.data?.bundleDelete!==i)throw new Error(`Failed to delete bundle: ${e.errors}`)},Ad=async i=>{const t=await dd(i),e=await y.getShadowGraphqlClient().mutate({mutation:mc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[i]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==i)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function Ar(i,t,e,a){const n=e.width*i.zoom,r=e.height*i.zoom;if(a){const s=i,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,i.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Be(i.x,t.width-c,0),s.y=Be(i.y,t.height-d,0),s}const o=i;return o.x=Be(o.x,-n,t.width),o.y=Be(o.y,-r,t.height),o}function Be(i,t,e){return Math.min(Math.max(i,t),e)}class hr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Ln(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 r=!1;for(let o=0;o<n.currentFrameSources.length;o++){const s=n.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;ae(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[o]=l,r=!0)}r&&(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=Mt.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=He(this.imageData.svg,this.imageData.colors||{},!1);return Ge(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 r=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(r,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 O("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]=Ar(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,r){if(!a||a.length===0||a.some(l=>!l))throw new O("Frame data not set. This is a bug");if(!this.workflowManager)throw new O("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new U([new Ws(l,e,t[d]),new Ys(l,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),r&&r()}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 r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=r,this.maxZoomScale[n]=r*2.5):(this.minZoomScale[n]=r/10,this.maxZoomScale[n]=r*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]=Ha(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class hd{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,n,r,o,s,l,c,d,u,A,h,g,p,m,C){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Promise(()=>new Set)}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 gr=(i=>(i.SelectFrame="SelectFrame",i.SelectImage="SelectImage",i.Position="Position",i))(gr||{});class mr extends Z{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 pt.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 pt.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 canUseAdvancedImageManipulation(){return this.manager.getClient().canUseAddon(Ue.AdvancedImageManipulation)}async canRemoveBackground(){return await this.canUseAdvancedImageManipulation()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseAdvancedImageManipulation 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 G.removeBackgroundFromAsset(e);t&&await pt.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}async vectorize(t,e=void 0){const a=t??await this.getOriginalImageSelection();if(!a)throw new Error("You must supply an image selection before attempting to vectorize the image.");const n=await G.vectorizeAsset(a,e);await this.selectImage(n,t!==void 0);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,vectorizedAssetKey:n.key,useOriginalAsset:!1}}),n}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return G.getLocalOrFromServer(t)}async getVectorizedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.vectorizedAssetKey;if(t)return G.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}async changeColors(t){await pt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?pt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await rt(t.svg)).colors:void 0}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return pt.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 G.getLocalOrFromServer(t)}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)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const gd=f.gql`
2485
2486
  query GetLoggedInCustomer($email: String!) {
2486
2487
  customer(emailAddress: $email) {
2487
2488
  id