@spiffcommerce/core 26.7.2 → 26.7.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -14,6 +14,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
14
14
  - `Fixed` for any bug fixes.
15
15
  - `Security` in case of vulnerabilities.
16
16
 
17
+ ## [26.7.3] - 18-12-2024
18
+
19
+ ### Added
20
+
21
+ - Added the `illustrationStep.isPMSPickerEnabled` function. This function returns a boolean indicating whether the PMS picker is enabled for the step.
22
+
17
23
  ## [26.7.2] - 02-12-2024
18
24
 
19
25
  ### Fixed
package/dist/index.d.ts CHANGED
@@ -2942,6 +2942,7 @@ interface IllustrationStepData extends Animatable, Placeable, Colorable {
2942
2942
  assets?: StepAsset[];
2943
2943
  defaultAssetKey?: string;
2944
2944
  colorPickerEnabled?: boolean;
2945
+ pmsPickerEnabled?: boolean;
2945
2946
  varySelection?: boolean;
2946
2947
  varyColors?: boolean;
2947
2948
  }
@@ -4952,6 +4953,7 @@ declare class IllustrationStepHandle extends StepHandle<IllustrationStepData> {
4952
4953
  pmsValue: string;
4953
4954
  }[] | undefined>;
4954
4955
  isColorPickerEnabled(): boolean;
4956
+ isPMSPickerEnabled(): boolean;
4955
4957
  }
4956
4958
 
4957
4959
  interface TextChangeResult {
package/dist/index.js CHANGED
@@ -925,6 +925,7 @@
925
925
  ...OptionFields
926
926
  }
927
927
  colorPickerEnabled
928
+ pmsPickerEnabled
928
929
  displayColorsOnFinishStep
929
930
  displaySelectionOnFinishStep
930
931
  hideColorsInCart
@@ -3154,7 +3155,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
3154
3155
  mutation RejectTransaction($id: String!, $note: String) {
3155
3156
  transactionReject(id: $id, note: $note)
3156
3157
  }
