@spiffcommerce/core 32.1.1-beta.dd6ba549-af6a-55a7-a5b1-c73eebc8f7e2 → 32.2.0-beta.19153fed-e0bc-5f5f-8acf-49dc9a9c3eb8
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 +3 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +2 -6
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
@@ -2214,7 +2214,7 @@
|
|
2214
2214
|
id
|
2215
2215
|
}
|
2216
2216
|
}
|
2217
|
-
`;var pe=(r=>(r.Error="Error",r.Warning="Warning",r.Info="Info",r))(pe||{});const vl=1e3;class An extends xa{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},vl)})}}class El{constructor(t,e,a,n,i,o,s,l,c,d,A,u,h,g=!1,m,p=!1,f=!1,S=!1){this.workflowStatePromiseQueue=new Da(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.renderLayouts=()=>{if(!this.previewService)return;const b=this.getCommandContext().getAllLayouts(),P=this.getLayoutPreviewService()?.getAll();if(P)for(const[,C]of P)C.render(b)},this.experience=t,this.client=e,this.updateTransaction=s,this.graphQlClient=l,this.commandContext=o,this.reloadedState=h,this.transaction=c,this.readOnly=g,this.singleVariantsRenderable=f,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=a,this.stepSpecificServices={},this.profanityFilter=n,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=d,this.previewService=A,this.modelContainer=m,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.currentAdjustingStepId="",this.renderableContextService=u,this.renderableContextService?.setWorkflowManager(this),this.isReloadedTransaction=p,this.workflow.steps.forEach(b=>{this.stepTags[b.stepName]=b.tags??[]}),S&&(this.workflowStatePromiseQueue.enabled=!1),this.initializationPromise=this.initializeDefaultWorkflowState(a),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(b=>{throw console.error(b),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.getCommandContext().registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()}))}getTemplatingContext(){const t=this.transaction.recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const n=a.uniqueIdentifier??a.title??"";a.type===Xt.FirstName?e[n]=t?.firstName:a.type===Xt.LastName?e[n]=t?.lastName:a.type===Xt.Custom&&(a.customFieldIndex===1?e[n]=t?.customField1:a.customFieldIndex===2?e[n]=t?.customField2:a.customFieldIndex===3?e[n]=t?.customField3:a.customFieldIndex===4?e[n]=t?.customField4:a.customFieldIndex===5&&(e[n]=t?.customField5))}),e}async updateRecipient(t,e,a,n,i,o,s,l,c,d,A,u,h,g,m,p,f){if(this.transaction.recipient?.id)this.transaction.recipient={id:this.transaction.recipient.id,firstName:t??this.transaction.recipient.firstName,lastName:e??this.transaction.recipient.lastName,address:a??this.transaction.recipient.address,suburb:n??this.transaction.recipient.suburb,state:i??this.transaction.recipient.state,email:o??this.transaction.recipient.email,postalCode:s??this.transaction.recipient.postalCode,country:l??this.transaction.recipient.country,mobile:c??this.transaction.recipient.mobile,company:d??this.transaction.recipient.company,apartment:A??this.transaction.recipient.apartment,customField1:u??this.transaction.recipient.customField1,customField2:h??this.transaction.recipient.customField2,customField3:g??this.transaction.recipient.customField3,customField4:m??this.transaction.recipient.customField4,customField5:p??this.transaction.recipient.customField5,conversionConfigurationId:f||this.transaction.recipient.conversionConfigurationId},await this.graphQlClient().mutate({mutation:yl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:n||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:o||this.transaction.recipient.email,postalCode:s||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company,apartment:A||this.transaction.recipient.apartment,customField1:u||this.transaction.recipient.customField1,customField2:h||this.transaction.recipient.customField2,customField3:g||this.transaction.recipient.customField3,customField4:m||this.transaction.recipient.customField4,customField5:p||this.transaction.recipient.customField5,conversionConfigurationId:f||this.transaction.recipient.conversionConfigurationId}});else{const S=await this.graphQlClient().mutate({mutation:wl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:n,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:A,customField1:u,customField2:h,customField3:g,customField4:m,customField5:p,conversionConfigurationId:f}});this.transaction.recipient={id:S?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:n,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:A,customField1:u,customField2:h,customField3:g,customField4:m,customField5:p,conversionConfigurationId:f},await this.graphQlClient().mutate({mutation:Sl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id,recipientId:S.data?.recipientCreate?.id},context:{transactionOwnerId:this.transaction.transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(S=>S(this.transaction.recipient))}async fetchConversionConfiguration(){const t=this.transaction.recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=await this.graphQlClient().query({query:ho,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}});e.data.conversionConfiguration&&(this.recipientConversionConfiguration=e.data.conversionConfiguration)}}async initializeDefaultWorkflowState(t){const e=()=>{const s=this.workflow.finalizeStepConfig;if(!s)return;const l=s.lookAtAnimation,c=s.modelAnimation;l&&this.previewService?.executeCameraAnimation(l),c&&this.modelContainer?.executeAnimation(c)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(s=>{this.storage[s.stepName]=s.storage||{}}),await this.fetchConversionConfiguration(),this.allScenes=await To(t);const n=Et(this.allScenes,this.stepSelections).map(s=>s.silentSteps).flat(),{stepElements:i,commands:o}=await this.stepElementsForIntroducedSilentSteps(n,!!this.reloadedState);this.commandContext.apply(new Q(o),!0),this.stepElements={...this.stepElements,...i},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addPoller(t){this.pollers.push(t)}addValidationCallback(t){this.validationCallbacks.push(t),t(this.validationErrors)}addRecipientCallback(t){this.recipientCallbacks.push(t),t(this.transaction.recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(t=>t.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!0}),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter(e=>e!==t)}markUpdatePending(){const t=M();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}getMandatoryUnfulfilledSteps(){return Et(this.allScenes,this.stepSelections).flatMap(i=>i.renderableSteps).filter(i=>i.mandatory).filter(i=>!this.mandatorySteps[i.stepName]).map(i=>i.stepName)}setStepError(t,e,a){let n=!1;if(!this.validationErrors.steps.has(t)&&a)n=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const i=this.validationErrors.steps.get(t);a&&a!==i.get(e)?(n=!0,i.set(e,a)):a||(n=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}n&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const a=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(a),Et(this.allScenes,this.stepSelections).filter(o=>o).map(o=>o.renderableSteps).flat().filter(o=>o.type===v.Model||o.type===v.Material).forEach(o=>{if(!o.option?.id){console.error(`Failed to read option id from step: ${o.stepName}`);return}const s=this.stepSelections[o.stepName]?.selectedVariants||[];if(s.length===0)return;const l=s[0];if(o.type===v.Model){if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");const c=l.asset?.fileLink;if(!c){console.error(`Failed to read model url from variant: ${l.id} for step: ${o.stepName}`);return}const d=o.data;this.modelContainer.applyModelVariant(o.stepName,{model:c,contextService:this.getLayoutPreviewService()},d.replaceProductModel||!1)}else{const c=l.material;if(!c){console.error(`Failed to read material from variant: ${l.id} for step: ${o.stepName}`);return}o.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,o.option.id,c)})}}),await a.getInitializationPromise(),this.renderLayouts()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}updateStorage(t,e){const a={...this.storage,[t]:{...this.storage[t],...e}};if(!En(a,this.storage)){this.storage=a;const n=new sn(this.constructSerializableWorkflow());this.commandContext.apply(n,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const n={stepName:a.stepName};n.storage=this.storage[a.stepName],n.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(i=>({id:i.id,priceModifier:i.priceModifier})),t.push(n)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;console.log("updating state");const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new An(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;console.log("updating state immediate");const t=this.serialize();return new An(async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new L("Attempted to serialize state before it was initialized.");const e=It(t.transaction),a=this.dehydrateState(e);return JSON.stringify(a)}dehydrateState(t){for(const e of Object.values(t.layouts).map(a=>a.elements).flat())e.type==="illustration"&&(delete e.cachedObjectURL,e.src&&delete e.svg),e.type==="frame"&&delete e.pattern?.svg;return this.deleteFieldNameFromObjectRecursive(t,"__typename"),t}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,n)=>Object.keys(a).reduce((i,o)=>{const s=[...a[o]||[]];return n.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),i[o]=s,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce((t,e)=>(Bt(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])}getInvalidModelVariants(){return this.workflow.steps.reduce((t,e)=>(e.type===v.Model&&!Bt(e,this.stepSelections)&&t.push(e.stepName),t),[])}async stepElementsForIntroducedSilentSteps(t,e){const a=this.product;if(!a)return Promise.resolve({stepElements:{},commands:[]});const n=async(c,d,A)=>{if(c.type===v.SilentIllustration){const u=await new ln(c,d).trigger();return{step:c,results:u}}else if(c.type===v.ProductOverlay){const u=await new ln(c,d,A).trigger();return{step:c,results:u}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||s.push(n(c,this.layouts,a));const l=await Promise.all(s);for(const c of l)o.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),o.commands=[...o.commands,...c.results.map(d=>d.command)];return o}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.transaction.id);this.transaction.transactionShareActions=t}async updateTransactionStakeholders(){const t=await y.getShadowGraphqlClient().query({query:Co,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.transaction.currentStakeholder=void 0,this.transaction.stakeholders=void 0):(this.transaction.stakeholders=t.data.transactions[0].stakeholders,this.transaction.currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:fl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async rejectTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:Cl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async reset(){this.commandContext.getAllLayouts().forEach(e=>e.layoutState.elements.forEach(a=>{this.getCommandDispatcher()(new yt(a.id))})),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,n){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((C,E)=>C+E.selectedVariants.map(x=>x.priceModifier||0).reduce((x,B)=>x+B,0),0),this.workflow.steps.forEach(C=>{Bt(C,this.stepSelections)||(this.stepInitialised[C.stepName]=!1,delete this.stepMetadata[C.stepName],delete this.stepSelections[C.stepName],delete this.storage[C.stepName])});const o=this.allScenes,s=Et(o,i),l=Et(o,this.stepSelections),c=s.map(C=>C.silentSteps).flat(),A=l.map(C=>C.silentSteps).flat().filter(C=>!c.some(E=>E.stepName===C.stepName));c.forEach(C=>{Bt(C,this.stepSelections)||(this.stepInitialised[C.stepName]=!1)});const u=this.getInvalidCanvasRegions(),{stepElements:h,commands:g}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...h,[t]:a},this.removeElements(u);const m=this.workflow.steps.find(C=>C.stepName===t);m?.type===v.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(E=>E.id));const p=u.map(C=>new yt(C.id)),f=new sn(this.constructSerializableWorkflow()),S=[...g,...p,f];S.length>0&&this.commandContext.apply(new Q(S),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const b=this.getInvalidModelVariants(),P=this.modelContainer;if(P){const C=b.map(E=>P.applyModelVariant(E,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(C)}await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const e=Et(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],n=e.flat();for(const l of n)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case v.DigitalContent:a.push(Qa.init(l,this,this.reloadedState));break;case v.Frame:a.push(ht.init(l,this,this.reloadedState));break;case v.Illustration:a.push(Jt.init(l,this,this.reloadedState));break;case v.Material:a.push(Ra.init(l,this,this.reloadedState));break;case v.Model:a.push(Oa.init(l,this,this.reloadedState));break;case v.Module:this.stepSpecificServices[l.stepName]={module:await mr(l.data.module)},a.push($a.init(l,this,this.reloadedState));break;case v.Picture:a.push(Ua.init(l,this,this.reloadedState));break;case v.Question:a.push(La.init(l,this,this.reloadedState));break;case v.Shape:a.push(kt.init(l,this,this.reloadedState));break;case v.Text:a.push(q.init(l,this,this.reloadedState));break}const i=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=i.filter(l=>!!l&&!!l.command).map(l=>l.command),s=i.filter(l=>!!l&&!!l.followup).map(l=>l.followup);o&&o.length>0&&this.commandContext.apply(new Q(o),!0);for(const l of s)await l();s.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(t=>t(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(t=>t(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(t=>t(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(t=>t(this.informationResults))}onInitChange(){this.initCallbacks.forEach(t=>t(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(t=>{t(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(t=>t(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(t=>{t(this.stepMetadata)})}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach(e=>e(this.storage[t]))}onStorageChange(){this.storageCallbacks.forEach(t=>t(this.storage))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return Ro(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class rt{constructor(t){this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.asset?.versions?.find(t=>t.name==="cdn")?.link}getAssetResource(){return this.variantData.asset}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find(a=>a.name==="thumbnail")?.link,e=this.variantData.thumbnail?.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}const Zt=class Zt{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){Zt.updateState.set(`${this.step.stepName}-${this.manager.getTransaction().id}`,t)}getUpdateState(){return!!Zt.updateState.get(`${this.step.stepName}-${this.manager.getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new rt(a)}getAvailableVariants(){return(this.step.option?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.step.option?.variants||[]).map(e=>new rt(e))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.tags}hasTag(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){const a=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){return this.step.globalPropertyAspectConfigurations?.filter(e=>e.globalPropertyConfigurationId===t&&e.aspectName).map(e=>e.aspectName)??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),n=this.step.data.modelAnimation,i=this.step.data.lookAtAnimation;e?i&&e.executeCameraAnimation(i):console.warn("No preview service available, cannot execute camera animations."),a?n&&a.executeAnimation(n,t):console.warn("No model container available, cannot execute model animations.")}};Zt.updateState=new Map;let X=Zt;class pr extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Jt.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=$(t[0].id,this.manager.getAllLayoutData()).colors,i=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=i?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=i.channelNumbers.find(d=>d.number===l.channelNumber);if(c){const d=c.id.replace(/\W/g,"");s[l.channelNumber]={browserValue:a[d]?.browserValue||""}}}),s}try{return a}catch(s){console.error(s)}}setColor(t,e,a){const n=new Map,o=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(o?.defaultColorVariants||[]).length!==0?o.channelNumbers.forEach(l=>{if(l.number.toString()===t){const c=l.id.replace(/\W/g,"");a?n.set(c,{browserValue:e,pmsValue:a}):n.set(c,e)}}):a?n.set(t,{browserValue:e,pmsValue:a}):n.set(t,e),Jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),n)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?Jt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}}class fr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ra.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Cr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Oa.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class wr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ua.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class yr extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await La.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class Sr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return kt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return kt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return kt.availableColours(this.step)}setCustomColor(t){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),kt.setCustomColor(t,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const t=this.manager.getStepStorage(this.step.stepName)?.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}}class vr extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(t){q.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:pe.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?q.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return q.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return q.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);q.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,n=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1}),this.setText(n)}setText(t){const e={input:t,helperData:{}},a=q.findLayoutElements(this.manager,this.step),n=q.filterUnsupportedCharacters(t,a[0]?.fontData),i=Mt(n,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&i>this.step.data.maxLength;o||(e.input=n);const s=a.length<=0,l=s?{inputText:n,text:n}:{inputText:n};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=q.getProcessedInput(n,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:A,errorData:u,helperData:h}=q.updateInputText(n,a,this.step,this.manager);A&&this.manager.getCommandDispatcher()(A),e.helperData=h,e.errorData=u,!o&&!u&&this.manager.updateMetadata(this.step.stepName,{text:d})}return e}getText(){const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&e?.defaultCleared!==void 0&&!e?.defaultCleared?t:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=q.findLayoutElements(this.manager,this.step);return q.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Mt(this.getText(),this.manager);return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}getAvailableStrokeColors(){return this.step.data.strokeEnabled?q.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeStrokeColor(this.step,t,e,this.manager)}}class Er extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class br extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return Qa.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Br extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Mt(this.getText(),this.manager);return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(t){$a.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:pe.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class Se{static get(t,e){switch(e.type){case v.DigitalContent:return new br(t,e,t.getStepTags(e.stepName));case v.Information:return new Er(t,e,t.getStepTags(e.stepName));case v.Question:return new yr(t,e,t.getStepTags(e.stepName));case v.Text:return new vr(t,e,t.getStepTags(e.stepName));case v.Illustration:return new pr(t,e,t.getStepTags(e.stepName));case v.Picture:return new wr(t,e,t.getStepTags(e.stepName));case v.Shape:return new Sr(t,e,t.getStepTags(e.stepName));case v.Material:return new fr(t,e,t.getStepTags(e.stepName));case v.Model:return new Cr(t,e,t.getStepTags(e.stepName));case v.Frame:return new Jr(t,e,t.getStepTags(e.stepName));case v.Module:return new Br(t,e,t.getStepTags(e.stepName));default:throw new L(`Step type ${e.type} not yet supported in Core SDK`)}}}const Ir=w.gql`
|
2217
|
+
`;var pe=(r=>(r.Error="Error",r.Warning="Warning",r.Info="Info",r))(pe||{});const vl=1e3;class An extends xa{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},vl)})}}class El{constructor(t,e,a,n,i,o,s,l,c,d,A,u,h,g=!1,m,p=!1,f=!1,S=!1){this.workflowStatePromiseQueue=new Da(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.renderLayouts=()=>{if(!this.previewService)return;const b=this.getCommandContext().getAllLayouts(),P=this.getLayoutPreviewService()?.getAll();if(P)for(const[,C]of P)C.render(b)},this.experience=t,this.client=e,this.updateTransaction=s,this.graphQlClient=l,this.commandContext=o,this.reloadedState=h,this.transaction=c,this.readOnly=g,this.singleVariantsRenderable=f,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=a,this.stepSpecificServices={},this.profanityFilter=n,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=d,this.previewService=A,this.modelContainer=m,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.currentAdjustingStepId="",this.renderableContextService=u,this.renderableContextService?.setWorkflowManager(this),this.isReloadedTransaction=p,this.workflow.steps.forEach(b=>{this.stepTags[b.stepName]=b.tags??[]}),S&&(this.workflowStatePromiseQueue.enabled=!1),this.initializationPromise=this.initializeDefaultWorkflowState(a),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(b=>{throw console.error(b),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.getCommandContext().registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()}))}getTemplatingContext(){const t=this.transaction.recipient,e={recipient:t};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(a=>{const n=a.uniqueIdentifier??a.title??"";a.type===Xt.FirstName?e[n]=t?.firstName:a.type===Xt.LastName?e[n]=t?.lastName:a.type===Xt.Custom&&(a.customFieldIndex===1?e[n]=t?.customField1:a.customFieldIndex===2?e[n]=t?.customField2:a.customFieldIndex===3?e[n]=t?.customField3:a.customFieldIndex===4?e[n]=t?.customField4:a.customFieldIndex===5&&(e[n]=t?.customField5))}),e}async updateRecipient(t,e,a,n,i,o,s,l,c,d,A,u,h,g,m,p,f){if(this.transaction.recipient?.id)this.transaction.recipient={id:this.transaction.recipient.id,firstName:t??this.transaction.recipient.firstName,lastName:e??this.transaction.recipient.lastName,address:a??this.transaction.recipient.address,suburb:n??this.transaction.recipient.suburb,state:i??this.transaction.recipient.state,email:o??this.transaction.recipient.email,postalCode:s??this.transaction.recipient.postalCode,country:l??this.transaction.recipient.country,mobile:c??this.transaction.recipient.mobile,company:d??this.transaction.recipient.company,apartment:A??this.transaction.recipient.apartment,customField1:u??this.transaction.recipient.customField1,customField2:h??this.transaction.recipient.customField2,customField3:g??this.transaction.recipient.customField3,customField4:m??this.transaction.recipient.customField4,customField5:p??this.transaction.recipient.customField5,conversionConfigurationId:f||this.transaction.recipient.conversionConfigurationId},await this.graphQlClient().mutate({mutation:yl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.recipient.id,firstName:t||this.transaction.recipient.firstName,lastName:e||this.transaction.recipient.lastName,address:a||this.transaction.recipient.address,suburb:n||this.transaction.recipient.suburb,state:i||this.transaction.recipient.state,email:o||this.transaction.recipient.email,postalCode:s||this.transaction.recipient.postalCode,country:l||this.transaction.recipient.country,mobile:c||this.transaction.recipient.mobile,company:d||this.transaction.recipient.company,apartment:A||this.transaction.recipient.apartment,customField1:u||this.transaction.recipient.customField1,customField2:h||this.transaction.recipient.customField2,customField3:g||this.transaction.recipient.customField3,customField4:m||this.transaction.recipient.customField4,customField5:p||this.transaction.recipient.customField5,conversionConfigurationId:f||this.transaction.recipient.conversionConfigurationId}});else{const S=await this.graphQlClient().mutate({mutation:wl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:t,lastName:e,address:a,suburb:n,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:A,customField1:u,customField2:h,customField3:g,customField4:m,customField5:p,conversionConfigurationId:f}});this.transaction.recipient={id:S?.data?.recipientCreate?.id,firstName:t,lastName:e,address:a,suburb:n,state:i,email:o,postalCode:s,country:l,mobile:c,company:d,apartment:A,customField1:u,customField2:h,customField3:g,customField4:m,customField5:p,conversionConfigurationId:f},await this.graphQlClient().mutate({mutation:Sl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id,recipientId:S.data?.recipientCreate?.id},context:{transactionOwnerId:this.transaction.transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(S=>S(this.transaction.recipient))}async fetchConversionConfiguration(){const t=this.transaction.recipient;if(t?.conversionConfigurationId&&!this.recipientConversionConfiguration){const e=await this.graphQlClient().query({query:ho,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t.conversionConfigurationId}});e.data.conversionConfiguration&&(this.recipientConversionConfiguration=e.data.conversionConfiguration)}}async initializeDefaultWorkflowState(t){const e=()=>{const s=this.workflow.finalizeStepConfig;if(!s)return;const l=s.lookAtAnimation,c=s.modelAnimation;l&&this.previewService?.executeCameraAnimation(l),c&&this.modelContainer?.executeAnimation(c)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(s=>{this.storage[s.stepName]=s.storage||{}}),await this.fetchConversionConfiguration(),this.allScenes=await To(t);const n=Et(this.allScenes,this.stepSelections).map(s=>s.silentSteps).flat(),{stepElements:i,commands:o}=await this.stepElementsForIntroducedSilentSteps(n,!!this.reloadedState);this.commandContext.apply(new Q(o),!0),this.stepElements={...this.stepElements,...i},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&e()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(t){this.workflowStatePromiseQueue.enabled=t}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addPoller(t){this.pollers.push(t)}addValidationCallback(t){this.validationCallbacks.push(t),t(this.validationErrors)}addRecipientCallback(t){this.recipientCallbacks.push(t),t(this.transaction.recipient)}removeRecipientCallback(t){this.recipientCallbacks=this.recipientCallbacks.filter(e=>e!==t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(t=>t.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t,t&&t.metadata&&t.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach(e=>{const a=this.stepSelections[e.stepName];a&&a.selectedVariants&&a.selectedVariants.length>0&&(t[e.stepName]={selections:a.selectedVariants})}),t}getStepSelections(){return this.stepSelections}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach(a=>{e[a]=!0}),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter(e=>e!==t)}markUpdatePending(){const t=M();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}getMandatoryUnfulfilledSteps(){return Et(this.allScenes,this.stepSelections).flatMap(i=>i.renderableSteps).filter(i=>i.mandatory).filter(i=>!this.mandatorySteps[i.stepName]).map(i=>i.stepName)}setStepError(t,e,a){let n=!1;if(!this.validationErrors.steps.has(t)&&a)n=!0,this.validationErrors.steps.set(t,new Map([[e,a]]));else if(this.validationErrors.steps.has(t)){const i=this.validationErrors.steps.get(t);a&&a!==i.get(e)?(n=!0,i.set(e,a)):a||(n=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}n&&this.onValidationChange()}getStepErrors(t){return this.validationErrors.steps.get(t)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t,e){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const a=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:e});this.setModelContainer(a),Et(this.allScenes,this.stepSelections).filter(o=>o).map(o=>o.renderableSteps).flat().filter(o=>o.type===v.Model||o.type===v.Material).forEach(o=>{if(!o.option?.id){console.error(`Failed to read option id from step: ${o.stepName}`);return}const s=this.stepSelections[o.stepName]?.selectedVariants||[];if(s.length===0)return;const l=s[0];if(o.type===v.Model){if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");const c=l.asset?.fileLink;if(!c){console.error(`Failed to read model url from variant: ${l.id} for step: ${o.stepName}`);return}const d=o.data;this.modelContainer.applyModelVariant(o.stepName,{model:c,contextService:this.getLayoutPreviewService()},d.replaceProductModel||!1)}else{const c=l.material;if(!c){console.error(`Failed to read material from variant: ${l.id} for step: ${o.stepName}`);return}o.data.targetMaterials.forEach(A=>{if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(A,o.option.id,c)})}}),await a.getInitializationPromise(),this.renderLayouts()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}updateStorage(t,e){const a={...this.storage,[t]:{...this.storage[t],...e}};if(!En(a,this.storage)){this.storage=a;const n=new sn(this.constructSerializableWorkflow());this.commandContext.apply(n,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(a=>{const n={stepName:a.stepName};n.storage=this.storage[a.stepName],n.selectedVariants=this.stepSelections[a.stepName]?.selectedVariants?.map(i=>({id:i.id,priceModifier:i.priceModifier})),t.push(n)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new An(async()=>{await new Promise(e=>{setTimeout(()=>{e()},1)}),await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new An(async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t}})}).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new L("Attempted to serialize state before it was initialized.");const e=It(t.transaction),a=this.dehydrateState(e);return JSON.stringify(a)}dehydrateState(t){for(const e of Object.values(t.layouts).map(a=>a.elements).flat())e.type==="illustration"&&(delete e.cachedObjectURL,e.src&&delete e.svg),e.type==="frame"&&delete e.pattern?.svg;return this.deleteFieldNameFromObjectRecursive(t,"__typename"),t}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){const e=(a,n)=>Object.keys(a).reduce((i,o)=>{const s=[...a[o]||[]];return n.forEach(l=>{const c=s.findIndex(d=>d.id===l.id);c>-1&&s.splice(c,1)}),i[o]=s,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce((t,e)=>(Bt(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach(a=>t.push(a)),t),[])}getInvalidModelVariants(){return this.workflow.steps.reduce((t,e)=>(e.type===v.Model&&!Bt(e,this.stepSelections)&&t.push(e.stepName),t),[])}async stepElementsForIntroducedSilentSteps(t,e){const a=this.product;if(!a)return Promise.resolve({stepElements:{},commands:[]});const n=async(c,d,A)=>{if(c.type===v.SilentIllustration){const u=await new ln(c,d).trigger();return{step:c,results:u}}else if(c.type===v.ProductOverlay){const u=await new ln(c,d,A).trigger();return{step:c,results:u}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),o={stepElements:{},commands:[]},s=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||s.push(n(c,this.layouts,a));const l=await Promise.all(s);for(const c of l)o.stepElements[c.step.stepName]=c.results.map(d=>d.regionElement),o.commands=[...o.commands,...c.results.map(d=>d.command)];return o}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(t){return this.stepTags[t]||[]}getSerializedStep(t,e){return e.find(a=>a.stepName===t)}async updateTransactionShareActions(){const t=await this.client.getShareActionsForTransaction(this.transaction.id);this.transaction.transactionShareActions=t}async updateTransactionStakeholders(){const t=await y.getShadowGraphqlClient().query({query:Co,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id}});!t?.data?.transactions||t.data.transactions.length!==1?(this.transaction.currentStakeholder=void 0,this.transaction.stakeholders=void 0):(this.transaction.stakeholders=t.data.transactions[0].stakeholders,this.transaction.currentStakeholder=t.data.transactions[0].currentStakeholder)}async approveTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:fl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async rejectTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:Cl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async reset(){this.commandContext.getAllLayouts().forEach(e=>e.layoutState.elements.forEach(a=>{this.getCommandDispatcher()(new yt(a.id))})),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,a,n){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((C,E)=>C+E.selectedVariants.map(x=>x.priceModifier||0).reduce((x,B)=>x+B,0),0),this.workflow.steps.forEach(C=>{Bt(C,this.stepSelections)||(this.stepInitialised[C.stepName]=!1,delete this.stepMetadata[C.stepName],delete this.stepSelections[C.stepName],delete this.storage[C.stepName])});const o=this.allScenes,s=Et(o,i),l=Et(o,this.stepSelections),c=s.map(C=>C.silentSteps).flat(),A=l.map(C=>C.silentSteps).flat().filter(C=>!c.some(E=>E.stepName===C.stepName));c.forEach(C=>{Bt(C,this.stepSelections)||(this.stepInitialised[C.stepName]=!1)});const u=this.getInvalidCanvasRegions(),{stepElements:h,commands:g}=await this.stepElementsForIntroducedSilentSteps(A,!1);this.stepElements={...this.stepElements,...h,[t]:a},this.removeElements(u);const m=this.workflow.steps.find(C=>C.stepName===t);m?.type===v.Frame&&this.getWorkflowExperience().getStepById(m.stepName)?.frameService?.setTargetElements(a.map(E=>E.id));const p=u.map(C=>new yt(C.id)),f=new sn(this.constructSerializableWorkflow()),S=[...g,...p,f];S.length>0&&this.commandContext.apply(new Q(S),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const b=this.getInvalidModelVariants(),P=this.modelContainer;if(P){const C=b.map(E=>P.applyModelVariant(E,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(C)}await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const e=Et(this.allScenes,this.stepSelections).map(l=>l.renderableSteps),a=[],n=e.flat();for(const l of n)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case v.DigitalContent:a.push(Qa.init(l,this,this.reloadedState));break;case v.Frame:a.push(ht.init(l,this,this.reloadedState));break;case v.Illustration:a.push(Jt.init(l,this,this.reloadedState));break;case v.Material:a.push(Ra.init(l,this,this.reloadedState));break;case v.Model:a.push(Oa.init(l,this,this.reloadedState));break;case v.Module:this.stepSpecificServices[l.stepName]={module:await mr(l.data.module)},a.push($a.init(l,this,this.reloadedState));break;case v.Picture:a.push(Ua.init(l,this,this.reloadedState));break;case v.Question:a.push(La.init(l,this,this.reloadedState));break;case v.Shape:a.push(kt.init(l,this,this.reloadedState));break;case v.Text:a.push(q.init(l,this,this.reloadedState));break}const i=(await Promise.allSettled(a)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),o=i.filter(l=>!!l&&!!l.command).map(l=>l.command),s=i.filter(l=>!!l&&!!l.followup).map(l=>l.followup);o&&o.length>0&&this.commandContext.apply(new Q(o),!0);for(const l of s)await l();s.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(t=>t(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(t=>t(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(t=>t(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(t=>t(this.informationResults))}onInitChange(){this.initCallbacks.forEach(t=>t(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(t=>{t(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(t=>t(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(t=>{t(this.stepMetadata)})}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach(e=>e(this.storage[t]))}onStorageChange(){this.storageCallbacks.forEach(t=>t(this.storage))}onValidationChange(){this.validationCallbacks.forEach(t=>t(this.validationErrors))}traversableScenes(){return Ro(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class rt{constructor(t){this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.asset?.versions?.find(t=>t.name==="cdn")?.link}getAssetResource(){return this.variantData.asset}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find(a=>a.name==="thumbnail")?.link,e=this.variantData.thumbnail?.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}const Zt=class Zt{constructor(t,e,a){this.manager=t,this.step=e,this.tags=a}setUpdateState(t){Zt.updateState.set(`${this.step.stepName}-${this.manager.getTransaction().id}`,t)}getUpdateState(){return!!Zt.updateState.get(`${this.step.stepName}-${this.manager.getTransaction().id}`)}getCurrentVariant(){const a=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(a)return new rt(a)}getAvailableVariants(){return(this.step.option?.variants?.filter(e=>e.enabled)||[]).map(e=>new rt(e))}getAllVariants(){return(this.step.option?.variants||[]).map(e=>new rt(e))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}getTags(){return this.tags}hasTag(t){return this.tags.includes(t)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(t){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){const a=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...a,[t.toString()]:e}})}getGlobalPropertyAspects(t){return this.step.globalPropertyAspectConfigurations?.filter(e=>e.globalPropertyConfigurationId===t&&e.aspectName).map(e=>e.aspectName)??[]}executeAnimations(t){const e=this.manager.getPreviewService(),a=this.manager.getModelContainer(),n=this.step.data.modelAnimation,i=this.step.data.lookAtAnimation;e?i&&e.executeCameraAnimation(i):console.warn("No preview service available, cannot execute camera animations."),a?n&&a.executeAnimation(n,t):console.warn("No model container available, cannot execute model animations.")}};Zt.updateState=new Map;let X=Zt;class pr extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!this.getUpdateState()&&this.getCurrentVariant()!==t)return Jt.selectVariant(this.step,t.getResource(),this.manager.getRegionElements(this.step.stepName)||[],e=>this.setUpdateState(e),this.manager)}getColors(){const t=this.manager.getRegionElements(this.step.stepName)||[];if(t.length===0)return;const a=$(t[0].id,this.manager.getAllLayoutData()).colors,i=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,o=i?.defaultColorVariants||[];if(o.length!==0){const s={};return o.forEach(l=>{const c=i.channelNumbers.find(d=>d.number===l.channelNumber);if(c){const d=c.id.replace(/\W/g,"");s[l.channelNumber]={browserValue:a[d]?.browserValue||""}}}),s}try{return a}catch(s){console.error(s)}}setColor(t,e,a){const n=new Map,o=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(o?.defaultColorVariants||[]).length!==0?o.channelNumbers.forEach(l=>{if(l.number.toString()===t){const c=l.id.replace(/\W/g,"");a?n.set(c,{browserValue:e,pmsValue:a}):n.set(c,e)}}):a?n.set(t,{browserValue:e,pmsValue:a}):n.set(t,e),Jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),n)}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?Jt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}}class fr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ra.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class Cr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Oa.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class wr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){return Ua.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class yr extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(t){if(!t.getId())throw new Error("Unable to select variant with a null ID");await La.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){return this.step.data.displayType||this.step.option?.displayType}}class Sr extends X{constructor(t,e,a){super(t,e,a)}selectVariant(t){const e=t.getResource();return kt.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return kt.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return kt.availableColours(this.step)}setCustomColor(t){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),kt.setCustomColor(t,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const t=this.manager.getStepStorage(this.step.stepName)?.colour;if(!t)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return t}}class vr extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(t){q.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:pe.Error,stepID:this.step.stepName}]);else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?q.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillColor(this.step,t,e,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return q.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeFillImage(this.step,t,e,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return q.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);q.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){const e=this.manager.getStepStorage(this.step.stepName)?.inputText||"",a=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,n=t?a:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:n,defaultCleared:!1}),this.setText(n)}setText(t){const e={input:t,helperData:{}},a=q.findLayoutElements(this.manager,this.step),n=q.filterUnsupportedCharacters(t,a[0]?.fontData),i=Mt(n,this.manager).length,o=!!this.step.data&&!!this.step.data.maxLength&&i>this.step.data.maxLength;o||(e.input=n);const s=a.length<=0,l=s?{inputText:n,text:n}:{inputText:n};this.manager.updateStorage(this.step.stepName,l);const c=this.manager.getStepStorage(this.step.stepName),d=q.getProcessedInput(n,this.step.data,c?.customiseAllText??!1);if(s)o||this.manager.updateMetadata(this.step.stepName,{text:d});else{const{command:A,errorData:u,helperData:h}=q.updateInputText(n,a,this.step,this.manager);A&&this.manager.getCommandDispatcher()(A),e.helperData=h,e.errorData=u,!o&&!u&&this.manager.updateMetadata(this.step.stepName,{text:d})}return e}getText(){const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&e?.defaultCleared!==void 0&&!e?.defaultCleared?t:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const a=q.findLayoutElements(this.manager,this.step);return q.updateInputText("",a,this.step,this.manager),e}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Mt(this.getText(),this.manager);return t-e.length}setCustomColor(t){throw new Error("Custom color support is not yet available on text. Check back soon.")}getCustomColor(){throw new Error("Custom color support is not yet available on text. Check back soon.")}getAvailableStrokeColors(){return this.step.data.strokeEnabled?q.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await q.changeStrokeColor(this.step,t,e,this.manager)}}class Er extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getContent(){return this.step.data.content}}class br extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(t){return Qa.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class Br extends X{constructor(t,e,a){super(t,e,a)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const t=this.step.data.maxLength;if(t===void 0)return;const e=Mt(this.getText(),this.manager);return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(t){$a.changeText(this.step,t,this.manager,e=>{if(e){const a=[...this.manager.getInformationResults(),{message:e,messageType:pe.Error,stepID:this.step.stepName}];this.manager.setInformationResults(a)}else{const a=this.manager.getInformationResults().filter(n=>n.stepID!==this.step.stepName);this.manager.setInformationResults(a)}})}}class Se{static get(t,e){switch(e.type){case v.DigitalContent:return new br(t,e,t.getStepTags(e.stepName));case v.Information:return new Er(t,e,t.getStepTags(e.stepName));case v.Question:return new yr(t,e,t.getStepTags(e.stepName));case v.Text:return new vr(t,e,t.getStepTags(e.stepName));case v.Illustration:return new pr(t,e,t.getStepTags(e.stepName));case v.Picture:return new wr(t,e,t.getStepTags(e.stepName));case v.Shape:return new Sr(t,e,t.getStepTags(e.stepName));case v.Material:return new fr(t,e,t.getStepTags(e.stepName));case v.Model:return new Cr(t,e,t.getStepTags(e.stepName));case v.Frame:return new Jr(t,e,t.getStepTags(e.stepName));case v.Module:return new Br(t,e,t.getStepTags(e.stepName));default:throw new L(`Step type ${e.type} not yet supported in Core SDK`)}}}const Ir=w.gql`
|
2218
2218
|
fragment CreateDesignTransaction on Transaction {
|
2219
2219
|
id
|
2220
2220
|
designName
|
@@ -2401,7 +2401,7 @@
|
|
2401
2401
|
quoteId
|
2402
2402
|
}
|
2403
2403
|
}
|
2404
|
-
`;class aa{constructor(t,e,a,n,i,o){this.workflowExperiences=[],this.eventEmitter=new lc,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new nc(e.bundleStateData);const s=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=s?.id,this.globalPropertyStateManager=new ac(this.id,this.ownerId,s,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new Zl(this),this.setPreviewService(a);const l=new Promise((c,d)=>{if(o?.readonly){c([]);return}console.log("Setting default global variants.");const A=this.globalPropertyStateManager.getGlobalPropertyState();A?this.globalPropertyHandleService.getHandles().then(u=>{const h=u.map(g=>{if(g.getType()===U.ColorOption||g.getType()===U.Option){const m=g;if(!A.aspects.find(f=>f.name===m.getName()))return m.initDefaultVariant()}});Promise.all(h).then(c).catch(d)}):(console.log("Attempted to set global default variant before state was initialized."),c([]))});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(e.transactions?.map(c=>c.id)||[],{...n,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}getTemplate(){return this.template}async generateQuoteId(){const e=(await y.getShadowGraphqlClient().mutate({mutation:Ac,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,n,i,o){await y.getShadowGraphqlClient().mutate({mutation:cc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:i||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await y.getShadowGraphqlClient().mutate({mutation:dc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){const e=await this.globalPropertyHandleService.getHandles();for(const a of t.aspects){const n=a?.name;this.getGlobalPropertyStateManager().setAspect(n,a.value)}for(const a of t.aspects){const n=a?.name,i=e.find(o=>o.getName()===n);if(i)switch(a.type){case U.FileUpload:{const o=i,s=await Pe([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case U.ColorOption:{const o=i;if(a.type===U.ColorOption){const l=o.getAllVariants().find(c=>c.getId()===a.value);l&&await o.selectVariant(l)}else o.setCustomColor(a.value);break}case U.Option:{const o=i,l=o.getAllVariants().find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case U.Text:{await i.setText(a.value);break}}}this.checkMandatoryHandlesChanged(void 0,e)}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===U.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,n)=>a+n,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new qa(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(v.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const n of a){const i=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===n);if(i&&i.type===U.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=ec(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",n),d=[...new Set(s.map(u=>u.number))];if(d.length>c)for(const u of d){const h=this.getGlobalPropertyStateManager(),g=l.find(m=>m.channelNumber===u);g&&await h.setAspect(n,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getWorkflowManager().getTransaction().id),a=e.map(s=>this.workflowExperiences.find(l=>l.getWorkflowManager().getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getWorkflowManager().getTransaction().id).join(", "));const n=k.getMap("transactionOwnerIds")||new Map,i=e.map(s=>n.get(s));await y.getShadowGraphqlClient().mutate({mutation:rl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(k.getMap("transactionOwnerIds")||new Map).get(a);await y.getShadowGraphqlClient().mutate({mutation:nl,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const n=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);if(n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await y.getShadowGraphqlClient().mutate({mutation:il,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,o])=>({key:i,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(n=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id));if(e.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((n,i)=>e[i]===-1).map(n=>n.id).join(", "));const a=t.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id),1)[0]);a.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&a.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),t.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await y.getShadowGraphqlClient().mutate({mutation:ol,variables:{id:this.id,transactionIds:t.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,i])=>({key:n,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(n=>n.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const a=await y.getShadowGraphqlClient().mutate({mutation:sl,variables:{id:this.id,details:t,type:e||ee.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const n=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async removeStakeholder(t){if(!(await y.getShadowGraphqlClient().mutate({mutation:ll,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await y.getShadowGraphqlClient().mutate({mutation:cl,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await y.getShadowGraphqlClient().query({query:dn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await y.getShadowGraphqlClient().query({query:dn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){if(this.completed)return await y.getShadowGraphqlClient().mutate({mutation:gl,variables:{bundleId:this.id}}),{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:[],bundleOwnerId:this.ownerId};const a=await Dl(this.workflowExperiences.map(n=>({workflowManager:n.getWorkflowManager(),workflow:n.getWorkflowManager().getWorkflow(),layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:n.getWorkflowManager().getProduct(),transaction:n.getWorkflowManager().getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:n.getWorkflowManager().getWorkflow().name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(n,i)=>{const o=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===i);return o?e(o,n):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getWorkflowManager().getTransaction().id,amountToOrder:e.getWorkflowManager().getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await y.getShadowGraphqlClient().mutate({mutation:ul,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await y.getShadowGraphqlClient().mutate({mutation:Al(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),this.globalConfigurationPropertyId=a?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const n=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===n.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(n=>({type:"transaction",transactionId:n})),e);if(a.forEach(n=>n.setBundle(this)),a.forEach(n=>n.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const n of a)await this.injectExperienceIntoPreviewService(n)}async updateBundle(){if(!(await y.getShadowGraphqlClient().mutate({mutation:al,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await y.getShadowGraphqlClient().mutate({mutation:dl,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){const a=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(n,i),this.checkMandatoryHandlesChanged(t,i);const o=i.filter(s=>!n.includes(s));await Promise.all(o.map(s=>s.applyGlobalState()))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let n=0;n<t.length;n++)if(t[n].getName()!==e[n].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],n=[],i=[],o=Qr(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?n.push(s):i.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:n,remaining:i})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await y.getShadowGraphqlClient().mutate({mutation:ml,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await y.getShadowGraphqlClient().mutate({mutation:pl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const uc=w.gql`
|
2404
|
+
`;class aa{constructor(t,e,a,n,i,o){this.workflowExperiences=[],this.eventEmitter=new lc,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(e.metadata?.map(c=>[c.key,c.value])||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new nc(e.bundleStateData);const s=this.productCollection?.globalPropertyConfiguration;this.globalConfigurationPropertyId=s?.id,this.globalPropertyStateManager=new ac(this.id,this.ownerId,s,this.onGlobalPropertiesChanged.bind(this),o),this.globalPropertyHandleService=new Zl(this),this.setPreviewService(a);const l=new Promise((c,d)=>{if(o?.readonly){c([]);return}console.log("Setting default global variants.");const A=this.globalPropertyStateManager.getGlobalPropertyState();A?this.globalPropertyHandleService.getHandles().then(u=>{const h=u.map(g=>{if(g.getType()===U.ColorOption||g.getType()===U.Option){const m=g;if(!A.aspects.find(f=>f.name===m.getName()))return m.initDefaultVariant()}});Promise.all(h).then(c).catch(d)}):(console.log("Attempted to set global default variant before state was initialized."),c([]))});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(e.transactions?.map(c=>c.id)||[],{...n,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(c=>{console.error(`Bundle initialization failed: ${c}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(c=>this.checkMandatoryHandlesChanged(void 0,c))})}getTemplate(){return this.template}async generateQuoteId(){const e=(await y.getShadowGraphqlClient().mutate({mutation:Ac,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data?.bundleGenerateQuoteId?.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,n,i,o){await y.getShadowGraphqlClient().mutate({mutation:cc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:i||void 0,postCode:o||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await y.getShadowGraphqlClient().mutate({mutation:dc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){return!!this.productCollection?.globalPropertyConfiguration}getGlobalPropertyConfiguration(){return this.productCollection?.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){const e=await this.globalPropertyHandleService.getHandles();for(const a of t.aspects){const n=a?.name;this.getGlobalPropertyStateManager().setAspect(n,a.value)}for(const a of t.aspects){const n=a?.name,i=e.find(o=>o.getName()===n);if(i)switch(a.type){case U.FileUpload:{const o=i,s=await Pe([a.value]);s.length>0&&await o.selectImage(s[0]);const l=a.storage?.colors;if(l){const c=Object.fromEntries(l.map(d=>[d.key,{browserValue:d.browserValue,pmsValue:d.pmsValue}])??[]);await o.changeColors(c)}break}case U.ColorOption:{const o=i;if(a.type===U.ColorOption){const l=o.getAllVariants().find(c=>c.getId()===a.value);l&&await o.selectVariant(l)}else o.setCustomColor(a.value);break}case U.Option:{const o=i,l=o.getAllVariants().find(c=>c.getId()===a.value);l&&await o.selectVariant(l);break}case U.Text:{await i.setText(a.value);break}}}this.checkMandatoryHandlesChanged(void 0,e)}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===U.Option).map(a=>a.getCurrentVariant()?.getPrice()||0).reduce((a,n)=>a+n,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new qa(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){for(const e of t.getStepsByType(v.Illustration)){const a=e.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const n of a){const i=this.getGlobalPropertyConfiguration()?.aspects.find(o=>o.name===n);if(i&&i.type===U.ColorOption){const o=e.getCurrentVariant()?.getAssetResource(),s=o?.assetConfiguration?.channelNumbers||[],l=o?.assetConfiguration?.defaultColorVariants||[],c=ec(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",n),d=[...new Set(s.map(u=>u.number))];if(d.length>c)for(const u of d){const h=this.getGlobalPropertyStateManager(),g=l.find(m=>m.channelNumber===u);g&&await h.setAspect(n,g.variant.id||"",void 0,g.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const s of t)await this.initializeAdditionalRequiredColorChannels(s);const e=t.map(s=>s.getWorkflowManager().getTransaction().id),a=e.map(s=>this.workflowExperiences.find(l=>l.getWorkflowManager().getTransaction().id===s));if(a.some(s=>!!s))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(s=>!!s).map(s=>s?.getWorkflowManager().getTransaction().id).join(", "));const n=k.getMap("transactionOwnerIds")||new Map,i=e.map(s=>n.get(s));await y.getShadowGraphqlClient().mutate({mutation:rl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(s=>{console.error(s)}),this.workflowExperiences.push(...t);const o=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const s=await this.getGlobalProperties();for(const l of s)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),o()]),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const o=(k.getMap("transactionOwnerIds")||new Map).get(a);await y.getShadowGraphqlClient().mutate({mutation:nl,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:o}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const n=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);if(n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await y.getShadowGraphqlClient().mutate({mutation:il,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,o])=>({key:i,value:o})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(n=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id));if(e.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((n,i)=>e[i]===-1).map(n=>n.id).join(", "));const a=t.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id),1)[0]);a.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&a.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),t.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await y.getShadowGraphqlClient().mutate({mutation:ol,variables:{id:this.id,transactionIds:t.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,i])=>({key:n,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(n=>n.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){const a=await y.getShadowGraphqlClient().mutate({mutation:sl,variables:{id:this.id,details:t,type:e||ee.Owner},context:{bundleOwnerId:this.ownerId}});if(!a.data?.bundleAddStakeholder)throw new Error("Bundle not found!");const n=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async removeStakeholder(t){if(!(await y.getShadowGraphqlClient().mutate({mutation:ll,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data?.bundleRemoveStakeholder)throw new Error("Bundle not found!")}async updateStakeholders(t){const e=await y.getShadowGraphqlClient().mutate({mutation:cl,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!e.data?.bundleUpdateStakeholders)throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await y.getShadowGraphqlClient().query({query:dn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await y.getShadowGraphqlClient().query({query:dn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){if(this.completed)return await y.getShadowGraphqlClient().mutate({mutation:gl,variables:{bundleId:this.id}}),{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:[],bundleOwnerId:this.ownerId};const a=await Dl(this.workflowExperiences.map(n=>({workflowManager:n.getWorkflowManager(),workflow:n.getWorkflowManager().getWorkflow(),layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:n.getWorkflowManager().getProduct(),transaction:n.getWorkflowManager().getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:n.getWorkflowManager().getWorkflow().name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(n,i)=>{const o=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===i);return o?e(o,n):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,name:this.getName(),dispatchDate:this.getDispatchDate()||"",purchaseOrder:this.getPurchaseOrder()||"",collectionId:this.getProductCollection()?.getId()||"",collectionName:this.getProductCollection()?.getName()||"",items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getWorkflowManager().getTransaction().id,amountToOrder:e.getWorkflowManager().getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await y.getShadowGraphqlClient().mutate({mutation:ul,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){const e=await y.getShadowGraphqlClient().mutate({mutation:Al(this.globalPropertyStateManager.getBundleOptions()?.eagerFetchProducts??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if(e.data?.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const a=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(a),this.globalConfigurationPropertyId=a?.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const n=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===n.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(n=>({type:"transaction",transactionId:n})),e);if(a.forEach(n=>n.setBundle(this)),a.forEach(n=>n.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const n of a)await this.injectExperienceIntoPreviewService(n)}async updateBundle(){if(!(await y.getShadowGraphqlClient().mutate({mutation:al,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([e,a])=>({key:e,value:a})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data?.bundleUpdate)throw new Error("Bundle not found!")}async updateTransactionOrder(){await y.getShadowGraphqlClient().mutate({mutation:dl,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){const a=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(n,i),this.checkMandatoryHandlesChanged(t,i),await Promise.all(i.map(o=>o.applyGlobalState()))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let n=0;n<t.length;n++)if(t[n].getName()!==e[n].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],n=[],i=[],o=Qr(t);e.forEach(s=>{if(s.isMandatory()){const l=s.isMandatoryFulfilled();l?n.push(s):i.push(s);const c=o.get(s.getName());(c===void 0||c!==l)&&a.push(s)}}),this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:n,remaining:i})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await y.getShadowGraphqlClient().mutate({mutation:ml,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await y.getShadowGraphqlClient().mutate({mutation:pl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const uc=w.gql`
|
2405
2405
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
2406
2406
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
2407
2407
|
id
|
@@ -2530,7 +2530,7 @@
|
|
2530
2530
|
}
|
2531
2531
|
}
|
2532
2532
|
}
|
2533
|
-
`;class Cc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class wc{init(t,e,a){this.cognitoClient=new fe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const n=await this.cognitoClient?.send(new fe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return n?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new wc;class qr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return di(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ka.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Ka.code(e)?.code==="CLP")return"USD0,0"}}const hn=new qr;class Gr{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,hn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,hn.getPrecisionForCurrency(e))}}const yc=async(r,t)=>{const e=await y.getShadowGraphqlClient().query({query:bo(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:r}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(n=>console.error(n)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(n=>{n.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&R.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&R.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&R.cacheAsset(o.asset),o.thumbnail&&R.cacheAsset(o.thumbnail),o.material&&R.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),n.finalizeStepConfig||(n.finalizeStepConfig={}),n.finalizeStepConfig.termsMarkdown=n.finalizeStepConfig.termsMarkdown||n.partner.termsMarkdown}),a},Sc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},ja=async(r,t)=>{const e=r.map(s=>$t.get({id:s,options:t})),a=r.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=yc(a,t),i=a.map(s=>$t.set({id:s,options:t},Sc(s,n))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},vc=async(r,t)=>(await ja([r],t))[0],Ec=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:M(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),bc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):Ec(t.panels)};class Bc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:Ao})}catch(a){throw console.error(a),new gt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Pi(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 32.1.1-beta.024c12f2-73fa-5718-a179-d941802fb807"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&On(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return R}getFlowService(){if(!xi())throw new Error("Application key required to use Flow Service.");return new Lr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:Mo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new Gr(o,s,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Wr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}async authenticateBundleFromLocalStorage(t){if(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const n=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(n)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=y.getShadowGraphqlClient(),a=await e.query({query:Bo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const n=a.data.transactions[0];if(!n.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const u=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(u)return Promise.resolve({success:!0,stakeholderType:u.type})}const c=(await e.query({query:Io,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await y.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),n=(await e.query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const s=(await e.mutate({mutation:mc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(n);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),i=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:pc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,i=!a?.AccessToken||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||i){const o=await Wt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:fc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:tl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!i?.id)throw new Error("Unable to create bundle");const o=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new aa(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const m=Object.entries(localStorage).find(([f,S])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(m);p&&!_t(p)&&(s.Authorization=`Bearer ${p}`)}const l={bundleOwnerId:o,...s,...n?.graphql?.additionalHeaders},c=await y.getShadowGraphqlClient().query({query:Js(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],A=k.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",A);const u=new aa(this,d,e,a,o,{additionalHeaders:n?.graphql?.additionalHeaders,eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:n?.readonly});return await u.getInitializationPromise(),u}async duplicateBundle(t,e,a,n){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const u=await this.loggedInBearerToken();o.Authorization=`Bearer ${u}`}catch{const g=Object.entries(localStorage).find(([p,f])=>p.startsWith("CognitoIdentityServiceProvider")&&p.endsWith("idToken"))?.[0]||"",m=localStorage.getItem(g);m&&!_t(m)&&(o.Authorization=`Bearer ${m}`)}const s={bundleOwnerId:i,...o,...n?.graphql?.additionalHeaders},c=(await y.getShadowGraphqlClient().mutate({mutation:el(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const A=k.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",A),async()=>{const u=new aa(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await u.getInitializationPromise(),u}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:hl(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:Ks,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&n.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new gt("No options provided!");const a=y.getShadowGraphqlClient(),n=async C=>{if(C.length===0)return[];const E=C.map(D=>D.option.transactionId),x=await a.query({query:co,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),B=x.data.transactions;if(B.length!==C.length){const D=x.errors?.[0]?.message||"Unknown error";throw new gt(`Not all transactions were found: ${D}`)}return!this.activeIntegration&&B[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(B[0].integrationProduct.integration)),B.map((D,O)=>({transaction:D,workflowId:D.workflowId,readOnly:C.find(T=>T.option.transactionId===D.id)?.option.readOnly??!1,index:C[O].index}))},i=async C=>{if(C.length===0)return[];const E=await a.mutate({mutation:lo,variables:{inputs:C.map(B=>({integrationProductId:B.option.type==="integration"?B.option.integrationProductId:void 0,externalIntegrationId:B.option.type==="external"?B.option.externalIntegrationId:void 0,externalProductId:B.option.type==="external"?B.option.externalProductId:void 0,workflowId:B.option.workflowId,designName:B.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),x=E.data?.transactionCreateMany;if(!x||x.length===0){const B=E.errors?.[0]?.message||"Unknown error";throw new gt(`Failed to create transactions: ${B}`)}return x.map((B,D)=>({transaction:B,workflowId:B.workflowId,readOnly:!1,index:C[D].index}))},o=t.map((C,E)=>({option:C,index:E})),s=o.filter(C=>C.option.type==="transaction"),l=o.filter(C=>C.option.type==="integration"||C.option.type==="external"),c=Ja(s,10),d=Ja(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(C=>C.workflowId))],h=await ja(u,e),g=new Map(h.map(C=>[C.id,C])),m=k.getMap("transactionOwnerIds")||new Map,p=A.map(async C=>{const{transaction:E,workflowId:x,readOnly:B,index:D}=C,O=g.get(x),T=t[D];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const et=m.get(E.id)||void 0,at=new Cc({onMutate:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}})}),H={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:T?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:B?async()=>{throw new L("State mutation is forbidden in read only mode!")}:async Y=>this.updateTransactionState({...Y,context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>at,readOnly:B,workflow:O,isReloadedTransaction:T.type==="transaction"};if(T.type==="transaction"&&E.workflowState){const Y=JSON.parse(E.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await ma(Y),H.reloadedState=Y}else if(!B&&T.workflowState){const Y=JSON.parse(T.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await ma(Y),H.reloadedState=Y}else H.layouts=bc(H.transaction,H.workflow);return H.renderableContextService=new jl(H.layouts),H.delayWorkflowStateSync=!0,{experienceOptions:H,index:D,options:T}}),f=await Promise.all(p);k.setMap("transactionOwnerIds",m);const b=f.sort((C,E)=>C.index-E.index).map(async C=>{const{experienceOptions:E,options:x}=C,B=new kr(this,E);return await B.getWorkflowManager().getInitializationPromise(),x.type!=="transaction"&&this.customer&&await B.attachCustomerDetails({email:this.customer.emailAddress}),B}),P=await Promise.all(b);return P.forEach(C=>C.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),P}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:po(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new wa(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:fo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new wa(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await y.getShadowGraphqlClient().query({query:mo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ko,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const Wr=async(r,t)=>(await y.getShadowGraphqlClient().query({query:xo,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,Ic=async r=>{const e=await y.getShadowGraphqlClient().query({query:go,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Pc=async(r,t)=>(await y.getShadowGraphqlClient().query({query:Po,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,xc=async r=>(await y.getShadowGraphqlClient().query({query:Fo,errorPolicy:"all",variables:{id:r}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Dc=async r=>(await y.getShadowGraphqlClient().query({query:Do,errorPolicy:"all",variables:{id:r}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;function jr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const s=r,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,r.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Ee(r.x,t.width-c,0),s.y=Ee(r.y,t.height-d,0),s}const o=r;return o.x=Ee(o.x,-n,t.width),o.y=Ee(o.y,-i,t.height),o}function Ee(r,t,e){return Math.min(Math.max(r,t),e)}class Hr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=bn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let o=0;o<n.currentFrameSources.length;o++){const s=n.currentFrameSources[o],l=await he(s),c=this.frameData?this.frameData[o]:void 0;En(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Ft.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=Le(this.imageData.svg,this.imageData.colors||{},!1);return $e(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],A=a[s]-c*t[s];return{x:d,y:A,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,n),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new L("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=jr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,i){if(!a||a.length===0||a.some(s=>!s))throw new L("Frame data not set. This is a bug");if(!this.workflowManager)throw new L("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new Q([new ps(s,e,t[l]),new fs(s,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=ka(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Fc{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,n,i,o,s,l,c,d,A,u,h,g,m,p,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Yr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(Yr||{});class Jr extends X{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Hr(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await ht.selectImage(this.step,t,this.manager,a),e){const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Te.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await R.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return R.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return R.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const n=await this.getBackgroundRemovedImageSelection();if(!n)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(n,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const kc=w.gql`
|
2533
|
+
`;class Cc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class wc{init(t,e,a){this.cognitoClient=new fe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const n=await this.cognitoClient?.send(new fe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return n?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new fe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new wc;class qr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return di(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ka.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Ka.code(e)?.code==="CLP")return"USD0,0"}}const hn=new qr;class Gr{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,hn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,hn.getPrecisionForCurrency(e))}}const yc=async(r,t)=>{const e=await y.getShadowGraphqlClient().query({query:bo(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:r}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(n=>console.error(n)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(n=>{n.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&R.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&R.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&R.cacheAsset(o.asset),o.thumbnail&&R.cacheAsset(o.thumbnail),o.material&&R.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),n.finalizeStepConfig||(n.finalizeStepConfig={}),n.finalizeStepConfig.termsMarkdown=n.finalizeStepConfig.termsMarkdown||n.partner.termsMarkdown}),a},Sc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},ja=async(r,t)=>{const e=r.map(s=>$t.get({id:s,options:t})),a=r.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=yc(a,t),i=a.map(s=>$t.set({id:s,options:t},Sc(s,n))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},vc=async(r,t)=>(await ja([r],t))[0],Ec=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:M(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),bc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):Ec(t.panels)};class Bc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:Ao})}catch(a){throw console.error(a),new gt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Pi(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 32.2.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&On(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return R}getFlowService(){if(!xi())throw new Error("Application key required to use Flow Service.");return new Lr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await y.getShadowGraphqlClient().query({query:Mo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new Gr(o,s,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Wr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}async authenticateBundleFromLocalStorage(t){if(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const n=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(n)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=y.getShadowGraphqlClient(),a=await e.query({query:Bo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const n=a.data.transactions[0];if(!n.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const u=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(u)return Promise.resolve({success:!0,stakeholderType:u.type})}const c=(await e.query({query:Io,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await y.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),n=(await e.query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const s=(await e.mutate({mutation:mc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(n);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),i=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:pc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:ve,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,i=!a?.AccessToken||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||i){const o=await Wt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:fc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await y.getShadowGraphqlClient().mutate({mutation:tl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!i?.id)throw new Error("Unable to create bundle");const o=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new aa(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const m=Object.entries(localStorage).find(([f,S])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",p=localStorage.getItem(m);p&&!_t(p)&&(s.Authorization=`Bearer ${p}`)}const l={bundleOwnerId:o,...s,...n?.graphql?.additionalHeaders},c=await y.getShadowGraphqlClient().query({query:Js(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],A=k.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",A);const u=new aa(this,d,e,a,o,{additionalHeaders:n?.graphql?.additionalHeaders,eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:n?.readonly});return await u.getInitializationPromise(),u}async duplicateBundle(t,e,a,n){const i=k.getMap("bundleOwnerIds")?.get(t),o={};try{const u=await this.loggedInBearerToken();o.Authorization=`Bearer ${u}`}catch{const g=Object.entries(localStorage).find(([p,f])=>p.startsWith("CognitoIdentityServiceProvider")&&p.endsWith("idToken"))?.[0]||"",m=localStorage.getItem(g);m&&!_t(m)&&(o.Authorization=`Bearer ${m}`)}const s={bundleOwnerId:i,...o,...n?.graphql?.additionalHeaders},c=(await y.getShadowGraphqlClient().mutate({mutation:el(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!c?.id)throw new Error("Unable to duplicate bundle");const d=k.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),k.setMap("bundlePartnerIds",d);const A=k.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),k.setMap("bundleOwnerIds",A),async()=>{const u=new aa(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await u.getInitializationPromise(),u}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:hl(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:Ks,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&n.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new gt("No options provided!");const a=y.getShadowGraphqlClient(),n=async C=>{if(C.length===0)return[];const E=C.map(D=>D.option.transactionId),x=await a.query({query:co,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),B=x.data.transactions;if(B.length!==C.length){const D=x.errors?.[0]?.message||"Unknown error";throw new gt(`Not all transactions were found: ${D}`)}return!this.activeIntegration&&B[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(B[0].integrationProduct.integration)),B.map((D,O)=>({transaction:D,workflowId:D.workflowId,readOnly:C.find(T=>T.option.transactionId===D.id)?.option.readOnly??!1,index:C[O].index}))},i=async C=>{if(C.length===0)return[];const E=await a.mutate({mutation:lo,variables:{inputs:C.map(B=>({integrationProductId:B.option.type==="integration"?B.option.integrationProductId:void 0,externalIntegrationId:B.option.type==="external"?B.option.externalIntegrationId:void 0,externalProductId:B.option.type==="external"?B.option.externalProductId:void 0,workflowId:B.option.workflowId,designName:B.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),x=E.data?.transactionCreateMany;if(!x||x.length===0){const B=E.errors?.[0]?.message||"Unknown error";throw new gt(`Failed to create transactions: ${B}`)}return x.map((B,D)=>({transaction:B,workflowId:B.workflowId,readOnly:!1,index:C[D].index}))},o=t.map((C,E)=>({option:C,index:E})),s=o.filter(C=>C.option.type==="transaction"),l=o.filter(C=>C.option.type==="integration"||C.option.type==="external"),c=Ja(s,10),d=Ja(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(C=>C.workflowId))],h=await ja(u,e),g=new Map(h.map(C=>[C.id,C])),m=k.getMap("transactionOwnerIds")||new Map,p=A.map(async C=>{const{transaction:E,workflowId:x,readOnly:B,index:D}=C,O=g.get(x),T=t[D];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const et=m.get(E.id)||void 0,at=new Cc({onMutate:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}})}),H={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:T?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:B?async()=>{throw new L("State mutation is forbidden in read only mode!")}:async Y=>this.updateTransactionState({...Y,context:{transactionOwnerId:et,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>at,readOnly:B,workflow:O,isReloadedTransaction:T.type==="transaction"};if(T.type==="transaction"&&E.workflowState){const Y=JSON.parse(E.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await ma(Y),H.reloadedState=Y}else if(!B&&T.workflowState){const Y=JSON.parse(T.workflowState);H.layouts=Object.values(Y.layouts||{}).map(vt=>vt.layout),await ma(Y),H.reloadedState=Y}else H.layouts=bc(H.transaction,H.workflow);return H.renderableContextService=new jl(H.layouts),H.delayWorkflowStateSync=!0,{experienceOptions:H,index:D,options:T}}),f=await Promise.all(p);k.setMap("transactionOwnerIds",m);const b=f.sort((C,E)=>C.index-E.index).map(async C=>{const{experienceOptions:E,options:x}=C,B=new kr(this,E);return await B.getWorkflowManager().getInitializationPromise(),x.type!=="transaction"&&this.customer&&await B.attachCustomerDetails({email:this.customer.emailAddress}),B}),P=await Promise.all(b);return P.forEach(C=>C.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),P}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await y.getShadowGraphqlClient().query({query:po(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new wa(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:fo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new wa(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await y.getShadowGraphqlClient().query({query:mo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:ko,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const Wr=async(r,t)=>(await y.getShadowGraphqlClient().query({query:xo,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,Ic=async r=>{const e=await y.getShadowGraphqlClient().query({query:go,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Pc=async(r,t)=>(await y.getShadowGraphqlClient().query({query:Po,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,xc=async r=>(await y.getShadowGraphqlClient().query({query:Fo,errorPolicy:"all",variables:{id:r}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Dc=async r=>(await y.getShadowGraphqlClient().query({query:Do,errorPolicy:"all",variables:{id:r}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;function jr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const s=r,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,r.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Ee(r.x,t.width-c,0),s.y=Ee(r.y,t.height-d,0),s}const o=r;return o.x=Ee(o.x,-n,t.width),o.y=Ee(o.y,-i,t.height),o}function Ee(r,t,e){return Math.min(Math.max(r,t),e)}class Hr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=bn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let o=0;o<n.currentFrameSources.length;o++){const s=n.currentFrameSources[o],l=await he(s),c=this.frameData?this.frameData[o]:void 0;En(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Ft.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=Le(this.imageData.svg,this.imageData.colors||{},!1);return $e(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],A=a[s]-c*t[s];return{x:d,y:A,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,n),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new L("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=jr(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,i){if(!a||a.length===0||a.some(s=>!s))throw new L("Frame data not set. This is a bug");if(!this.workflowManager)throw new L("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new Q([new ps(s,e,t[l]),new fs(s,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=ka(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Fc{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,n,i,o,s,l,c,d,A,u,h,g,m,p,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Yr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(Yr||{});class Jr extends X{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Hr(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await ht.selectImage(this.step,t,this.manager,a),e){const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Te.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await R.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return R.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return R.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const n=await this.getBackgroundRemovedImageSelection();if(!n)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(n,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const kc=w.gql`
|
2534
2534
|
query GetLoggedInCustomer($email: String!) {
|
2535
2535
|
customer(emailAddress: $email) {
|
2536
2536
|
id
|