@spiffcommerce/core 32.3.1-beta.3b8ccab8-d0c2-53b3-8f6e-79134c2e5bf5 → 32.3.1-beta.3d2e1d40-d250-51a3-8708-179c106f4e1e
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
@@ -2423,7 +2423,7 @@
|
|
2423
2423
|
}
|
2424
2424
|
}
|
2425
2425
|
}
|
2426
|
-
`;var Tr=(n=>(n.QuantityChanged="QuantityChanged",n.PriceBreakChanged="PriceBreakChanged",n.SelectionChanged="SelectionChanged",n))(Tr||{});class Nr{constructor(t,e){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=Pn(async()=>{await Pe.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async r=>new Promise((i,o)=>{try{r.toBlob(s=>{if(s){const l=URL.createObjectURL(s);i(l)}})}catch(s){o(s)}}),this.client=t,this.transaction=e.transaction,this.workflow=e.workflow,this.product=e.transaction.product,this.profanityList=this.product?.profanities?.map(r=>r.word)||[];const a=e.layouts;this.commandContext=new sr,this.commandContext.initialize(a,e.reloadedState),this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new xl(this,t,a,this.commandContext,r=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(r)},e.graphQlClient,e.previewService,e.renderableContextService,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(r=>{const i=r.traversableScenes.map(o=>{const s=o.renderableSteps.map(l=>l.stepName);return{id:o.name,title:o.title,renderableSteps:s,workflowScene:o}});this.renderableScenes=i,this.renderableSceneCallbacks.forEach(o=>o(i)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.product}getProfanityList(){return this.profanityList}async setProduct(t){this.workflow=void 0,this.workflowManager.reset();const a=(await this.graphQlClient().mutate({mutation:Ul,variables:{id:this.getTransaction().id,integrationProductId:t}})).data?.transactionUpdateIntegrationProduct.product;if(!a)throw new Error("Failed to set product. No product returned from server.");const r=this.bundle?.getProductCollection()?.getProducts().find(i=>i.getCurrentIntegration()?.id===a.id);try{const i=r?.getDefaultWorkflow();if(i){const o=await Yr(i.getId());await this.setWorkflow(o)}}catch{}this.product=a,this.currentPriceBreak=this.priceBreakToBeApplied()}getWorkflow(){return this.workflow}async setWorkflow(t){this.workflowManager.reset(),this.workflow=t,await this.workflowManager.setWorkflow(t)}async attachAddress(t,e,a,r,i,o){await this.graphQlClient().mutate({mutation:Ol,variables:{transactionId:this.getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:$l,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.commandContext}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.getWorkflow(),r=a?.finalizeStepConfig?.lookAtAnimation;if(!a)throw new Error("Failed to generate cart preview image! No workflow is set.");if(t){if(!r)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,r)||""}let i=2048;e&&e<=2048&&(i=e);const o=ft(i,i),s=this.commandContext.getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=s.find(I=>I.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.commandContext.getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new $e("Failed to obtain 2D context for preview image creation");const m=this.workflowManager.getTemplatingContext(),p=je(A.layoutState.layout,A.layoutState.elements,{renderingConfiguration:{purpose:Nt.Print,region:{left:u.x,top:u.y,width:u.width,height:u.height},templatingContext:m}}),g=On(p);await(await ba.Pith.from(h,g,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:ft,createImage:le,DOMParser:xa(),fetch})).render();const w=await this.getCanvasObjectURLAsync(o);return o.toDataURL(w)}getStepById(t){const e=this.getWorkflow()?.steps.find(i=>i.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const r=ve.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,r),r}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>It(e.getRaw(),this.getWorkflowManager().getStepSelections())))}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(r=>{a+=r.selections.reduce((i,o)=>i+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,e);if(t){const r=this.getAdditionalProductPriceSubunits(e)||0;return a+r}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(),r=t*a;return Math.ceil(r)}priceBreakToBeApplied(){const t=(this.getProduct()?.priceBreaks||[]).sort((r,i)=>-(r.minQty-i.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((r,i)=>r+i.getQuantity(),0);for(const r of t)if(r.minQty<=a)return r.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,r=t.getProduct()?.id,i=this.getProduct()?.id;return e!==a&&r===i})}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const r=await t.getGlobalProperties(),i=a?.map(c=>c.getId()),o=this.getSteps().filter(c=>i===void 0||i.includes(c.getId())),s=e.getSteps(),l=c=>r.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(m=>{const p=l(m),g=d.has(JSON.stringify(m));if(g&&p?.getType()==="Option"){const f=A.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(m))}else if(g&&p?.getType()==="Text"){const f=A.getText();c.setText(f),d.delete(JSON.stringify(m))}})}))})}getStepByName(t){const e=this.getWorkflow()?.steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return ve.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflow()?.steps.filter(e=>e.type===t).map(e=>ve.get(this.getWorkflowManager(),e))||[]}getStepsByScene(t){if(!this.getWorkflow()?.stepGroups.find(a=>a.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(a=>this.getWorkflow()?.steps.find(r=>r.stepName===a)).filter(a=>this.stepHasHandle(a)).map(a=>ve.get(this.getWorkflowManager(),a))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:Rl,variables:{id:this.getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(r=>r.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const r=k.getMap("transactionCustomerIds")||new Map;r.set(this.getTransaction().id,a.customer.id),k.setMap("transactionCustomerIds",r)}}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(),r=this.getCommandContext().getState();if(!e)throw new T("Product undefined!");if(!a)throw new T("Workflow undefined!");if(!r)throw new T("State undefined!");const o={title:await(async()=>{if(t)return t;const s=this.getTransaction().id,c=(await Pe.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 Pe.addDesign(o),o}async copy(){const t=Bt(this.getCommandContext().getState());if(!t)throw new T("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflow();if(!a)throw new T("Workflow is undefined! Cannot copy experience!");const r=this.getTransaction().integrationProduct?.id;if(!r)throw new T("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:r,workflowId:a.id,workflowState:e})}async onDesignFinished(t,e=!0){const a=this.getTransaction(),r=this.getProduct(),i=this.getWorkflow();if(!r)throw new T("Product undefined! Cannot finish an experience without a product.");if(!i)throw new T("Workflow undefined! Cannot finish an experience without a workflow.");return a.completed?(await this.graphQlClient().mutate({mutation:bo,variables:{transactionId:a.id}}),{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:a.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""}):Mr(this.workflowManager,i,this.workflowManager.getLayouts(),()=>this.commandContext.getState(),r,a,this.workflowManager.getWorkflowSelections(),i.name,t||(()=>{}),o=>e?this.createPreviewImage(o,1024):Promise.resolve(void 0),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==E.SilentIllustration&&t.type!==E.ProductOverlay}getExportedStepData(){const t=this.getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),r=[];return t?.steps.forEach(i=>{const o=i.stepName,s=e[o],l=a[o]?.selections[0],c={stepId:o,title:i.stepTitle,properties:[]};if(l&&Vl(i,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){r.push(c);return}switch(i.type){case E.Frame:{const d=i.data,u=s;u.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case E.Illustration:{const d=i.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=i.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case E.Text:{const d=i.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})}}r.push(c)}),r.filter(i=>i.properties&&i.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:fo,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(r=>r!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const Ll=n=>{if([E.Question,E.Frame,E.Illustration,E.Material,E.Model,E.Picture,E.Shape,E.Text].includes(n.type)){const e=n.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Vl=(n,t)=>{if(!Ll(n))return!1;if(n.option&&(n.option.variants||[]).length>1){const e=t[n.stepName];return!!(e&&e.selections.length>0)}return!1},zl=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],ql=async(n,t,e)=>{const a=t.data,r=e.data.baseUrl,i=a.assetUrl.replace("localhost","localstack"),o=r.slice(0,4)==="http"?"":"https://",s=new URL(o+r);s.searchParams.append("video",nn(JSON.stringify([{href:i}]))),s.pathname=s.pathname+(s.pathname.slice(-1)==="/"?"":"/");const l=s.toString(),d=`data:image/svg+xml;base64,${nn(await Bn.toString(l,{type:"svg"}))}`,u=h=>{const m=n.find(g=>g.panelId===h.panelId);if(!m)throw new H(h);const p=M();return new z({id:p,src:d,type:F.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},m)},A=e.data.regions;try{return A.map(u)}catch(h){return console.error(h),[]}},Gl=async(n,t,e,a)=>{const r=e.data,i=r.assetUrl,o=await pa(i);try{const s=ps(r,a.option);s&&(t[a.stepName]={selectedVariants:[s]});const l=async c=>{const d=await cr(c,s?.asset?.fileLink),u=await me(d),A=M(),h=n.find(p=>p.panelId===c.panelId);if(!h)throw new H(c);const m=Na(o,u,{scale:r.scale,left:r.x,top:r.y},a.data.forceImageCover);return[new z({id:A,path:u.path,type:F.Frame,forceImageCover:a.data.forceImageCover,x:c.left,y:c.top,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,rotation:c.rotation,scaleX:c.width/u.width,scaleY:c.height/u.height,pattern:{id:`${A}-pattern`,src:o.src,x:m.x,y:m.y,width:o.width,height:o.height,rotation:0,scaleX:m.zoom,scaleY:m.zoom,svg:o.svg,colors:o.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(s){return console.error(s),[]}},jl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(y=>y.id===r.illustrationVariantId)||he(i);if(!o)return console.error(`No variant with ID: ${r.illustrationVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${r.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${r.illustrationVariantId}`),[];const l=await tt(s,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],u=d?.length>0?d[0]:"",m=lt().parseFromString(u,"image/svg+xml").firstElementChild;if(!m)return console.error("Failed to read SVG."),[];ze(m);const p={};Ot(m,y=>{zl.includes(y.tagName)&&!y.attributes.getNamedItem("fill")&&y.setAttribute("fill","#000000");const S=y.attributes.getNamedItem("fill");if(S&&S.value!=="none"){const b=S.value,$=`spiff-fill-${b.replace(/\W/g,"")}`;y.classList.add($),p[$]={browserValue:b}}const P=y.attributes.getNamedItem("stroke");if(P&&P.value!=="none"){const b=P.value,$=`spiff-stroke-${b.replace(/\W/g,"")}`;y.classList.add($),p[$]={browserValue:b}}});const f=St().serializeToString(m),w=r.colors;if(w){for(const[y,S]of Object.entries(p))for(const P of Object.keys(w))if(S.browserValue===P){p[y]={browserValue:w[P]};break}}const I=y=>{const S=n.find(b=>b.panelId===y.panelId);if(!S)throw new H(y);const P=M();return new z({colors:p,id:P,svg:f,type:F.Illustration,y:y.top,x:y.left,rotation:y.rotation,width:y.width,height:y.height,layer:y.layer,layerIndex:y.layerIndex,immutable:y.immutable},S)},x=a.data.regions;try{return x.map(I)}catch(y){return console.error(y),[]}},Wl=async(n,t,e)=>{const a=await Cr(e.data.module),r=t.data,i=(s,l)=>{const c=n.find(u=>u.panelId===l.panelId);if(!c)throw new H(l);const d=M();return new z({colors:{},id:d,svg:s,type:F.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},o=e.data.regions;try{return o.map(s=>i(a.svgPrint(r.text,s),s))}catch(s){return console.error(s),[]}},Hl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(d=>d.id===r.pictureVariantId)||he(i);if(!o)return console.error(`No variant with ID: ${r.pictureVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${r.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${r.pictureVariantId}`),[];const l=d=>{const u=n.find(h=>h.panelId===d.panelId);if(!u)throw new H(d);const A=M();return new z({id:A,src:s,type:F.Image,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable,preserveAspectRatio:"none"},u)},c=a.data.regions;try{return c.map(l)}catch(d){return console.error(d),[]}},Yl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(c=>c.id===r.colorVariantId)||he(i);if(!o)return console.error(`No variant with ID: ${r.colorVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=c=>{const d=n.find(p=>p.panelId===c.panelId);if(!d)throw new H(c);const u=`
|
2426
|
+
`;var Tr=(n=>(n.QuantityChanged="QuantityChanged",n.PriceBreakChanged="PriceBreakChanged",n.SelectionChanged="SelectionChanged",n))(Tr||{});class Nr{constructor(t,e){this.cachedStepHandles=new Map,this.profanityList=[],this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=Pn(async()=>{await Pe.getSavedDesignByTransaction(this.getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async r=>new Promise((i,o)=>{try{r.toBlob(s=>{if(s){const l=URL.createObjectURL(s);i(l)}})}catch(s){o(s)}}),this.client=t,this.transaction=e.transaction,this.workflow=e.workflow,this.product=e.transaction.product,this.profanityList=this.product?.profanities?.map(r=>r.word)||[];const a=e.layouts;this.commandContext=new sr,this.commandContext.initialize(a,e.reloadedState),this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new xl(this,t,a,this.commandContext,r=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(r)},e.graphQlClient,e.previewService,e.renderableContextService,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(r=>{const i=r.traversableScenes.map(o=>{const s=o.renderableSteps.map(l=>l.stepName);return{id:o.name,title:o.title,renderableSteps:s,workflowScene:o}});this.renderableScenes=i,this.renderableSceneCallbacks.forEach(o=>o(i)),this.callEvent("SelectionChanged")}),this.currentPriceBreak=this.priceBreakToBeApplied()}getTransaction(){return this.transaction}getProduct(){return this.product}getProfanityList(){return this.profanityList}async setProduct(t){this.workflow=void 0,this.workflowManager.reset();const a=(await this.graphQlClient().mutate({mutation:Ul,variables:{id:this.getTransaction().id,integrationProductId:t}})).data?.transactionUpdateIntegrationProduct.product;if(!a)throw new Error("Failed to set product. No product returned from server.");const r=this.bundle?.getProductCollection()?.getProducts().find(i=>i.getCurrentIntegration()?.id===a.id);try{const i=r?.getDefaultWorkflow();if(i){const o=await Yr(i.getId());await this.setWorkflow(o)}}catch{}this.product=a,this.transaction.product=a,this.currentPriceBreak=this.priceBreakToBeApplied()}getWorkflow(){return this.workflow}async setWorkflow(t){this.workflowManager.reset(),this.workflow=t,await this.workflowManager.setWorkflow(t)}async attachAddress(t,e,a,r,i,o){await this.graphQlClient().mutate({mutation:Ol,variables:{transactionId:this.getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:r||void 0,state:i||void 0,postCode:o||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:$l,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.commandContext}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){const a=this.getWorkflow(),r=a?.finalizeStepConfig?.lookAtAnimation;if(!a)throw new Error("Failed to generate cart preview image! No workflow is set.");if(t){if(!r)throw new Error("Failed to generate cart preview image! No camera orientation configured.");return await this.workflowManager.getPreviewService()?.renderSceneScreenshot(e??512,r)||""}let i=2048;e&&e<=2048&&(i=e);const o=ft(i,i),s=this.commandContext.getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=s.find(I=>I.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.commandContext.getLayoutById(d.layoutState.layout.id),h=o.getContext("2d");if(!h)throw new $e("Failed to obtain 2D context for preview image creation");const m=this.workflowManager.getTemplatingContext(),p=je(A.layoutState.layout,A.layoutState.elements,{renderingConfiguration:{purpose:Nt.Print,region:{left:u.x,top:u.y,width:u.width,height:u.height},templatingContext:m}}),g=On(p);await(await ba.Pith.from(h,g,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:ft,createImage:le,DOMParser:xa(),fetch})).render();const w=await this.getCanvasObjectURLAsync(o);return o.toDataURL(w)}getStepById(t){const e=this.getWorkflow()?.steps.find(i=>i.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const r=ve.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,r),r}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>It(e.getRaw(),this.getWorkflowManager().getStepSelections())))}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(r=>{a+=r.selections.reduce((i,o)=>i+(o.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getProduct()?.basePrice||0,e);if(t){const r=this.getAdditionalProductPriceSubunits(e)||0;return a+r}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(),r=t*a;return Math.ceil(r)}priceBreakToBeApplied(){const t=(this.getProduct()?.priceBreaks||[]).sort((r,i)=>-(r.minQty-i.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((r,i)=>r+i.getQuantity(),0);for(const r of t)if(r.minQty<=a)return r.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,r=t.getProduct()?.id,i=this.getProduct()?.id;return e!==a&&r===i})}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const r=await t.getGlobalProperties(),i=a?.map(c=>c.getId()),o=this.getSteps().filter(c=>i===void 0||i.includes(c.getId())),s=e.getSteps(),l=c=>r.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(m=>{const p=l(m),g=d.has(JSON.stringify(m));if(g&&p?.getType()==="Option"){const f=A.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(m))}else if(g&&p?.getType()==="Text"){const f=A.getText();c.setText(f),d.delete(JSON.stringify(m))}})}))})}getStepByName(t){const e=this.getWorkflow()?.steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return ve.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflow()?.steps.filter(e=>e.type===t).map(e=>ve.get(this.getWorkflowManager(),e))||[]}getStepsByScene(t){if(!this.getWorkflow()?.stepGroups.find(a=>a.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(a=>this.getWorkflow()?.steps.find(r=>r.stepName===a)).filter(a=>this.stepHasHandle(a)).map(a=>ve.get(this.getWorkflowManager(),a))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){const a=(await this.graphQlClient().mutate({mutation:Rl,variables:{id:this.getTransaction().id,details:t,type:"Owner"}})).data?.transactionAddStakeholder?.stakeholders?.find(r=>r.customer?.emailAddress===t.emailAddress);if(a?.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const r=k.getMap("transactionCustomerIds")||new Map;r.set(this.getTransaction().id,a.customer.id),k.setMap("transactionCustomerIds",r)}}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(),r=this.getCommandContext().getState();if(!e)throw new T("Product undefined!");if(!a)throw new T("Workflow undefined!");if(!r)throw new T("State undefined!");const o={title:await(async()=>{if(t)return t;const s=this.getTransaction().id,c=(await Pe.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 Pe.addDesign(o),o}async copy(){const t=Bt(this.getCommandContext().getState());if(!t)throw new T("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflow();if(!a)throw new T("Workflow is undefined! Cannot copy experience!");const r=this.getTransaction().integrationProduct?.id;if(!r)throw new T("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:r,workflowId:a.id,workflowState:e})}async onDesignFinished(t,e=!0){const a=this.getTransaction(),r=this.getProduct(),i=this.getWorkflow();if(!r)throw new T("Product undefined! Cannot finish an experience without a product.");if(!i)throw new T("Workflow undefined! Cannot finish an experience without a workflow.");return a.completed?(await this.graphQlClient().mutate({mutation:bo,variables:{transactionId:a.id}}),{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:a.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""}):Mr(this.workflowManager,i,this.workflowManager.getLayouts(),()=>this.commandContext.getState(),r,a,this.workflowManager.getWorkflowSelections(),i.name,t||(()=>{}),o=>e?this.createPreviewImage(o,1024):Promise.resolve(void 0),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==E.SilentIllustration&&t.type!==E.ProductOverlay}getExportedStepData(){const t=this.getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),r=[];return t?.steps.forEach(i=>{const o=i.stepName,s=e[o],l=a[o]?.selections[0],c={stepId:o,title:i.stepTitle,properties:[]};if(l&&Vl(i,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!s){r.push(c);return}switch(i.type){case E.Frame:{const d=i.data,u=s;u.image&&d.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case E.Illustration:{const d=i.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=i.data,u=s;u&&u.text&&d.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case E.Text:{const d=i.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})}}r.push(c)}),r.filter(i=>i.properties&&i.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:fo,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(r=>r!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const Ll=n=>{if([E.Question,E.Frame,E.Illustration,E.Material,E.Model,E.Picture,E.Shape,E.Text].includes(n.type)){const e=n.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Vl=(n,t)=>{if(!Ll(n))return!1;if(n.option&&(n.option.variants||[]).length>1){const e=t[n.stepName];return!!(e&&e.selections.length>0)}return!1},zl=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],ql=async(n,t,e)=>{const a=t.data,r=e.data.baseUrl,i=a.assetUrl.replace("localhost","localstack"),o=r.slice(0,4)==="http"?"":"https://",s=new URL(o+r);s.searchParams.append("video",nn(JSON.stringify([{href:i}]))),s.pathname=s.pathname+(s.pathname.slice(-1)==="/"?"":"/");const l=s.toString(),d=`data:image/svg+xml;base64,${nn(await Bn.toString(l,{type:"svg"}))}`,u=h=>{const m=n.find(g=>g.panelId===h.panelId);if(!m)throw new H(h);const p=M();return new z({id:p,src:d,type:F.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},m)},A=e.data.regions;try{return A.map(u)}catch(h){return console.error(h),[]}},Gl=async(n,t,e,a)=>{const r=e.data,i=r.assetUrl,o=await pa(i);try{const s=ps(r,a.option);s&&(t[a.stepName]={selectedVariants:[s]});const l=async c=>{const d=await cr(c,s?.asset?.fileLink),u=await me(d),A=M(),h=n.find(p=>p.panelId===c.panelId);if(!h)throw new H(c);const m=Na(o,u,{scale:r.scale,left:r.x,top:r.y},a.data.forceImageCover);return[new z({id:A,path:u.path,type:F.Frame,forceImageCover:a.data.forceImageCover,x:c.left,y:c.top,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,rotation:c.rotation,scaleX:c.width/u.width,scaleY:c.height/u.height,pattern:{id:`${A}-pattern`,src:o.src,x:m.x,y:m.y,width:o.width,height:o.height,rotation:0,scaleX:m.zoom,scaleY:m.zoom,svg:o.svg,colors:o.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(s){return console.error(s),[]}},jl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(y=>y.id===r.illustrationVariantId)||he(i);if(!o)return console.error(`No variant with ID: ${r.illustrationVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${r.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${r.illustrationVariantId}`),[];const l=await tt(s,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],u=d?.length>0?d[0]:"",m=lt().parseFromString(u,"image/svg+xml").firstElementChild;if(!m)return console.error("Failed to read SVG."),[];ze(m);const p={};Ot(m,y=>{zl.includes(y.tagName)&&!y.attributes.getNamedItem("fill")&&y.setAttribute("fill","#000000");const S=y.attributes.getNamedItem("fill");if(S&&S.value!=="none"){const b=S.value,$=`spiff-fill-${b.replace(/\W/g,"")}`;y.classList.add($),p[$]={browserValue:b}}const P=y.attributes.getNamedItem("stroke");if(P&&P.value!=="none"){const b=P.value,$=`spiff-stroke-${b.replace(/\W/g,"")}`;y.classList.add($),p[$]={browserValue:b}}});const f=St().serializeToString(m),w=r.colors;if(w){for(const[y,S]of Object.entries(p))for(const P of Object.keys(w))if(S.browserValue===P){p[y]={browserValue:w[P]};break}}const I=y=>{const S=n.find(b=>b.panelId===y.panelId);if(!S)throw new H(y);const P=M();return new z({colors:p,id:P,svg:f,type:F.Illustration,y:y.top,x:y.left,rotation:y.rotation,width:y.width,height:y.height,layer:y.layer,layerIndex:y.layerIndex,immutable:y.immutable},S)},x=a.data.regions;try{return x.map(I)}catch(y){return console.error(y),[]}},Wl=async(n,t,e)=>{const a=await Cr(e.data.module),r=t.data,i=(s,l)=>{const c=n.find(u=>u.panelId===l.panelId);if(!c)throw new H(l);const d=M();return new z({colors:{},id:d,svg:s,type:F.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},o=e.data.regions;try{return o.map(s=>i(a.svgPrint(r.text,s),s))}catch(s){return console.error(s),[]}},Hl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(d=>d.id===r.pictureVariantId)||he(i);if(!o)return console.error(`No variant with ID: ${r.pictureVariantId}`),[];if(!o.asset)return console.error(`No asset for variant with ID: ${r.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=o.asset?.fileLink;if(!s)return console.error(`No asset link for variant with ID: ${r.pictureVariantId}`),[];const l=d=>{const u=n.find(h=>h.panelId===d.panelId);if(!u)throw new H(d);const A=M();return new z({id:A,src:s,type:F.Image,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable,preserveAspectRatio:"none"},u)},c=a.data.regions;try{return c.map(l)}catch(d){return console.error(d),[]}},Yl=async(n,t,e,a)=>{const r=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const o=i.variants?.find(c=>c.id===r.colorVariantId)||he(i);if(!o)return console.error(`No variant with ID: ${r.colorVariantId}`),[];t[a.stepName]={selectedVariants:[o]};const s=c=>{const d=n.find(p=>p.panelId===c.panelId);if(!d)throw new H(c);const u=`
|
2427
2427
|
<svg
|
2428
2428
|
xmlns="http://www.w3.org/2000/svg"
|
2429
2429
|
xmlnsXlink="http://www.w3.org/1999/xlink"
|
@@ -2626,7 +2626,7 @@
|
|
2626
2626
|
}
|
2627
2627
|
}
|
2628
2628
|
}
|
2629
|
-
`;class Bc{constructor(t,e=v.getShadowGraphqlClient.bind(v)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Pc{init(t,e,a){this.cognitoClient=new Ce.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new Ce.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new Ce.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new Ce.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Pc;class Wr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return mi(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Za.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Za.code(e)?.code==="CLP")return"USD0,0"}}const fn=new Wr;class Hr{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,fn.getPrecisionForCurrency(e))}}const xc=async(n,t)=>{const e=await v.getShadowGraphqlClient().query({query:Do(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&O.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&O.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&O.cacheAsset(o.asset),o.thumbnail&&O.cacheAsset(o.thumbnail),o.material&&O.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},Dc=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},Ja=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=xc(a,t),i=a.map(s=>$t.set({id:s,options:t},Dc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},Yr=async(n,t)=>(await Ja([n],t))[0],Fc=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:M(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),kc=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(r=>r.layout):Fc(t.panels)};class Mc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return v.getShadowGraphqlClient().mutate({...e,mutation:po})}catch(a){throw console.error(a),new mt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Mi(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 32.3.1-beta.cb99cb5d-bbe6-57e1-9338-6d75af0a506b"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ut.setHubUrl(t.hubUrl),ut.setServerUrl(t.serverUrl),ut.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Ln(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return O}getFlowService(){if(!Ti())throw new Error("Application key required to use Flow Service.");return new qr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await v.getShadowGraphqlClient().query({query:Oo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new Hr(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=Jr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}async authenticateBundleFromLocalStorage(t){if(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=v.getShadowGraphqlClient(),a=await e.query({query:Fo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const A=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(m=>m.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(A)return Promise.resolve({success:!0,stakeholderType:A.type})}const c=(await e.query({query:ko,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await v.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=v.getShadowGraphqlClient(),r=(await e.query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:Ec,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await v.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await v.getShadowGraphqlClient().mutate({mutation:bc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await jt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await v.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),r=new Date().getTime()/1e3,i=!a?.AccessToken||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await v.getShadowGraphqlClient().query({query:Ic,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await v.getShadowGraphqlClient().mutate({mutation:il(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!i?.id)throw new Error("Unable to create bundle");const o=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new ra(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const p=Object.entries(localStorage).find(([f,w])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",g=localStorage.getItem(p);g&&!_t(g)&&(s.Authorization=`Bearer ${g}`)}const l={bundleOwnerId:o,...s,...r?.graphql?.additionalHeaders},c=await v.getShadowGraphqlClient().query({query:tl(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],u=k.getMap("bundlePartnerIds")||new Map;u.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",u);const A=new ra(this,d,e,a,o,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:r?.readonly});return await A.getInitializationPromise(),A}async duplicateBundle(t,e,a,r){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const A=await this.loggedInBearerToken();o.Authorization=`Bearer ${A}`}catch{const m=Object.entries(localStorage).find(([g,f])=>g.startsWith("CognitoIdentityServiceProvider")&&g.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(m);p&&!_t(p)&&(o.Authorization=`Bearer ${p}`)}const s={bundleOwnerId:i,...o,...r?.graphql?.additionalHeaders},c=(await v.getShadowGraphqlClient().mutate({mutation:ol(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const u=k.getMap("bundleOwnerIds")||new Map;return u.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",u),async()=>{const A=new ra(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await A.getInitializationPromise(),A}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await v.getShadowGraphqlClient().query({query:fl(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await v.getShadowGraphqlClient().query({query:el,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],r=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",r),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),r=a[0],i=r.getWorkflow();return e&&!i&&console.error("No workflow instantiated when trying to create preview service."),e&&i&&await r.getWorkflowManager().injectIntoPreviewService(e(i)),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new mt("No options provided!");const a=v.getShadowGraphqlClient(),r=async y=>{if(y.length===0)return[];const S=y.map(D=>D.option.transactionId),P=await a.query({query:go,variables:{ids:S},errorPolicy:"all",fetchPolicy:"no-cache"}),b=P.data.transactions;if(b.length!==y.length){const D=P.errors?.[0]?.message||"Unknown error";throw new mt(`Not all transactions were found: ${D}`)}return!this.activeIntegration&&b[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(b[0].integrationProduct.integration)),b.map((D,$)=>({transaction:D,workflowId:D.workflowId,readOnly:y.find(N=>N.option.transactionId===D.id)?.option.readOnly??!1,index:y[$].index}))},i=async y=>{if(y.length===0)return[];const S=await a.mutate({mutation:mo,variables:{inputs:y.map(b=>({integrationProductId:b.option.type==="integration"?b.option.integrationProductId:void 0,externalIntegrationId:b.option.type==="external"?b.option.externalIntegrationId:void 0,externalProductId:b.option.type==="external"?b.option.externalProductId:void 0,workflowId:b.option.workflowId,designName:b.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),P=S.data?.transactionCreateMany;if(!P||P.length===0){const b=S.errors?.[0]?.message||"Unknown error";throw new mt(`Failed to create transactions: ${b}`)}return P.map((b,D)=>({transaction:b,workflowId:b.workflowId,readOnly:!1,index:y[D].index}))},o=t.map((y,S)=>({option:y,index:S})),s=o.filter(y=>y.option.type==="transaction"),l=o.filter(y=>y.option.type==="integration"||y.option.type==="external"||y.option.type==="blank"),c=Xa(s,10),d=Xa(l,10),u=(await Promise.all([...c.map(r),...d.map(i)])).flat(),A=[...new Set(u.map(y=>y.workflowId))].filter(y=>y!==void 0),h=A.length>0?await Ja(A,e):[],m=new Map(h.map(y=>[y.id,y])),p=k.getMap("transactionOwnerIds")||new Map,g=u.map(async y=>{const{transaction:S,workflowId:P,readOnly:b,index:D}=y,$=P?m.get(P):void 0,N=t[D];!p.get(S.id)&&S.transactionOwnerId&&p.set(S.id,S.transactionOwnerId);const et=p.get(S.id)||void 0,at=new Bc({onMutate:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}})}),q={workflow:$,transaction:S,layouts:[],singleVariantsRenderable:N?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:b?async()=>{throw new T("State mutation is forbidden in read only mode!")}:async Y=>this.updateTransactionState({...Y,context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>at,readOnly:b,isReloadedTransaction:N.type==="transaction"};if(N.type==="transaction"&&S.workflowState){const Y=JSON.parse(S.workflowState);q.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),q.reloadedState=Y}else if(!b&&N.workflowState){const Y=JSON.parse(N.workflowState);q.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),q.reloadedState=Y}else q.workflow?q.layouts=kc(q.transaction,q.workflow):q.layouts=[];return q.renderableContextService=new Xl(q.layouts),q.delayWorkflowStateSync=!0,{experienceOptions:q,index:D,options:N}}),f=await Promise.all(g);k.setMap("transactionOwnerIds",p);const I=f.sort((y,S)=>y.index-S.index).map(async y=>{const{experienceOptions:S,options:P}=y,b=new Nr(this,S);return await b.getWorkflowManager().getInitializationPromise(),P.type!=="transaction"&&this.customer&&await b.attachCustomerDetails({email:this.customer.emailAddress}),b}),x=await Promise.all(I);return x.forEach(y=>y.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),x}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await v.getShadowGraphqlClient().query({query:So(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new va(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await v.getShadowGraphqlClient().query({query:vo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new va(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await v.getShadowGraphqlClient().query({query:yo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await v.getShadowGraphqlClient().mutate({mutation:Ro,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 Jr=async(n,t)=>(await v.getShadowGraphqlClient().query({query:To,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,Tc=async n=>{const e=await v.getShadowGraphqlClient().query({query:wo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Nc=async(n,t)=>(await v.getShadowGraphqlClient().query({query:Mo,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,Qc=async n=>(await v.getShadowGraphqlClient().query({query:Qo,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Rc=async n=>(await v.getShadowGraphqlClient().query({query:No,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,Oc=async n=>{const t=await v.getShadowGraphqlClient().mutate({mutation:Bl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n}});if(t.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${t.errors}`)};function Kr(n,t,e,a){const r=e.width*n.zoom,i=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Ie(n.x,t.width-c,0),s.y=Ie(n.y,t.height-d,0),s}const o=n;return o.x=Ie(o.x,-r,t.width),o.y=Ie(o.y,-i,t.height),o}function Ie(n,t,e){return Math.min(Math.max(n,t),e)}class _r{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Pn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;De(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const r=Ft.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=qe(this.imageData.svg,this.imageData.colors||{},!1);return Ve(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new T("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=Kr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,r,i){if(!a||a.length===0||a.some(s=>!s))throw new T("Frame data not set. This is a bug");if(!this.workflowManager)throw new T("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new R([new Ss(s,e,t[l]),new vs(s,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,r)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Na(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class $c{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,m,p,g,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Xr=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Xr||{});class Zr extends X{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new _r(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await ht.selectImage(this.step,t,this.manager,a),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Re.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await O.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,r){return r&&r.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return O.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return O.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Uc=C.gql`
|
2629
|
+
`;class Bc{constructor(t,e=v.getShadowGraphqlClient.bind(v)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Pc{init(t,e,a){this.cognitoClient=new Ce.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new Ce.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new Ce.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new Ce.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Pc;class Wr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return mi(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Za.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Za.code(e)?.code==="CLP")return"USD0,0"}}const fn=new Wr;class Hr{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,fn.getPrecisionForCurrency(e))}}const xc=async(n,t)=>{const e=await v.getShadowGraphqlClient().query({query:Do(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&O.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&O.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&O.cacheAsset(o.asset),o.thumbnail&&O.cacheAsset(o.thumbnail),o.material&&O.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},Dc=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},Ja=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=xc(a,t),i=a.map(s=>$t.set({id:s,options:t},Dc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},Yr=async(n,t)=>(await Ja([n],t))[0],Fc=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:M(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),kc=(n,t)=>{const e=n.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(r=>r.layout):Fc(t.panels)};class Mc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return v.getShadowGraphqlClient().mutate({...e,mutation:po})}catch(a){throw console.error(a),new mt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Mi(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 32.3.1-beta.3b8ccab8-d0c2-53b3-8f6e-79134c2e5bf5"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ut.setHubUrl(t.hubUrl),ut.setServerUrl(t.serverUrl),ut.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Ln(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return O}getFlowService(){if(!Ti())throw new Error("Application key required to use Flow Service.");return new qr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await v.getShadowGraphqlClient().query({query:Oo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new Hr(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=Jr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}async authenticateBundleFromLocalStorage(t){if(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=v.getShadowGraphqlClient(),a=await e.query({query:Fo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const A=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(m=>m.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(A)return Promise.resolve({success:!0,stakeholderType:A.type})}const c=(await e.query({query:ko,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await v.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=v.getShadowGraphqlClient(),r=(await e.query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:Ec,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await v.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await v.getShadowGraphqlClient().mutate({mutation:bc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await jt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await v.getShadowGraphqlClient().query({query:be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),r=new Date().getTime()/1e3,i=!a?.AccessToken||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await v.getShadowGraphqlClient().query({query:Ic,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await v.getShadowGraphqlClient().mutate({mutation:il(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!i?.id)throw new Error("Unable to create bundle");const o=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new ra(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const p=Object.entries(localStorage).find(([f,w])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",g=localStorage.getItem(p);g&&!_t(g)&&(s.Authorization=`Bearer ${g}`)}const l={bundleOwnerId:o,...s,...r?.graphql?.additionalHeaders},c=await v.getShadowGraphqlClient().query({query:tl(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],u=k.getMap("bundlePartnerIds")||new Map;u.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",u);const A=new ra(this,d,e,a,o,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:r?.readonly});return await A.getInitializationPromise(),A}async duplicateBundle(t,e,a,r){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const A=await this.loggedInBearerToken();o.Authorization=`Bearer ${A}`}catch{const m=Object.entries(localStorage).find(([g,f])=>g.startsWith("CognitoIdentityServiceProvider")&&g.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(m);p&&!_t(p)&&(o.Authorization=`Bearer ${p}`)}const s={bundleOwnerId:i,...o,...r?.graphql?.additionalHeaders},c=(await v.getShadowGraphqlClient().mutate({mutation:ol(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const u=k.getMap("bundleOwnerIds")||new Map;return u.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",u),async()=>{const A=new ra(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await A.getInitializationPromise(),A}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await v.getShadowGraphqlClient().query({query:fl(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await v.getShadowGraphqlClient().query({query:el,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],r=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",r),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),r=a[0],i=r.getWorkflow();return e&&!i&&console.error("No workflow instantiated when trying to create preview service."),e&&i&&await r.getWorkflowManager().injectIntoPreviewService(e(i)),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new mt("No options provided!");const a=v.getShadowGraphqlClient(),r=async y=>{if(y.length===0)return[];const S=y.map(D=>D.option.transactionId),P=await a.query({query:go,variables:{ids:S},errorPolicy:"all",fetchPolicy:"no-cache"}),b=P.data.transactions;if(b.length!==y.length){const D=P.errors?.[0]?.message||"Unknown error";throw new mt(`Not all transactions were found: ${D}`)}return!this.activeIntegration&&b[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(b[0].integrationProduct.integration)),b.map((D,$)=>({transaction:D,workflowId:D.workflowId,readOnly:y.find(N=>N.option.transactionId===D.id)?.option.readOnly??!1,index:y[$].index}))},i=async y=>{if(y.length===0)return[];const S=await a.mutate({mutation:mo,variables:{inputs:y.map(b=>({integrationProductId:b.option.type==="integration"?b.option.integrationProductId:void 0,externalIntegrationId:b.option.type==="external"?b.option.externalIntegrationId:void 0,externalProductId:b.option.type==="external"?b.option.externalProductId:void 0,workflowId:b.option.workflowId,designName:b.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),P=S.data?.transactionCreateMany;if(!P||P.length===0){const b=S.errors?.[0]?.message||"Unknown error";throw new mt(`Failed to create transactions: ${b}`)}return P.map((b,D)=>({transaction:b,workflowId:b.workflowId,readOnly:!1,index:y[D].index}))},o=t.map((y,S)=>({option:y,index:S})),s=o.filter(y=>y.option.type==="transaction"),l=o.filter(y=>y.option.type==="integration"||y.option.type==="external"||y.option.type==="blank"),c=Xa(s,10),d=Xa(l,10),u=(await Promise.all([...c.map(r),...d.map(i)])).flat(),A=[...new Set(u.map(y=>y.workflowId))].filter(y=>y!==void 0),h=A.length>0?await Ja(A,e):[],m=new Map(h.map(y=>[y.id,y])),p=k.getMap("transactionOwnerIds")||new Map,g=u.map(async y=>{const{transaction:S,workflowId:P,readOnly:b,index:D}=y,$=P?m.get(P):void 0,N=t[D];!p.get(S.id)&&S.transactionOwnerId&&p.set(S.id,S.transactionOwnerId);const et=p.get(S.id)||void 0,at=new Bc({onMutate:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}})}),q={workflow:$,transaction:S,layouts:[],singleVariantsRenderable:N?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:b?async()=>{throw new T("State mutation is forbidden in read only mode!")}:async Y=>this.updateTransactionState({...Y,context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>at,readOnly:b,isReloadedTransaction:N.type==="transaction"};if(N.type==="transaction"&&S.workflowState){const Y=JSON.parse(S.workflowState);q.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),q.reloadedState=Y}else if(!b&&N.workflowState){const Y=JSON.parse(N.workflowState);q.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await fa(Y),q.reloadedState=Y}else q.workflow?q.layouts=kc(q.transaction,q.workflow):q.layouts=[];return q.renderableContextService=new Xl(q.layouts),q.delayWorkflowStateSync=!0,{experienceOptions:q,index:D,options:N}}),f=await Promise.all(g);k.setMap("transactionOwnerIds",p);const I=f.sort((y,S)=>y.index-S.index).map(async y=>{const{experienceOptions:S,options:P}=y,b=new Nr(this,S);return await b.getWorkflowManager().getInitializationPromise(),P.type!=="transaction"&&this.customer&&await b.attachCustomerDetails({email:this.customer.emailAddress}),b}),x=await Promise.all(I);return x.forEach(y=>y.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),x}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await v.getShadowGraphqlClient().query({query:So(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new va(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await v.getShadowGraphqlClient().query({query:vo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new va(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await v.getShadowGraphqlClient().query({query:yo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await v.getShadowGraphqlClient().mutate({mutation:Ro,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 Jr=async(n,t)=>(await v.getShadowGraphqlClient().query({query:To,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,Tc=async n=>{const e=await v.getShadowGraphqlClient().query({query:wo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Nc=async(n,t)=>(await v.getShadowGraphqlClient().query({query:Mo,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,Qc=async n=>(await v.getShadowGraphqlClient().query({query:Qo,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Rc=async n=>(await v.getShadowGraphqlClient().query({query:No,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,Oc=async n=>{const t=await v.getShadowGraphqlClient().mutate({mutation:Bl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n}});if(t.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${t.errors}`)};function Kr(n,t,e,a){const r=e.width*n.zoom,i=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Ie(n.x,t.width-c,0),s.y=Ie(n.y,t.height-d,0),s}const o=n;return o.x=Ie(o.x,-r,t.width),o.y=Ie(o.y,-i,t.height),o}function Ie(n,t,e){return Math.min(Math.max(n,t),e)}class _r{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Pn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;De(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const r=Ft.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=qe(this.imageData.svg,this.imageData.colors||{},!1);return Ve(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new T("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=Kr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,r,i){if(!a||a.length===0||a.some(s=>!s))throw new T("Frame data not set. This is a bug");if(!this.workflowManager)throw new T("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new R([new Ss(s,e,t[l]),new vs(s,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,r)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Na(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class $c{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,m,p,g,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Xr=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Xr||{});class Zr extends X{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new _r(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await ht.selectImage(this.step,t,this.manager,a),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Re.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await O.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,r){return r&&r.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return O.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return O.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Uc=C.gql`
|
2630
2630
|
query GetLoggedInCustomer($email: String!) {
|
2631
2631
|
customer(emailAddress: $email) {
|
2632
2632
|
id
|