3157
- `;var re=(n=>(n.Error="Error",n.Warning="Warning",n.Info="Info",n))(re||{});const Ko=1e3;class Aa extends wA{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},Ko)})}}class Wo{constructor(t,e,A,a,i,s,o,r,c,l,g,d,B=!1,h,C=!1,u=!1,w=!1){this.workflowStatePromiseQueue=new EA(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.renderLayouts=()=>{var f;if(!this.previewService)return;const E=this.getCommandContext().getAllLayouts(),m=(f=this.getLayoutPreviewService())==null?void 0:f.getAll();if(m)for(const[,p]of m)p.render(E)},this.experience=t,this.client=e,this.updateTransaction=o,this.commandContext=s,this.reloadedState=d,this.transaction=r,this.readOnly=B,this.singleVariantsRenderable=u,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=A,this.stepSpecificServices={},this.profanityFilter=a,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=c,this.previewService=l,this.modelContainer=h,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.currentAdjustingStepId="",this.renderableContextService=g,this.isReloadedTransaction=C,this.workflow.steps.forEach(E=>{this.stepTags[E.stepName]=E.tags??[]}),w&&(this.workflowStatePromiseQueue.enabled=!1),this.initializationPromise=this.initializeDefaultWorkflowState(A),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(E=>{throw console.error(E),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.getCommandContext().registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()}))}async initializeDefaultWorkflowState(t){const e=()=>{var l,g;const o=this.workflow.finalizeStepConfig;if(!o)return;const r=o.lookAtAnimation,c=o.modelAnimation;r&&((l=this.previewService)==null||l.executeCameraAnimation(r)),c&&((g=this.modelContainer)==null||g.executeAnimation(c))};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(o=>{this.storage[o.stepName]=o.storage||{}}),this.allScenes=await ss(t);const a=Ft(this.allScenes,this.stepSelections).map(o=>o.silentSteps).flat(),{stepElements:i,commands:s}=await this.stepElementsForIntroducedSilentSteps(a,!!this.reloadedState);this.commandContext.apply(new G(s),!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)}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=b();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.setInformationResults([]),this.onMandatoryChange())}setStepError(t,e,A){let a=!1;if(!this.validationErrors.steps.has(t)&&A)a=!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)?(a=!0,i.set(e,A)):A||(a=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}a&&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),Ft(this.allScenes,this.stepSelections).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===M.Model||s.type===M.Material).forEach(s=>{var c,l,g;if(!((c=s.option)!=null&&c.id)){console.error(`Failed to read option id from step: ${s.stepName}`);return}const o=((l=this.stepSelections[s.stepName])==null?void 0:l.selectedVariants)||[];if(o.length===0)return;const r=o[0];if(s.type===M.Model){if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");const d=(g=r.asset)==null?void 0:g.fileLink;if(!d){console.error(`Failed to read model url from variant: ${r.id} for step: ${s.stepName}`);return}const B=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:d,contextService:this.getLayoutPreviewService()},B.replaceProductModel||!1)}else{const d=r.material;if(!d){console.error(`Failed to read material from variant: ${r.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(h=>{if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(h,s.option.id,d)})}}),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(!sa(A,this.storage)){this.storage=A;const a=new $A(this.constructSerializableWorkflow());this.commandContext.apply(a,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(A=>{var i,s;const a={stepName:A.stepName};a.storage=this.storage[A.stepName],a.selectedVariants=(s=(i=this.stepSelections[A.stepName])==null?void 0:i.selectedVariants)==null?void 0:s.map(o=>({id:o.id,priceModifier:o.priceModifier})),t.push(a)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new Aa(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 Aa(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=xt(t.transaction),A=this.dehydrateState(e);return JSON.stringify(A)}dehydrateState(t){var e;for(const A of Object.values(t.layouts).map(a=>a.elements).flat())A.type==="illustration"&&(delete A.cachedObjectURL,A.src&&delete A.svg),A.type==="frame"&&((e=A.pattern)==null||delete e.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,a)=>Object.keys(A).reduce((i,s)=>{const o=[...A[s]||[]];return a.forEach(r=>{const c=o.findIndex(l=>l.id===r.id);c>-1&&o.splice(c,1)}),i[s]=o,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce((t,e)=>(ft(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===M.Model&&!ft(e,this.stepSelections)&&t.push(e.stepName),t),[])}async stepElementsForIntroducedSilentSteps(t,e){const A=this.product;if(!A)return Promise.resolve({stepElements:{},commands:[]});const a=async(c,l,g)=>{if(c.type===M.SilentIllustration){const d=await new _A(c,l).trigger();return{step:c,results:d}}else if(c.type===M.ProductOverlay){const d=await new _A(c,l,g).trigger();return{step:c,results:d}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),s={stepElements:{},commands:[]},o=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||o.push(a(c,this.layouts,A));const r=await Promise.all(o);for(const c of r)s.stepElements[c.step.stepName]=c.results.map(l=>l.regionElement),s.commands=[...s.commands,...c.results.map(l=>l.command)];return s}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(){var e;const t=await y.getShadowGraphqlClient().query({query:Vi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id}});!((e=t==null?void 0:t.data)!=null&&e.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:jo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async rejectTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:Vo,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 ut(A.id))})),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,A,a){var p;const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((I,D)=>I+D.selectedVariants.map(F=>F.priceModifier||0).reduce((F,x)=>F+x,0),0),this.workflow.steps.forEach(I=>{ft(I,this.stepSelections)||(this.stepInitialised[I.stepName]=!1,delete this.stepMetadata[I.stepName],delete this.stepSelections[I.stepName],delete this.storage[I.stepName])});const s=this.allScenes,o=Ft(s,i),r=Ft(s,this.stepSelections),c=o.map(I=>I.silentSteps).flat(),g=r.map(I=>I.silentSteps).flat().filter(I=>!c.some(D=>D.stepName===I.stepName));c.forEach(I=>{ft(I,this.stepSelections)||(this.stepInitialised[I.stepName]=!1)});const d=this.getInvalidCanvasRegions(),{stepElements:B,commands:h}=await this.stepElementsForIntroducedSilentSteps(g,!1);this.stepElements={...this.stepElements,...B,[t]:A},this.removeElements(d);const C=this.workflow.steps.find(I=>I.stepName===t);if((C==null?void 0:C.type)===M.Frame){const I=(p=this.getWorkflowExperience().getStepById(C.stepName))==null?void 0:p.frameService;I==null||I.setTargetElements(A.map(D=>D.id))}const u=d.map(I=>new ut(I.id)),w=new $A(this.constructSerializableWorkflow()),E=[...h,...u,w];E.length>0&&this.commandContext.apply(new G(E),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const m=this.getInvalidModelVariants(),f=this.modelContainer;if(f){const I=m.map(D=>f.applyModelVariant(D,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(I)}await this.onSelectionChange(),a&&await a()}async ensureStepsAreLoaded(){const e=Ft(this.allScenes,this.stepSelections).map(r=>r.renderableSteps),A=[],a=e.flat();for(const r of a)if(!this.stepInitialised[r.stepName])switch(this.stepInitialised[r.stepName]=!0,r.type){case M.DigitalContent:A.push(yA.init(r,this,this.reloadedState));break;case M.Frame:A.push(rt.init(r,this,this.reloadedState));break;case M.Illustration:A.push(jt.init(r,this,this.reloadedState));break;case M.Material:A.push(FA.init(r,this,this.reloadedState));break;case M.Model:A.push(MA.init(r,this,this.reloadedState));break;case M.Module:this.stepSpecificServices[r.stepName]={module:await sn(r.data.module)},A.push(SA.init(r,this,this.reloadedState));break;case M.Picture:A.push(xA.init(r,this,this.reloadedState));break;case M.Question:A.push(YA.init(r,this,this.reloadedState));break;case M.Shape:A.push(St.init(r,this,this.reloadedState));break;case M.Text:A.push(W.init(r,this,this.reloadedState));break}const i=(await Promise.allSettled(A)).map(r=>{if(r.status==="rejected")throw new Error(`Step initialization failed: ${r.reason}`);return r.value}),s=i.filter(r=>!!r&&!!r.command).map(r=>r.command),o=i.filter(r=>!!r&&!!r.followup).map(r=>r.followup);s&&s.length>0&&this.commandContext.apply(new G(s),!0);for(const r of o)await r();o.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 cs(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class at{constructor(t){this.variantData=t}getType(){var t;return(t=this.variantData.asset)==null?void 0:t.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(){var t,e,A;return(A=(e=(t=this.variantData.asset)==null?void 0:t.versions)==null?void 0:e.find(a=>a.name==="cdn"))==null?void 0:A.link}getAssetResource(){return this.variantData.asset}getThumbnail(){var A,a,i,s;const t=(i=(a=(A=this.variantData.thumbnail)==null?void 0:A.versions)==null?void 0:a.find(o=>o.name==="thumbnail"))==null?void 0:i.link,e=(s=this.variantData.thumbnail)==null?void 0:s.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}const on=class iA{constructor(t,e,A){this.manager=t,this.step=e,this.tags=A}setUpdateState(t){iA.updateState.set(`${this.step.stepName}-${this.manager.getTransaction().id}`,t)}getUpdateState(){return!!iA.updateState.get(`${this.step.stepName}-${this.manager.getTransaction().id}`)}getCurrentVariant(){const e=this.manager.getWorkflowSelections()[this.step.stepName],A=e==null?void 0:e.selections[0];if(A)return new at(A)}getAvailableVariants(){var e,A;return(((A=(e=this.step.option)==null?void 0:e.variants)==null?void 0:A.filter(a=>a.enabled))||[]).map(a=>new at(a))}getAllVariants(){var e;return(((e=this.step.option)==null?void 0:e.variants)||[]).map(A=>new at(A))}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){var A;return(((A=this.manager.getStepStorage(this.step.stepName))==null?void 0:A.overrideGlobalConfigurations)??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){var a;const A=((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.overrideGlobalConfigurations)??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...A,[t.toString()]:e}})}getGlobalPropertyAspects(t){var e;return((e=this.step.globalPropertyAspectConfigurations)==null?void 0:e.filter(A=>A.globalPropertyConfigurationId===t&&A.aspectName).map(A=>A.aspectName))??[]}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),A=this.step.data.modelAnimation,a=this.step.data.lookAtAnimation;t?a&&t.executeCameraAnimation(a):console.warn("No preview service available, cannot execute camera animations."),e?A&&e.executeAnimation(A):console.warn("No model container available, cannot execute model animations.")}};on.updateState=new Map;let et=on;class rn extends et{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)try{return J(t[0].id,this.manager.getAllLayoutData()).colors}catch(e){console.error(e)}}setColor(t,e,A){const a=new Map;return A?a.set(t,{browserValue:e,pmsValue:A}):a.set(t,e),jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),a)}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}}class cn extends et{constructor(t,e,A){super(t,e,A)}selectVariant(t){return FA.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class ln extends et{constructor(t,e,A){super(t,e,A)}selectVariant(t){return MA.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class gn extends et{constructor(t,e,A){super(t,e,A)}selectVariant(t){return xA.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class dn extends et{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 YA.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){var t;return this.step.data.displayType||((t=this.step.option)==null?void 0:t.displayType)}}class Bn extends et{constructor(t,e,A){super(t,e,A)}selectVariant(t){const e=t.getResource();return St.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return St.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return St.availableColours(this.step)}setCustomColor(t){var e,A;return((e=this.getCurrentVariant())==null?void 0:e.getColor())!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${(A=this.getCurrentVariant())==null?void 0:A.getColor()}`),St.setCustomColor(t,this.step,this.manager)}getCustomColor(){var e,A,a;((e=this.getCurrentVariant())==null?void 0:e.getColor())!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${(A=this.getCurrentVariant())==null?void 0:A.getColor()}`);const t=(a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.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 hn extends et{constructor(t,e,A){super(t,e,A)}async selectVariant(t){W.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:re.Error,stepID:this.step.stepName}]);else{const A=this.manager.getInformationResults().filter(a=>a.stepID!==this.step.stepName);this.manager.setInformationResults(A)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?W.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillColor(this.step,t,e,this.manager)}getFillColor(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.color)||"#000000"}getAvailableFillImages(){return W.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillImage(this.step,t,e,this.manager)}getFillImage(){var t;return(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.fillImage}getAlignment(){const t=W.findLayoutElements(this.manager,this.step);return t==null?void 0:t[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);W.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){var s;const e=((s=this.manager.getStepStorage(this.step.stepName))==null?void 0:s.inputText)||"",A=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,a=t?A:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:a,defaultCleared:!1}),this.setText(a)}setText(t){var l;const e={input:t,helperData:{}},A=W.findLayoutElements(this.manager,this.step),a=W.filterUnsupportedCharacters(t,(l=A[0])==null?void 0:l.fontData),i=!!this.step.data&&!!this.step.data.maxLength&&a.length>this.step.data.maxLength;i||(e.input=a);const s=A.length<=0,o=s?{inputText:a,text:a}:{inputText:a};this.manager.updateStorage(this.step.stepName,o);const r=this.manager.getStepStorage(this.step.stepName),c=W.getProcessedInput(a,this.step.data,!!r.customiseAllText);if(s)i||this.manager.updateMetadata(this.step.stepName,{text:c});else{const{command:g,errorData:d,helperData:B}=W.updateInputText(a,A,this.step,this.manager);g&&this.manager.getCommandDispatcher()(g),e.helperData=B,e.errorData=d,!i&&!d&&this.manager.updateMetadata(this.step.stepName,{text:c})}return e}getText(){var A;const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&(e==null?void 0:e.defaultCleared)!==void 0&&!(e!=null&&e.defaultCleared)?t:((A=this.manager.getStepStorage(this.step.stepName))==null?void 0:A.text)||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){const t=this.manager.getStepStorage(this.step.stepName);if(!(t!=null&&t.defaultCleared)&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const A=W.findLayoutElements(this.manager,this.step);return W.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=this.getText();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?W.availableStrokeColors(this.step):[]}getStrokeColor(){var t,e;return((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.strokeColor)==null?void 0:e.browserValue)||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeStrokeColor(this.step,t,e,this.manager)}}class Cn extends et{constructor(t,e,A){super(t,e,A)}async selectVariant(){}getContent(){return this.step.data.content}}class un extends et{constructor(t,e,A){super(t,e,A)}async selectVariant(){}getPreviewURL(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.videoUrl)||""}async selectVideo(t){return yA.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class wn extends et{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=this.getText();return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.text)||""}setText(t){SA.changeText(this.step,t,this.manager,"",e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:e,messageType:re.Error,stepID:this.step.stepName}]);else{const A=this.manager.getInformationResults().filter(a=>a.stepID!==this.step.stepName);this.manager.setInformationResults(A)}})}}class de{static get(t,e){switch(e.type){case M.DigitalContent:return new un(t,e,t.getStepTags(e.stepName));case M.Information:return new Cn(t,e,t.getStepTags(e.stepName));case M.Question:return new dn(t,e,t.getStepTags(e.stepName));case M.Text:return new hn(t,e,t.getStepTags(e.stepName));case M.Illustration:return new rn(t,e,t.getStepTags(e.stepName));case M.Picture:return new gn(t,e,t.getStepTags(e.stepName));case M.Shape:return new Bn(t,e,t.getStepTags(e.stepName));case M.Material:return new cn(t,e,t.getStepTags(e.stepName));case M.Model:return new ln(t,e,t.getStepTags(e.stepName));case M.Frame:return new Hn(t,e,t.getStepTags(e.stepName));case M.Module:return new wn(t,e,t.getStepTags(e.stepName));default:throw new L(`Step type ${e.type} not yet supported in Core SDK`)}}}const En=Q.gql`
3158
+ `;var re=(n=>(n.Error="Error",n.Warning="Warning",n.Info="Info",n))(re||{});const Ko=1e3;class Aa extends wA{constructor(t){super(),this.createdAt=new Date,this.update=t}async execute(){await this.update(),await new Promise(t=>{window.setTimeout(()=>{t()},Ko)})}}class Wo{constructor(t,e,A,a,i,s,o,r,c,l,g,d,B=!1,h,C=!1,u=!1,w=!1){this.workflowStatePromiseQueue=new EA(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.renderLayouts=()=>{var f;if(!this.previewService)return;const E=this.getCommandContext().getAllLayouts(),m=(f=this.getLayoutPreviewService())==null?void 0:f.getAll();if(m)for(const[,p]of m)p.render(E)},this.experience=t,this.client=e,this.updateTransaction=o,this.commandContext=s,this.reloadedState=d,this.transaction=r,this.readOnly=B,this.singleVariantsRenderable=u,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=A,this.stepSpecificServices={},this.profanityFilter=a,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=c,this.previewService=l,this.modelContainer=h,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.currentAdjustingStepId="",this.renderableContextService=g,this.isReloadedTransaction=C,this.workflow.steps.forEach(E=>{this.stepTags[E.stepName]=E.tags??[]}),w&&(this.workflowStatePromiseQueue.enabled=!1),this.initializationPromise=this.initializeDefaultWorkflowState(A),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(E=>{throw console.error(E),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")}),this.initializationPromise.finally(()=>this.getCommandContext().registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()}))}async initializeDefaultWorkflowState(t){const e=()=>{var l,g;const o=this.workflow.finalizeStepConfig;if(!o)return;const r=o.lookAtAnimation,c=o.modelAnimation;r&&((l=this.previewService)==null||l.executeCameraAnimation(r)),c&&((g=this.modelContainer)==null||g.executeAnimation(c))};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(o=>{this.storage[o.stepName]=o.storage||{}}),this.allScenes=await ss(t);const a=Ft(this.allScenes,this.stepSelections).map(o=>o.silentSteps).flat(),{stepElements:i,commands:s}=await this.stepElementsForIntroducedSilentSteps(a,!!this.reloadedState);this.commandContext.apply(new G(s),!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)}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=b();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.setInformationResults([]),this.onMandatoryChange())}setStepError(t,e,A){let a=!1;if(!this.validationErrors.steps.has(t)&&A)a=!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)?(a=!0,i.set(e,A)):A||(a=!0,i.delete(e),i.size===0&&this.validationErrors.steps.delete(t))}a&&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),Ft(this.allScenes,this.stepSelections).filter(s=>s).map(s=>s.renderableSteps).flat().filter(s=>s.type===M.Model||s.type===M.Material).forEach(s=>{var c,l,g;if(!((c=s.option)!=null&&c.id)){console.error(`Failed to read option id from step: ${s.stepName}`);return}const o=((l=this.stepSelections[s.stepName])==null?void 0:l.selectedVariants)||[];if(o.length===0)return;const r=o[0];if(s.type===M.Model){if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");const d=(g=r.asset)==null?void 0:g.fileLink;if(!d){console.error(`Failed to read model url from variant: ${r.id} for step: ${s.stepName}`);return}const B=s.data;this.modelContainer.applyModelVariant(s.stepName,{model:d,contextService:this.getLayoutPreviewService()},B.replaceProductModel||!1)}else{const d=r.material;if(!d){console.error(`Failed to read material from variant: ${r.id} for step: ${s.stepName}`);return}s.data.targetMaterials.forEach(h=>{if(!this.modelContainer)throw new L("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(h,s.option.id,d)})}}),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(!sa(A,this.storage)){this.storage=A;const a=new $A(this.constructSerializableWorkflow());this.commandContext.apply(a,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach(e=>{e.renderableSteps.forEach(A=>{var i,s;const a={stepName:A.stepName};a.storage=this.storage[A.stepName],a.selectedVariants=(s=(i=this.stepSelections[A.stepName])==null?void 0:i.selectedVariants)==null?void 0:s.map(o=>({id:o.id,priceModifier:o.priceModifier})),t.push(a)})}),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new Aa(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 Aa(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=xt(t.transaction),A=this.dehydrateState(e);return JSON.stringify(A)}dehydrateState(t){var e;for(const A of Object.values(t.layouts).map(a=>a.elements).flat())A.type==="illustration"&&(delete A.cachedObjectURL,A.src&&delete A.svg),A.type==="frame"&&((e=A.pattern)==null||delete e.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,a)=>Object.keys(A).reduce((i,s)=>{const o=[...A[s]||[]];return a.forEach(r=>{const c=o.findIndex(l=>l.id===r.id);c>-1&&o.splice(c,1)}),i[s]=o,i},{});this.stepElements=e(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce((t,e)=>(ft(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===M.Model&&!ft(e,this.stepSelections)&&t.push(e.stepName),t),[])}async stepElementsForIntroducedSilentSteps(t,e){const A=this.product;if(!A)return Promise.resolve({stepElements:{},commands:[]});const a=async(c,l,g)=>{if(c.type===M.SilentIllustration){const d=await new _A(c,l).trigger();return{step:c,results:d}}else if(c.type===M.ProductOverlay){const d=await new _A(c,l,g).trigger();return{step:c,results:d}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter(c=>!this.stepInitialised[c.stepName]),s={stepElements:{},commands:[]},o=[];for(const c of i)this.markStepsAsInitialised([c.stepName]),e||o.push(a(c,this.layouts,A));const r=await Promise.all(o);for(const c of r)s.stepElements[c.step.stepName]=c.results.map(l=>l.regionElement),s.commands=[...s.commands,...c.results.map(l=>l.command)];return s}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(){var e;const t=await y.getShadowGraphqlClient().query({query:Vi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.transaction.id}});!((e=t==null?void 0:t.data)!=null&&e.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:jo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.getTransaction().id,note:t}})}async rejectTransaction(t){await y.getShadowGraphqlClient().mutate({mutation:Vo,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 ut(A.id))})),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,A,a){var p;const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce((I,D)=>I+D.selectedVariants.map(F=>F.priceModifier||0).reduce((F,x)=>F+x,0),0),this.workflow.steps.forEach(I=>{ft(I,this.stepSelections)||(this.stepInitialised[I.stepName]=!1,delete this.stepMetadata[I.stepName],delete this.stepSelections[I.stepName],delete this.storage[I.stepName])});const s=this.allScenes,o=Ft(s,i),r=Ft(s,this.stepSelections),c=o.map(I=>I.silentSteps).flat(),g=r.map(I=>I.silentSteps).flat().filter(I=>!c.some(D=>D.stepName===I.stepName));c.forEach(I=>{ft(I,this.stepSelections)||(this.stepInitialised[I.stepName]=!1)});const d=this.getInvalidCanvasRegions(),{stepElements:B,commands:h}=await this.stepElementsForIntroducedSilentSteps(g,!1);this.stepElements={...this.stepElements,...B,[t]:A},this.removeElements(d);const C=this.workflow.steps.find(I=>I.stepName===t);if((C==null?void 0:C.type)===M.Frame){const I=(p=this.getWorkflowExperience().getStepById(C.stepName))==null?void 0:p.frameService;I==null||I.setTargetElements(A.map(D=>D.id))}const u=d.map(I=>new ut(I.id)),w=new $A(this.constructSerializableWorkflow()),E=[...h,...u,w];E.length>0&&this.commandContext.apply(new G(E),!0),await this.ensureStepsAreLoaded(),this.onElementsChange();const m=this.getInvalidModelVariants(),f=this.modelContainer;if(f){const I=m.map(D=>f.applyModelVariant(D,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(I)}await this.onSelectionChange(),a&&await a()}async ensureStepsAreLoaded(){const e=Ft(this.allScenes,this.stepSelections).map(r=>r.renderableSteps),A=[],a=e.flat();for(const r of a)if(!this.stepInitialised[r.stepName])switch(this.stepInitialised[r.stepName]=!0,r.type){case M.DigitalContent:A.push(yA.init(r,this,this.reloadedState));break;case M.Frame:A.push(rt.init(r,this,this.reloadedState));break;case M.Illustration:A.push(jt.init(r,this,this.reloadedState));break;case M.Material:A.push(FA.init(r,this,this.reloadedState));break;case M.Model:A.push(MA.init(r,this,this.reloadedState));break;case M.Module:this.stepSpecificServices[r.stepName]={module:await sn(r.data.module)},A.push(SA.init(r,this,this.reloadedState));break;case M.Picture:A.push(xA.init(r,this,this.reloadedState));break;case M.Question:A.push(YA.init(r,this,this.reloadedState));break;case M.Shape:A.push(St.init(r,this,this.reloadedState));break;case M.Text:A.push(W.init(r,this,this.reloadedState));break}const i=(await Promise.allSettled(A)).map(r=>{if(r.status==="rejected")throw new Error(`Step initialization failed: ${r.reason}`);return r.value}),s=i.filter(r=>!!r&&!!r.command).map(r=>r.command),o=i.filter(r=>!!r&&!!r.followup).map(r=>r.followup);s&&s.length>0&&this.commandContext.apply(new G(s),!0);for(const r of o)await r();o.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 cs(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}}class at{constructor(t){this.variantData=t}getType(){var t;return(t=this.variantData.asset)==null?void 0:t.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(){var t,e,A;return(A=(e=(t=this.variantData.asset)==null?void 0:t.versions)==null?void 0:e.find(a=>a.name==="cdn"))==null?void 0:A.link}getAssetResource(){return this.variantData.asset}getThumbnail(){var A,a,i,s;const t=(i=(a=(A=this.variantData.thumbnail)==null?void 0:A.versions)==null?void 0:a.find(o=>o.name==="thumbnail"))==null?void 0:i.link,e=(s=this.variantData.thumbnail)==null?void 0:s.fileLink;return t||e}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}const on=class iA{constructor(t,e,A){this.manager=t,this.step=e,this.tags=A}setUpdateState(t){iA.updateState.set(`${this.step.stepName}-${this.manager.getTransaction().id}`,t)}getUpdateState(){return!!iA.updateState.get(`${this.step.stepName}-${this.manager.getTransaction().id}`)}getCurrentVariant(){const e=this.manager.getWorkflowSelections()[this.step.stepName],A=e==null?void 0:e.selections[0];if(A)return new at(A)}getAvailableVariants(){var e,A;return(((A=(e=this.step.option)==null?void 0:e.variants)==null?void 0:A.filter(a=>a.enabled))||[]).map(a=>new at(a))}getAllVariants(){var e;return(((e=this.step.option)==null?void 0:e.variants)||[]).map(A=>new at(A))}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){var A;return(((A=this.manager.getStepStorage(this.step.stepName))==null?void 0:A.overrideGlobalConfigurations)??{})[t.toString()]??!1}setOverrideGlobalPropertyConfiguration(t,e){var a;const A=((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.overrideGlobalConfigurations)??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...A,[t.toString()]:e}})}getGlobalPropertyAspects(t){var e;return((e=this.step.globalPropertyAspectConfigurations)==null?void 0:e.filter(A=>A.globalPropertyConfigurationId===t&&A.aspectName).map(A=>A.aspectName))??[]}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),A=this.step.data.modelAnimation,a=this.step.data.lookAtAnimation;t?a&&t.executeCameraAnimation(a):console.warn("No preview service available, cannot execute camera animations."),e?A&&e.executeAnimation(A):console.warn("No model container available, cannot execute model animations.")}};on.updateState=new Map;let et=on;class rn extends et{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)try{return J(t[0].id,this.manager.getAllLayoutData()).colors}catch(e){console.error(e)}}setColor(t,e,A){const a=new Map;return A?a.set(t,{browserValue:e,pmsValue:A}):a.set(t,e),jt.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,()=>this.manager.getCommandContext().getAllLayouts(),a)}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 cn extends et{constructor(t,e,A){super(t,e,A)}selectVariant(t){return FA.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class ln extends et{constructor(t,e,A){super(t,e,A)}selectVariant(t){return MA.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class gn extends et{constructor(t,e,A){super(t,e,A)}selectVariant(t){return xA.selectVariant(this.step,t.getResource(),this.manager,e=>this.setUpdateState(e))}}class dn extends et{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 YA.selectVariant(this.step,t.getId(),this.manager)}getDisplayType(){var t;return this.step.data.displayType||((t=this.step.option)==null?void 0:t.displayType)}}class Bn extends et{constructor(t,e,A){super(t,e,A)}selectVariant(t){const e=t.getResource();return St.selectVariant(this.step,{fill:e.color,stroke:e.color,variant:e},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(t){return St.selectVariant(this.step,t,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return St.availableColours(this.step)}setCustomColor(t){var e,A;return((e=this.getCurrentVariant())==null?void 0:e.getColor())!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${(A=this.getCurrentVariant())==null?void 0:A.getColor()}`),St.setCustomColor(t,this.step,this.manager)}getCustomColor(){var e,A,a;((e=this.getCurrentVariant())==null?void 0:e.getColor())!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${(A=this.getCurrentVariant())==null?void 0:A.getColor()}`);const t=(a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.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 hn extends et{constructor(t,e,A){super(t,e,A)}async selectVariant(t){W.selectVariant(this.step,t.getResource(),this.manager,e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:"An issue has occurred with text",messageType:re.Error,stepID:this.step.stepName}]);else{const A=this.manager.getInformationResults().filter(a=>a.stepID!==this.step.stepName);this.manager.setInformationResults(A)}},()=>{})}getAvailableFillColors(){return this.step.data.colorPickerEnabled?W.availableFillColors(this.step):[]}async setFillColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillColor(this.step,t,e,this.manager)}getFillColor(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.color)||"#000000"}getAvailableFillImages(){return W.availableFillImages(this.step)}async setFillImage(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeFillImage(this.step,t,e,this.manager)}getFillImage(){var t;return(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.fillImage}getAlignment(){const t=W.findLayoutElements(this.manager,this.step);return t==null?void 0:t[0].align}setAlignment(t){const e=this.manager.getRegionElements(this.step.stepName);W.changeAlignment(this.step,t,e,this.manager)}setFullTextCustomization(t){var s;const e=((s=this.manager.getStepStorage(this.step.stepName))==null?void 0:s.inputText)||"",A=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",e):e,a=t?A:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:t,text:a,defaultCleared:!1}),this.setText(a)}setText(t){var l;const e={input:t,helperData:{}},A=W.findLayoutElements(this.manager,this.step),a=W.filterUnsupportedCharacters(t,(l=A[0])==null?void 0:l.fontData),i=!!this.step.data&&!!this.step.data.maxLength&&a.length>this.step.data.maxLength;i||(e.input=a);const s=A.length<=0,o=s?{inputText:a,text:a}:{inputText:a};this.manager.updateStorage(this.step.stepName,o);const r=this.manager.getStepStorage(this.step.stepName),c=W.getProcessedInput(a,this.step.data,!!r.customiseAllText);if(s)i||this.manager.updateMetadata(this.step.stepName,{text:c});else{const{command:g,errorData:d,helperData:B}=W.updateInputText(a,A,this.step,this.manager);g&&this.manager.getCommandDispatcher()(g),e.helperData=B,e.errorData=d,!i&&!d&&this.manager.updateMetadata(this.step.stepName,{text:c})}return e}getText(){var A;const t=this.step.data.defaultText,e=this.manager.getStepStorage(this.step.stepName);return t&&(e==null?void 0:e.defaultCleared)!==void 0&&!(e!=null&&e.defaultCleared)?t:((A=this.manager.getStepStorage(this.step.stepName))==null?void 0:A.text)||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){const t=this.manager.getStepStorage(this.step.stepName);if(!(t!=null&&t.defaultCleared)&&this.step.data.deleteDefaultOnFocus){const e=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const A=W.findLayoutElements(this.manager,this.step);return W.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=this.getText();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?W.availableStrokeColors(this.step):[]}getStrokeColor(){var t,e;return((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.strokeColor)==null?void 0:e.browserValue)||"#000000"}async setStrokeColor(t){const e=this.manager.getRegionElements(this.step.stepName);await W.changeStrokeColor(this.step,t,e,this.manager)}}class Cn extends et{constructor(t,e,A){super(t,e,A)}async selectVariant(){}getContent(){return this.step.data.content}}class un extends et{constructor(t,e,A){super(t,e,A)}async selectVariant(){}getPreviewURL(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.videoUrl)||""}async selectVideo(t){return yA.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),t.key,this.manager,this.step)}}class wn extends et{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=this.getText();return t-e.length}getCharacterLimit(){return this.step.data.maxLength}getText(){var t;return((t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.text)||""}setText(t){SA.changeText(this.step,t,this.manager,"",e=>{if(e)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:e,messageType:re.Error,stepID:this.step.stepName}]);else{const A=this.manager.getInformationResults().filter(a=>a.stepID!==this.step.stepName);this.manager.setInformationResults(A)}})}}class de{static get(t,e){switch(e.type){case M.DigitalContent:return new un(t,e,t.getStepTags(e.stepName));case M.Information:return new Cn(t,e,t.getStepTags(e.stepName));case M.Question:return new dn(t,e,t.getStepTags(e.stepName));case M.Text:return new hn(t,e,t.getStepTags(e.stepName));case M.Illustration:return new rn(t,e,t.getStepTags(e.stepName));case M.Picture:return new gn(t,e,t.getStepTags(e.stepName));case M.Shape:return new Bn(t,e,t.getStepTags(e.stepName));case M.Material:return new cn(t,e,t.getStepTags(e.stepName));case M.Model:return new ln(t,e,t.getStepTags(e.stepName));case M.Frame:return new Hn(t,e,t.getStepTags(e.stepName));case M.Module:return new wn(t,e,t.getStepTags(e.stepName));default:throw new L(`Step type ${e.type} not yet supported in Core SDK`)}}}const En=Q.gql`
3158
3159
  fragment CreateDesignTransaction on Transaction {
3159
3160
  id
3160
3161
  designName
@@ -3383,7 +3384,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
3383
3384
  }
3384
3385
  }
3385
3386
  }
3386
- `,Pr=async(n,t)=>{var a;const e=await y.getShadowGraphqlClient().query({query:$i(((a=t==null?void 0:t.assets)==null?void 0:a.metadata)||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const A=e.data.workflows;if(A===void 0||A.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return A.forEach(i=>{i.steps.forEach(s=>{var o,r,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((r=s.option.defaultVariant)!=null&&r.asset&&T.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&T.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(l=>{l.asset&&T.cacheAsset(l.asset),l.thumbnail&&T.cacheAsset(l.thumbnail),l.material&&T.cacheMaterial(l.material)}),bt.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.partner.termsMarkdown}),A},vr=async(n,t)=>{const A=(await t).find(a=>a.id===n);if(!A)throw new Error(`Workflow not found: ${n}`);return A},GA=async(n,t)=>{const e=n.map(o=>bt.get({id:o,options:t})),A=n.filter((o,r)=>e[r]===void 0);if(A.length===0)return Promise.all(e);const a=Pr(A,t),i=A.map(o=>bt.set({id:o,options:t},vr(o,a))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},kr=async(n,t)=>(await GA([n],t))[0],Nr=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:b(),panelId:t.name,name:t.name,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})),br=(n,t)=>{const e=n.workflowState,A=e?JSON.parse(e):void 0;return A?Object.values(A.layouts).map(a=>a.layout):Nr(t.panels)};class Rr{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:Ti})}catch(A){throw console.error(A),new lt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&ni(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 26.7.2"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){dt.setHubUrl(t.hubUrl),dt.setServerUrl(t.serverUrl),dt.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,t.bearerAuthenticationToken&&pa(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return T}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!ii())throw new Error("Application key required to use Flow Service.");return new Yn}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=kn(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(A){return console.error(A),!1}}async authenticateBundleFromLocalStorage(t){var a,i;const e=k.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:Wt.Owner});const A=k.getMap("bundlePartnerIds")||new Map;if(A.has(t)){const s=A.get(t),r=(k.getMap("partnerCustomerIds")||new Map).get(s);if(r&&await this.authenticateCustomerId(r)){const l=(i=(a=this.customer)==null?void 0:a.bundleStakeholders)==null?void 0:i.find(g=>{var d;return((d=g.bundle)==null?void 0:d.id)===t});if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var l,g,d,B,h,C;const e=y.getShadowGraphqlClient(),A=await e.query({query:_i,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 a=A.data.transactions[0];if(!((g=(l=a.product)==null?void 0:l.partner)==null?void 0:g.id))throw new Error(`Unable to read transaction: ${t}`);if(a.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=k.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:Wt.Owner});const o=k.getMap("transactionCustomerIds");if(o!=null&&o.has(t)){const u=o.get(t);if(u&&await this.authenticateCustomerId(u)){const E=((B=(d=this.customer)==null?void 0:d.bundleStakeholders)==null?void 0:B.find(m=>{var f,p;return(p=(f=m.bundle)==null?void 0:f.transactions)==null?void 0:p.some(I=>I.id===t)}))||((C=(h=this.customer)==null?void 0:h.stakeholders)==null?void 0:C.find(m=>{var f;return((f=m.transaction)==null?void 0:f.id)===t}));if(E)return Promise.resolve({success:!0,stakeholderType:E.type})}}const c=(await e.query({query:ts,errorPolicy:"all",variables:{id:a.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${a.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:a.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const a=(await y.getShadowGraphqlClient().query({query:aa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return a.id?a.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var A,a;const e=(a=(A=this.customer)==null?void 0:A.stakeholders)==null?void 0:a.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=y.getShadowGraphqlClient(),a=(await e.query({query:aa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!a.id){const r=(s=(await e.mutate({mutation:Fr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!r)throw new Error("Unable to create customer.");return this.storeCustomer(r),this.customer=r,{customer:r,isAuthenticated:!1}}this.storeCustomer(a);const i=await this.authenticateCustomerId(a.id);return{customer:this.customer||a,isAuthenticated:i}}getCustomer(){return this.customer}async authenticateCustomerId(t){var o;const e=y.getShadowGraphqlClient(),A=k.getMap("customerTokens");if(!(A!=null&&A.has(t)))return!1;const a=A.get(t);if(!a)return!1;const s=(o=(await e.mutate({mutation:Mr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:a}})).data)==null?void 0:o.customerAuthenticate;return s?(this.storeCustomer(s),VA(a),this.customer=s,!0):!1}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:Sr,variables:{emailAddress:t}})}async verifyCode(t,e){var i,s;const a=(i=(await y.getShadowGraphqlClient().mutate({mutation:xr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data)==null?void 0:i.customerVerifyCode;if(a!=null&&a.loginToken){if(!((s=a.partner)!=null&&s.id))throw new Error(`Unable to find customer: ${t}`);const o=k.getMap("customerTokens")||new Map;return o.set(a.id,a.loginToken),k.setMap("customerTokens",o),this.storeCustomer(a),VA(a.loginToken),this.customer={...a,loginToken:void 0},!0}return!1}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Yr,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,A){var c,l,g,d,B;const i=(g=(await y.getShadowGraphqlClient().mutate({mutation:So(((l=(c=A==null?void 0:A.graphql)==null?void 0:c.productCollection)==null?void 0:l.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((h,C)=>({key:h[0],value:h[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:g.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=k.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",s);const o=k.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",o);const r=new ze(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(B=(d=A==null?void 0:A.graphql)==null?void 0:d.productCollection)==null?void 0:B.eagerFetchProducts});return await r.getInitializationPromise(),r}async getExistingBundle(t,e,A,a){var u,w,E,m,f,p,I,D,F,x,Y;const i=k.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),r=((u=Object.entries(localStorage).find(([P,v])=>P.startsWith("CognitoIdentityServiceProvider")&&P.endsWith("idToken")))==null?void 0:u[0])||"",c=localStorage.getItem(r),l={};c&&!fe(c)&&(l.Authorization=`Bearer ${c}`);const g={bundleOwnerId:s,...l,...(w=a==null?void 0:a.graphql)==null?void 0:w.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:Io(((m=(E=a==null?void 0:a.graphql)==null?void 0:E.productCollection)==null?void 0:m.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:g}});if(!((f=d.data)!=null&&f.bundles)||((p=d.data)==null?void 0:p.bundles.length)===0||!((I=d.data)!=null&&I.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const B=(D=d.data)==null?void 0:D.bundles[0],h=k.getMap("bundlePartnerIds")||new Map;h.set(B.id,B.partner.id),k.setMap("bundlePartnerIds",h);const C=new ze(this,B,e,A,s,{additionalHeaders:(F=a==null?void 0:a.graphql)==null?void 0:F.additionalHeaders,eagerFetchProducts:(Y=(x=a==null?void 0:a.graphql)==null?void 0:x.productCollection)==null?void 0:Y.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState});return await C.getInitializationPromise(),C}async duplicateBundle(t,e,A,a){var u,w,E,m,f,p,I,D;const i=(u=k.getMap("bundleOwnerIds"))==null?void 0:u.get(t),o=((w=Object.entries(localStorage).find(([F,x])=>F.startsWith("CognitoIdentityServiceProvider")&&F.endsWith("idToken")))==null?void 0:w[0])||"",r=localStorage.getItem(o),c={};r&&!fe(r)&&(c.Authorization=`Bearer ${r}`);const l={bundleOwnerId:i,...c,...(E=a==null?void 0:a.graphql)==null?void 0:E.additionalHeaders},d=(p=(await y.getShadowGraphqlClient().mutate({mutation:xo(((f=(m=a==null?void 0:a.graphql)==null?void 0:m.productCollection)==null?void 0:f.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:A},context:{headers:l},fetchPolicy:"no-cache"})).data)==null?void 0:p.bundleDuplicate;if(!(d!=null&&d.id))throw new Error("Unable to duplicate bundle");const B=k.getMap("bundlePartnerIds")||new Map;B.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",B);const h=k.getMap("bundleOwnerIds")||new Map;h.set(d.id,d.bundleOwnerId),k.setMap("bundleOwnerIds",h);const C=new ze(this,d,void 0,void 0,d.bundleOwnerId,{eagerFetchProducts:(D=(I=a==null?void 0:a.graphql)==null?void 0:I.productCollection)==null?void 0:D.eagerFetchProducts});return await C.getInitializationPromise(),C}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...A}=t;return(await y.getShadowGraphqlClient().query({query:Jo(e??!1),variables:{...A,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){var i;if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:Do,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const A=t.data.customers[0].bundleStakeholders||[],a=k.getMap("bundlePartnerIds")||new Map;return A.forEach(s=>{var o,r;(o=s.bundle)!=null&&o.id&&((r=s.bundle.partner)!=null&&r.id)&&a.set(s.bundle.id,s.bundle.partner.id)}),k.setMap("bundlePartnerIds",a),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),a=A[0];return e&&await a.getWorkflowManager().injectIntoPreviewService(e(a.getWorkflowManager().getWorkflow())),A[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new lt("No options provided!");const A=y.getShadowGraphqlClient(),a=async p=>{var x,Y,P;if(p.length===0)return[];const I=p.map(v=>v.option.transactionId),D=await A.query({query:Gi,variables:{ids:I},errorPolicy:"all",fetchPolicy:"no-cache"}),F=D.data.transactions;if(F.length!==p.length){const v=((Y=(x=D.errors)==null?void 0:x[0])==null?void 0:Y.message)||"Unknown error";throw new lt(`Not all transactions were found: ${v}`)}return!this.activeIntegration&&((P=F[0].integrationProduct)!=null&&P.integration)&&(this.activeIntegration=Promise.resolve(F[0].integrationProduct.integration)),F.map((v,H)=>{var V;return{transaction:v,workflowId:v.workflowId,readOnly:((V=p.find(j=>j.option.transactionId===v.id))==null?void 0:V.option.readOnly)??!1,index:p[H].index}})},i=async p=>{var F,x,Y;if(p.length===0)return[];const I=await A.mutate({mutation:Ui,variables:{inputs:p.map(P=>({integrationProductId:P.option.type==="integration"?P.option.integrationProductId:void 0,externalIntegrationId:P.option.type==="external"?P.option.externalIntegrationId:void 0,externalProductId:P.option.type==="external"?P.option.externalProductId:void 0,workflowId:P.option.workflowId,designName:P.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),D=(F=I.data)==null?void 0:F.transactionCreateMany;if(!D||D.length===0){const P=((Y=(x=I.errors)==null?void 0:x[0])==null?void 0:Y.message)||"Unknown error";throw new lt(`Failed to create transactions: ${P}`)}return D.map((P,v)=>({transaction:P,workflowId:P.workflowId,readOnly:!1,index:p[v].index}))},s=t.map((p,I)=>({option:p,index:I})),o=s.filter(p=>p.option.type==="transaction"),r=s.filter(p=>p.option.type==="integration"||p.option.type==="external"),c=JA(o,10),l=JA(r,10),g=(await Promise.all([...c.map(a),...l.map(i)])).flat(),d=[...new Set(g.map(p=>p.workflowId))],B=await GA(d,e),h=new Map(B.map(p=>[p.id,p])),C=k.getMap("transactionOwnerIds")||new Map,u=g.map(async p=>{var V;const{transaction:I,workflowId:D,readOnly:F,index:x}=p,Y=h.get(D),P=t[x];!C.get(I.id)&&I.transactionOwnerId&&C.set(I.id,I.transactionOwnerId);const v=C.get(I.id)||void 0,H={product:I.product,transaction:I,layouts:[],singleVariantsRenderable:(V=P==null?void 0:P.workflowConfiguration)==null?void 0:V.singleVariantsRenderable,stateMutationFunc:F?async()=>{throw new L("State mutation is forbidden in read only mode!")}:async j=>this.updateTransactionState({...j,context:{transactionOwnerId:v,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),readOnly:F,workflow:Y,isReloadedTransaction:P.type==="transaction"};if(P.type==="transaction"&&I.workflowState){const j=JSON.parse(I.workflowState);H.layouts=Object.values(j.layouts||{}).map(At=>At.layout),await AA(j),H.reloadedState=j}else if(!F&&P.workflowState){const j=JSON.parse(P.workflowState);H.layouts=Object.values(j.layouts||{}).map(At=>At.layout),await AA(j),H.reloadedState=j}else H.layouts=br(H.transaction,H.workflow);return H.renderableContextService=new Br(H.layouts),H.delayWorkflowStateSync=!0,{experienceOptions:H,index:x,options:P}}),w=await Promise.all(u);k.setMap("transactionOwnerIds",C);const m=w.sort((p,I)=>p.index-I.index).map(async p=>{const{experienceOptions:I,options:D}=p,F=new In(this,I);return await F.getWorkflowManager().getInitializationPromise(),D.type!=="transaction"&&this.customer&&await F.attachCustomerDetails({email:this.customer.emailAddress}),F}),f=await Promise.all(m);return f.forEach(p=>p.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),f}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t){var i,s;const a=(i=(await y.getShadowGraphqlClient().query({query:zi,variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:i.integrationProducts;if(!a||a.length===0||!((s=a[0])!=null&&s.id))throw new Error("Integration product not found.");return new rA(a[0])}async getIntegrationProductFromExternalIds(t,e){var s;const i=(s=(await y.getShadowGraphqlClient().query({query:ji,variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProductFromExternalIds;if(!(i!=null&&i.id))throw new Error("Integration product not found.");return new rA(i)}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,a=await y.getShadowGraphqlClient().query({query:Oi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:A}});if(!a.data.transactions||a.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return a.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:is,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 kn=async n=>(await y.getShadowGraphqlClient().query({query:As,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}}})).data.currentIntegration,Hr=async n=>{const e=await y.getShadowGraphqlClient().query({query:Li,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Ur=async(n,t)=>{var A;return(A=(await y.getShadowGraphqlClient().query({query:es,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data)==null?void 0:A.marketplaceThemeInstallConfiguration},Gr=async n=>{var e,A,a;return(a=(A=(e=(await y.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",variables:{id:n}})).data)==null?void 0:e.bundles)==null?void 0:A[0])==null?void 0:a.marketplaceThemeInstallConfiguration},Tr=async n=>{var e,A,a;return(a=(A=(e=(await y.getShadowGraphqlClient().query({query:as,errorPolicy:"all",variables:{id:n}})).data)==null?void 0:e.transactions)==null?void 0:A[0])==null?void 0:a.marketplaceThemeInstallConfiguration};function Nn(n,t,e,A){const a=e.width*n.zoom,i=e.height*n.zoom;if(A){const o=n,r=Math.max(t.width/e.width,t.height/e.height);o.zoom=Math.max(r,n.zoom);const c=e.width*o.zoom,l=e.height*o.zoom;return o.x=Be(n.x,t.width-c,0),o.y=Be(n.y,t.height-l,0),o}const s=n;return s.x=Be(s.x,-a,t.width),s.y=Be(s.y,-i,t.height),s}function Be(n,t,e){return Math.min(Math.max(n,t),e)}class bn{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=oa(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 a=A;if(a.currentFrameSources){let i=!1;for(let s=0;s<a.currentFrameSources.length;s++){const o=a.currentFrameSources[s],r=await oe(o),c=this.frameData?this.frameData[s]:void 0;sa(r,c)||(this.frameData||(this.frameData=new Array(a.currentFrameSources.length)),this.frameData[s]=r,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(s=>s(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 a=Mt.get(e);a&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[A]=a)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=Ya(this.imageData.svg,this.imageData.colors||{},!1);return gA(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,A,a){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((s,o)=>{const r=(e[o]-this.offsets[o].x)/this.offsets[o].zoom,c=(A[o]-this.offsets[o].y)/this.offsets[o].zoom,l=e[o]-r*t[o],g=A[o]-c*t[o];return{x:l,y:g,zoom:this.imageData.width*t[o]/this.imageData.width}});this.updateOffsets(i,a),this.onZoomChangeListeners.forEach(s=>s(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 a=this.imageData;if(!a||!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((s,o)=>!(t[o].x===s.x&&t[o].y===s.y&&t[o].zoom===s.zoom))&&!A){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=Nn(t[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,a,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,a,i){if(!A||A.length===0||A.some(o=>!o))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 s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,r)=>{s(new G([new Ls(o,e,t[r]),new Os(o,a.useThreshold,a.invertThreshold,a.threshold,a.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,a)=>{const i=Math.max(A.width/t.width,A.height/t.height);this.forceImageCover?(this.minZoomScale[a]=i,this.maxZoomScale[a]=i*2.5):(this.minZoomScale[a]=i/10,this.maxZoomScale[a]=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]=pA(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Jr{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 Rn=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Rn||{});class Hn extends et{constructor(t,e,A){super(t,e,A);const a=e.data;this.frameService=new bn(a.forceImageCover,a.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return rt.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){var a;if(await rt.selectImage(this.step,t,this.manager,A),e){const i=((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Qe.BackgroundRemover)}async canRemoveBackground(){var t,e,A,a;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((a=(A=this.frameService)==null?void 0:A.getImageData())!=null&&a.svg)}async removeBackgroundFromImageSelection(t=!0){var i;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 T.removeBackgroundFromAsset(e);t&&await rt.selectImage(this.step,A,this.manager,!1);const a=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,backgroundRemovedAssetKey:A.key,useOriginalAsset:!t}}),A}changeColors(t){rt.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?rt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await st(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return rt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,A,a){return a&&a.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(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.originalAssetKey;if(t)return T.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.backgroundRemovedAssetKey;if(t)return T.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var a;const e=((a=this.getFrameStepStorage())==null?void 0:a.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 i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Lr=Q.gql`
3387
+ `,Pr=async(n,t)=>{var a;const e=await y.getShadowGraphqlClient().query({query:$i(((a=t==null?void 0:t.assets)==null?void 0:a.metadata)||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const A=e.data.workflows;if(A===void 0||A.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return A.forEach(i=>{i.steps.forEach(s=>{var o,r,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((r=s.option.defaultVariant)!=null&&r.asset&&T.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&T.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(l=>{l.asset&&T.cacheAsset(l.asset),l.thumbnail&&T.cacheAsset(l.thumbnail),l.material&&T.cacheMaterial(l.material)}),bt.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.partner.termsMarkdown}),A},vr=async(n,t)=>{const A=(await t).find(a=>a.id===n);if(!A)throw new Error(`Workflow not found: ${n}`);return A},GA=async(n,t)=>{const e=n.map(o=>bt.get({id:o,options:t})),A=n.filter((o,r)=>e[r]===void 0);if(A.length===0)return Promise.all(e);const a=Pr(A,t),i=A.map(o=>bt.set({id:o,options:t},vr(o,a))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},kr=async(n,t)=>(await GA([n],t))[0],Nr=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:b(),panelId:t.name,name:t.name,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})),br=(n,t)=>{const e=n.workflowState,A=e?JSON.parse(e):void 0;return A?Object.values(A.layouts).map(a=>a.layout):Nr(t.panels)};class Rr{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:Ti})}catch(A){throw console.error(A),new lt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&ni(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 26.7.3"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){dt.setHubUrl(t.hubUrl),dt.setServerUrl(t.serverUrl),dt.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,t.bearerAuthenticationToken&&pa(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return T}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!ii())throw new Error("Application key required to use Flow Service.");return new Yn}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=kn(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(A){return console.error(A),!1}}async authenticateBundleFromLocalStorage(t){var a,i;const e=k.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:Wt.Owner});const A=k.getMap("bundlePartnerIds")||new Map;if(A.has(t)){const s=A.get(t),r=(k.getMap("partnerCustomerIds")||new Map).get(s);if(r&&await this.authenticateCustomerId(r)){const l=(i=(a=this.customer)==null?void 0:a.bundleStakeholders)==null?void 0:i.find(g=>{var d;return((d=g.bundle)==null?void 0:d.id)===t});if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var l,g,d,B,h,C;const e=y.getShadowGraphqlClient(),A=await e.query({query:_i,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 a=A.data.transactions[0];if(!((g=(l=a.product)==null?void 0:l.partner)==null?void 0:g.id))throw new Error(`Unable to read transaction: ${t}`);if(a.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=k.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:Wt.Owner});const o=k.getMap("transactionCustomerIds");if(o!=null&&o.has(t)){const u=o.get(t);if(u&&await this.authenticateCustomerId(u)){const E=((B=(d=this.customer)==null?void 0:d.bundleStakeholders)==null?void 0:B.find(m=>{var f,p;return(p=(f=m.bundle)==null?void 0:f.transactions)==null?void 0:p.some(I=>I.id===t)}))||((C=(h=this.customer)==null?void 0:h.stakeholders)==null?void 0:C.find(m=>{var f;return((f=m.transaction)==null?void 0:f.id)===t}));if(E)return Promise.resolve({success:!0,stakeholderType:E.type})}}const c=(await e.query({query:ts,errorPolicy:"all",variables:{id:a.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${a.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:a.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const a=(await y.getShadowGraphqlClient().query({query:aa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return a.id?a.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var A,a;const e=(a=(A=this.customer)==null?void 0:A.stakeholders)==null?void 0:a.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=y.getShadowGraphqlClient(),a=(await e.query({query:aa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!a.id){const r=(s=(await e.mutate({mutation:Fr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!r)throw new Error("Unable to create customer.");return this.storeCustomer(r),this.customer=r,{customer:r,isAuthenticated:!1}}this.storeCustomer(a);const i=await this.authenticateCustomerId(a.id);return{customer:this.customer||a,isAuthenticated:i}}getCustomer(){return this.customer}async authenticateCustomerId(t){var o;const e=y.getShadowGraphqlClient(),A=k.getMap("customerTokens");if(!(A!=null&&A.has(t)))return!1;const a=A.get(t);if(!a)return!1;const s=(o=(await e.mutate({mutation:Mr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:a}})).data)==null?void 0:o.customerAuthenticate;return s?(this.storeCustomer(s),VA(a),this.customer=s,!0):!1}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:Sr,variables:{emailAddress:t}})}async verifyCode(t,e){var i,s;const a=(i=(await y.getShadowGraphqlClient().mutate({mutation:xr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data)==null?void 0:i.customerVerifyCode;if(a!=null&&a.loginToken){if(!((s=a.partner)!=null&&s.id))throw new Error(`Unable to find customer: ${t}`);const o=k.getMap("customerTokens")||new Map;return o.set(a.id,a.loginToken),k.setMap("customerTokens",o),this.storeCustomer(a),VA(a.loginToken),this.customer={...a,loginToken:void 0},!0}return!1}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Yr,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,A){var c,l,g,d,B;const i=(g=(await y.getShadowGraphqlClient().mutate({mutation:So(((l=(c=A==null?void 0:A.graphql)==null?void 0:c.productCollection)==null?void 0:l.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((h,C)=>({key:h[0],value:h[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:g.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=k.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",s);const o=k.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",o);const r=new ze(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(B=(d=A==null?void 0:A.graphql)==null?void 0:d.productCollection)==null?void 0:B.eagerFetchProducts});return await r.getInitializationPromise(),r}async getExistingBundle(t,e,A,a){var u,w,E,m,f,p,I,D,F,x,Y;const i=k.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),r=((u=Object.entries(localStorage).find(([P,v])=>P.startsWith("CognitoIdentityServiceProvider")&&P.endsWith("idToken")))==null?void 0:u[0])||"",c=localStorage.getItem(r),l={};c&&!fe(c)&&(l.Authorization=`Bearer ${c}`);const g={bundleOwnerId:s,...l,...(w=a==null?void 0:a.graphql)==null?void 0:w.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:Io(((m=(E=a==null?void 0:a.graphql)==null?void 0:E.productCollection)==null?void 0:m.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:g}});if(!((f=d.data)!=null&&f.bundles)||((p=d.data)==null?void 0:p.bundles.length)===0||!((I=d.data)!=null&&I.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const B=(D=d.data)==null?void 0:D.bundles[0],h=k.getMap("bundlePartnerIds")||new Map;h.set(B.id,B.partner.id),k.setMap("bundlePartnerIds",h);const C=new ze(this,B,e,A,s,{additionalHeaders:(F=a==null?void 0:a.graphql)==null?void 0:F.additionalHeaders,eagerFetchProducts:(Y=(x=a==null?void 0:a.graphql)==null?void 0:x.productCollection)==null?void 0:Y.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState});return await C.getInitializationPromise(),C}async duplicateBundle(t,e,A,a){var u,w,E,m,f,p,I,D;const i=(u=k.getMap("bundleOwnerIds"))==null?void 0:u.get(t),o=((w=Object.entries(localStorage).find(([F,x])=>F.startsWith("CognitoIdentityServiceProvider")&&F.endsWith("idToken")))==null?void 0:w[0])||"",r=localStorage.getItem(o),c={};r&&!fe(r)&&(c.Authorization=`Bearer ${r}`);const l={bundleOwnerId:i,...c,...(E=a==null?void 0:a.graphql)==null?void 0:E.additionalHeaders},d=(p=(await y.getShadowGraphqlClient().mutate({mutation:xo(((f=(m=a==null?void 0:a.graphql)==null?void 0:m.productCollection)==null?void 0:f.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:A},context:{headers:l},fetchPolicy:"no-cache"})).data)==null?void 0:p.bundleDuplicate;if(!(d!=null&&d.id))throw new Error("Unable to duplicate bundle");const B=k.getMap("bundlePartnerIds")||new Map;B.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",B);const h=k.getMap("bundleOwnerIds")||new Map;h.set(d.id,d.bundleOwnerId),k.setMap("bundleOwnerIds",h);const C=new ze(this,d,void 0,void 0,d.bundleOwnerId,{eagerFetchProducts:(D=(I=a==null?void 0:a.graphql)==null?void 0:I.productCollection)==null?void 0:D.eagerFetchProducts});return await C.getInitializationPromise(),C}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...A}=t;return(await y.getShadowGraphqlClient().query({query:Jo(e??!1),variables:{...A,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){var i;if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:Do,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const A=t.data.customers[0].bundleStakeholders||[],a=k.getMap("bundlePartnerIds")||new Map;return A.forEach(s=>{var o,r;(o=s.bundle)!=null&&o.id&&((r=s.bundle.partner)!=null&&r.id)&&a.set(s.bundle.id,s.bundle.partner.id)}),k.setMap("bundlePartnerIds",a),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),a=A[0];return e&&await a.getWorkflowManager().injectIntoPreviewService(e(a.getWorkflowManager().getWorkflow())),A[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new lt("No options provided!");const A=y.getShadowGraphqlClient(),a=async p=>{var x,Y,P;if(p.length===0)return[];const I=p.map(v=>v.option.transactionId),D=await A.query({query:Gi,variables:{ids:I},errorPolicy:"all",fetchPolicy:"no-cache"}),F=D.data.transactions;if(F.length!==p.length){const v=((Y=(x=D.errors)==null?void 0:x[0])==null?void 0:Y.message)||"Unknown error";throw new lt(`Not all transactions were found: ${v}`)}return!this.activeIntegration&&((P=F[0].integrationProduct)!=null&&P.integration)&&(this.activeIntegration=Promise.resolve(F[0].integrationProduct.integration)),F.map((v,H)=>{var V;return{transaction:v,workflowId:v.workflowId,readOnly:((V=p.find(j=>j.option.transactionId===v.id))==null?void 0:V.option.readOnly)??!1,index:p[H].index}})},i=async p=>{var F,x,Y;if(p.length===0)return[];const I=await A.mutate({mutation:Ui,variables:{inputs:p.map(P=>({integrationProductId:P.option.type==="integration"?P.option.integrationProductId:void 0,externalIntegrationId:P.option.type==="external"?P.option.externalIntegrationId:void 0,externalProductId:P.option.type==="external"?P.option.externalProductId:void 0,workflowId:P.option.workflowId,designName:P.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),D=(F=I.data)==null?void 0:F.transactionCreateMany;if(!D||D.length===0){const P=((Y=(x=I.errors)==null?void 0:x[0])==null?void 0:Y.message)||"Unknown error";throw new lt(`Failed to create transactions: ${P}`)}return D.map((P,v)=>({transaction:P,workflowId:P.workflowId,readOnly:!1,index:p[v].index}))},s=t.map((p,I)=>({option:p,index:I})),o=s.filter(p=>p.option.type==="transaction"),r=s.filter(p=>p.option.type==="integration"||p.option.type==="external"),c=JA(o,10),l=JA(r,10),g=(await Promise.all([...c.map(a),...l.map(i)])).flat(),d=[...new Set(g.map(p=>p.workflowId))],B=await GA(d,e),h=new Map(B.map(p=>[p.id,p])),C=k.getMap("transactionOwnerIds")||new Map,u=g.map(async p=>{var V;const{transaction:I,workflowId:D,readOnly:F,index:x}=p,Y=h.get(D),P=t[x];!C.get(I.id)&&I.transactionOwnerId&&C.set(I.id,I.transactionOwnerId);const v=C.get(I.id)||void 0,H={product:I.product,transaction:I,layouts:[],singleVariantsRenderable:(V=P==null?void 0:P.workflowConfiguration)==null?void 0:V.singleVariantsRenderable,stateMutationFunc:F?async()=>{throw new L("State mutation is forbidden in read only mode!")}:async j=>this.updateTransactionState({...j,context:{transactionOwnerId:v,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),readOnly:F,workflow:Y,isReloadedTransaction:P.type==="transaction"};if(P.type==="transaction"&&I.workflowState){const j=JSON.parse(I.workflowState);H.layouts=Object.values(j.layouts||{}).map(At=>At.layout),await AA(j),H.reloadedState=j}else if(!F&&P.workflowState){const j=JSON.parse(P.workflowState);H.layouts=Object.values(j.layouts||{}).map(At=>At.layout),await AA(j),H.reloadedState=j}else H.layouts=br(H.transaction,H.workflow);return H.renderableContextService=new Br(H.layouts),H.delayWorkflowStateSync=!0,{experienceOptions:H,index:x,options:P}}),w=await Promise.all(u);k.setMap("transactionOwnerIds",C);const m=w.sort((p,I)=>p.index-I.index).map(async p=>{const{experienceOptions:I,options:D}=p,F=new In(this,I);return await F.getWorkflowManager().getInitializationPromise(),D.type!=="transaction"&&this.customer&&await F.attachCustomerDetails({email:this.customer.emailAddress}),F}),f=await Promise.all(m);return f.forEach(p=>p.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),f}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t){var i,s;const a=(i=(await y.getShadowGraphqlClient().query({query:zi,variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:i.integrationProducts;if(!a||a.length===0||!((s=a[0])!=null&&s.id))throw new Error("Integration product not found.");return new rA(a[0])}async getIntegrationProductFromExternalIds(t,e){var s;const i=(s=(await y.getShadowGraphqlClient().query({query:ji,variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProductFromExternalIds;if(!(i!=null&&i.id))throw new Error("Integration product not found.");return new rA(i)}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,a=await y.getShadowGraphqlClient().query({query:Oi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:A}});if(!a.data.transactions||a.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return a.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:is,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 kn=async n=>(await y.getShadowGraphqlClient().query({query:As,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}}})).data.currentIntegration,Hr=async n=>{const e=await y.getShadowGraphqlClient().query({query:Li,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Ur=async(n,t)=>{var A;return(A=(await y.getShadowGraphqlClient().query({query:es,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data)==null?void 0:A.marketplaceThemeInstallConfiguration},Gr=async n=>{var e,A,a;return(a=(A=(e=(await y.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",variables:{id:n}})).data)==null?void 0:e.bundles)==null?void 0:A[0])==null?void 0:a.marketplaceThemeInstallConfiguration},Tr=async n=>{var e,A,a;return(a=(A=(e=(await y.getShadowGraphqlClient().query({query:as,errorPolicy:"all",variables:{id:n}})).data)==null?void 0:e.transactions)==null?void 0:A[0])==null?void 0:a.marketplaceThemeInstallConfiguration};function Nn(n,t,e,A){const a=e.width*n.zoom,i=e.height*n.zoom;if(A){const o=n,r=Math.max(t.width/e.width,t.height/e.height);o.zoom=Math.max(r,n.zoom);const c=e.width*o.zoom,l=e.height*o.zoom;return o.x=Be(n.x,t.width-c,0),o.y=Be(n.y,t.height-l,0),o}const s=n;return s.x=Be(s.x,-a,t.width),s.y=Be(s.y,-i,t.height),s}function Be(n,t,e){return Math.min(Math.max(n,t),e)}class bn{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=oa(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 a=A;if(a.currentFrameSources){let i=!1;for(let s=0;s<a.currentFrameSources.length;s++){const o=a.currentFrameSources[s],r=await oe(o),c=this.frameData?this.frameData[s]:void 0;sa(r,c)||(this.frameData||(this.frameData=new Array(a.currentFrameSources.length)),this.frameData[s]=r,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(s=>s(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 a=Mt.get(e);a&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[A]=a)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=Ya(this.imageData.svg,this.imageData.colors||{},!1);return gA(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,A,a){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((s,o)=>{const r=(e[o]-this.offsets[o].x)/this.offsets[o].zoom,c=(A[o]-this.offsets[o].y)/this.offsets[o].zoom,l=e[o]-r*t[o],g=A[o]-c*t[o];return{x:l,y:g,zoom:this.imageData.width*t[o]/this.imageData.width}});this.updateOffsets(i,a),this.onZoomChangeListeners.forEach(s=>s(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 a=this.imageData;if(!a||!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((s,o)=>!(t[o].x===s.x&&t[o].y===s.y&&t[o].zoom===s.zoom))&&!A){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=Nn(t[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,a,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,a,i){if(!A||A.length===0||A.some(o=>!o))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 s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,r)=>{s(new G([new Ls(o,e,t[r]),new Os(o,a.useThreshold,a.invertThreshold,a.threshold,a.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,a)=>{const i=Math.max(A.width/t.width,A.height/t.height);this.forceImageCover?(this.minZoomScale[a]=i,this.maxZoomScale[a]=i*2.5):(this.minZoomScale[a]=i/10,this.maxZoomScale[a]=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]=pA(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Jr{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 Rn=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Rn||{});class Hn extends et{constructor(t,e,A){super(t,e,A);const a=e.data;this.frameService=new bn(a.forceImageCover,a.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return rt.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){var a;if(await rt.selectImage(this.step,t,this.manager,A),e){const i=((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Qe.BackgroundRemover)}async canRemoveBackground(){var t,e,A,a;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((a=(A=this.frameService)==null?void 0:A.getImageData())!=null&&a.svg)}async removeBackgroundFromImageSelection(t=!0){var i;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 T.removeBackgroundFromAsset(e);t&&await rt.selectImage(this.step,A,this.manager,!1);const a=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,backgroundRemovedAssetKey:A.key,useOriginalAsset:!t}}),A}changeColors(t){rt.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?rt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await st(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return rt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,A,a){return a&&a.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(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.originalAssetKey;if(t)return T.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.backgroundRemovedAssetKey;if(t)return T.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var a;const e=((a=this.getFrameStepStorage())==null?void 0:a.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 i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Lr=Q.gql`
3387
3388
  query GetLoggedInCustomer($email: String!) {
3388
3389
  customer(emailAddress: $email) {
3389
3390
  id