@spiffcommerce/core 44.5.6-alpha.0 → 44.5.6-alpha.1

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.
@@ -2652,7 +2652,7 @@ Minimum version required to store current data is: `+q+`.
2652
2652
  id
2653
2653
  }
2654
2654
  }
2655
- `,P9=(r,e)=>e&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).sort().reduce((t,n)=>(t[n]=e[n],t),{}):e,D9=r=>{for(const e of Object.values(r.layouts).map(t=>t.elements).flat())e.type==="illustration"&&(delete e.cachedObjectURL,e.src&&delete e.svg),e.type==="frame"&&delete e.pattern?.svg;return vI(r,"__typename"),r},vI=(r,e)=>{if(!(typeof r!="object"||r===null))for(const t in r)t===e?delete r[t]:vI(r[t],e)};var Jf=(r=>(r.Error="Error",r.Warning="Warning",r.Info="Info",r))(Jf||{});const R9=1e3;class EE extends jg{constructor(e){super(),this.update=e}async execute(){await this.update(),await new Promise(e=>{window.setTimeout(()=>{e()},R9)})}}const O9=r=>r.sort((e,t)=>e.index-t.index).map(e=>({id:hr(),panelId:e.name,name:e.name,title:e.title,index:e.index,createdAt:new Date,updatedAt:new Date,transparentBackground:e.transparentBackground,height:e.height,width:e.width,previewRegion:e.previewRegion,useEditableArea:e.useEditableArea,editableArea:e.editableArea})),kE=(r,e)=>{const t=r.workflowState,n=t?JSON.parse(t):void 0;return n?Object.values(n.layouts).map(i=>i.layout):O9(e.panels)},af=class af{constructor(e,t,n,i,a,s=!1,o,l=!1,u=!1,c=!1){this.workflowStatePromiseQueue=new Gg(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async d=>{this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.reloadedState?this.layouts=Object.values(this.reloadedState.layouts||{}).map(g=>g.layout):d?this.layouts=kE(this.experience.getTransaction(),d):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new zU(this.layouts),this.renderableContextService.setWorkflowManager(this),d.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(d),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(g=>{throw this.initialized=!1,new Error(g)}),this.initializationPromise.finally(()=>this.commandContext.registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()})),h&&await this.injectIntoPreviewService(h,!0)},this.renderLayouts=()=>{if(!this.previewService)return;const d=this.getCommandContext().getAllLayouts(),h=this.getLayoutPreviewService()?.getAll();if(h)for(const[,g]of h)g.render(d)},this.experience=e,this.client=t,this.updateTransaction=n,this.graphQlClient=i,this.reloadedState=a,this.readOnly=s,this.singleVariantsRenderable=u,this.commandContext=new WF,this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.modelContainer=o,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.isReloadedTransaction=l,c&&(this.workflowStatePromiseQueue.enabled=!1);const f=this.experience.getWorkflow();f&&this.setWorkflow(f)}async updateWorkflowConfiguration(e,t){t.panels&&await this.updatePanels(t.panels),t.steps&&await this.updateSteps(t.steps),t.stepGroups&&await this.updateScenes(t.stepGroups),this.renderLayouts(),await this.onSelectionChange()}async updatePanels(e){const t=new Map(this.layouts.map(a=>[a.panelId,a])),n=kE(this.experience.getTransaction(),{...this.experience.getWorkflow(),panels:e}),i=new Map;for(const a of n){const s=t.get(a.panelId);s?i.set(s.id,{...s,...a,id:s.id}):i.set(a.id,a)}this.layouts=Array.from(i.values()),this.commandContext.updateLayouts(this.layouts),this.renderableContextService&&this.renderableContextService.updateLayouts(this.layouts)}async updateSteps(e){const t=new Set(Object.keys(this.stepSelections)),n=new Set(e.map(i=>i.stepName));for(const i of t)n.has(i)||this.clearStepState(i);for(const i of e)t.has(i.stepName)&&await this.stepNeedsReinitialization(i)&&(this.stepInitialised[i.stepName]=!1);await this.ensureStepsAreLoaded(),await this.remapRegionElements(e)}clearStepState(e){delete this.stepSelections[e],delete this.stepMetadata[e],delete this.storage[e],delete this.stepElements[e],delete this.stepInitialised[e],delete this.stepSpecificServices[e],delete this.mandatorySteps[e],this.validationErrors.steps.delete(e)}async stepNeedsReinitialization(e){if("regions"in e.data){const n=this.stepElements[e.stepName]||[],i=e.data.regions,a=new Set(n.map(o=>o.region?.panelId).filter(Boolean)),s=new Set(i.map(o=>o.panelId));if(a.size!==s.size)return!0;for(const o of s)if(!a.has(o))return!0;for(let o=0;o<i.length;o++){const l=n[o]?.region,u=i[o];if(!l||l.width!==u.width||l.height!==u.height||l.top!==u.top||l.left!==u.left||l.panelId!==u.panelId)return!0}}return this.experience.getWorkflow()?.steps.find(n=>n.stepName===e.stepName)?.relevantPanelName!==e.relevantPanelName}async remapRegionElements(e){const t=[];for(const n of e){if(!("regions"in n.data))continue;const i=n.data.regions,a=this.stepElements[n.stepName]||[];for(let s=0;s<a.length&&s<i.length;s++){const o=a[s],l=i[s];if(o.region?.panelId!==l.panelId){const u=this.layouts.find(c=>c.panelId===l.panelId)?.id;u&&t.push(new eI(o.id,l,u))}}}t.length>0&&this.commandContext.apply(new In(t),!0)}async updateScenes(e){const t=this.experience.getWorkflow();t&&(this.allScenes=T0({...t,stepGroups:e}),await this.onSelectionChange())}getTemplatingContext(){const e=this.experience.getTransaction().recipient,t={recipient:e};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(n=>{const i=n.uniqueIdentifier??n.title??"";n.type===Qd.FirstName?t[i]=e?.firstName:n.type===Qd.LastName?t[i]=e?.lastName:n.type===Qd.Custom&&(n.customFieldIndex===1?t[i]=e?.customField1:n.customFieldIndex===2?t[i]=e?.customField2:n.customFieldIndex===3?t[i]=e?.customField3:n.customFieldIndex===4?t[i]=e?.customField4:n.customFieldIndex===5&&(t[i]=e?.customField5),n.option&&(t[i]=n.option.variants?.find(a=>a.id===t[i])?.name))}),t}async updateRecipient(e,t,n,i,a,s,o,l,u,c,f,d,h,g,v,y,A,C){const S=this.experience.getTransaction();if(S.recipient?.id)this.experience.getTransaction().recipient={id:S.recipient.id,firstName:e??S.recipient.firstName,lastName:t??S.recipient.lastName,address:n??S.recipient.address,suburb:i??S.recipient.suburb,state:a??S.recipient.state,email:s??S.recipient.email,postalCode:o??S.recipient.postalCode,country:l??S.recipient.country,mobile:u??S.recipient.mobile,company:c??S.recipient.company,apartment:f??S.recipient.apartment,customField1:d??S.recipient.customField1,customField2:h??S.recipient.customField2,customField3:g??S.recipient.customField3,customField4:v??S.recipient.customField4,customField5:y??S.recipient.customField5,conversionConfigurationId:A||S.recipient.conversionConfigurationId},this.experience.callEvent(yg.RecipientChanged),await this.graphQlClient().mutate({mutation:E9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:S.recipient.id,firstName:e||S.recipient.firstName,lastName:t||S.recipient.lastName,address:n||S.recipient.address,suburb:i||S.recipient.suburb,state:a||S.recipient.state,email:s||S.recipient.email,postalCode:o||S.recipient.postalCode,country:l||S.recipient.country,mobile:u||S.recipient.mobile,company:c||S.recipient.company,apartment:f||S.recipient.apartment,customField1:d||S.recipient.customField1,customField2:h||S.recipient.customField2,customField3:g||S.recipient.customField3,customField4:v||S.recipient.customField4,customField5:y||S.recipient.customField5,conversionConfigurationId:A||S.recipient.conversionConfigurationId,prevalidated:C}});else{const F=await this.graphQlClient().mutate({mutation:S9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:e,lastName:t,address:n,suburb:i,state:a,email:s,postalCode:o,country:l,mobile:u,company:c,apartment:f,customField1:d,customField2:h,customField3:g,customField4:v,customField5:y,conversionConfigurationId:A}});S.recipient={id:F?.data?.recipientCreate?.id,firstName:e,lastName:t,address:n,suburb:i,state:a,email:s,postalCode:o,country:l,mobile:u,company:c,apartment:f,customField1:d,customField2:h,customField3:g,customField4:v,customField5:y,conversionConfigurationId:A},this.experience.callEvent(yg.RecipientChanged),await this.graphQlClient().mutate({mutation:k9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,recipientId:F.data?.recipientCreate?.id},context:{transactionOwnerId:this.experience.getTransaction().transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(F=>F(this.experience.getTransaction().recipient))}async fetchConversionConfiguration(){const e=this.experience.getTransaction().recipient;if(e?.conversionConfigurationId&&!this.recipientConversionConfiguration){const t=af.configurationPromiseMap.get(e.conversionConfigurationId);if(t)this.recipientConversionConfiguration=await t;else{const i=(async()=>(await this.graphQlClient().query({query:N3,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e.conversionConfigurationId}})).data.conversionConfiguration)();af.configurationPromiseMap.set(e.conversionConfigurationId,i),this.recipientConversionConfiguration=await i}}}async initializeDefaultWorkflowState(e){const t=()=>{const c=e.finalizeStepConfig;if(!c)return;const f=c.lookAtAnimation,d=c.modelAnimation;f&&this.previewService?.executeCameraAnimation(f),d&&this.modelContainer?.executeAnimation(d)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(c=>{this.storage[c.stepName]=c.storage||{}});const n=await this.getInitialOptionIds(this.reloadedState?.serializableWorkflow?.steps.reduce((c,f)=>(f.selectedVariants?.length&&(c[f.stepName]={selectedVariants:f.selectedVariants.map(d=>({id:d.id}))}),c),{})),i=ct.getOptions(Array.from(n)),a=this.fetchConversionConfiguration();await Promise.all([i,a]),this.allScenes=T0(e);const o=(await Ja(this.allScenes,this.stepSelections)).map(c=>c.silentSteps).flat(),{stepElements:l,commands:u}=await this.stepElementsForIntroducedSilentSteps(o,!!this.reloadedState);this.commandContext.apply(new In(u),!0),this.stepElements={...this.stepElements,...l},await this.ensureStepsAreLoaded(),this.isReloadedTransaction||this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&t()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(e){this.workflowStatePromiseQueue.enabled=e}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}async getInitialOptionIds(e){const t=new Set,n=this.experience.getWorkflow();if(!n)return t;const i=T0(n),a={...e};let s=-1;for(;;){const u=(await Ja(i,a)).flatMap(c=>c.renderableSteps);if(u.length===s)break;s=u.length;for(const c of u){if(a[c.stepName])continue;const f=c.option?.defaultVariant?.id;f&&(a[c.stepName]={selectedVariants:[{id:f}]})}}return(await Ja(i,a)).flatMap(l=>l.renderableSteps).forEach(l=>{l.option?.id&&!l.option?.variants&&t.add(l.option.id)}),t}addConfirmCallback(e){e(this.confirmedDesign),this.confirmCallbacks.push(e)}addEditedCallback(e){e(this.editedSteps),this.editedCallbacks.push(e)}addElementsCallback(e){e(this.stepElements),this.elementsCallbacks.push(e)}addInformationResultCallback(e){e(this.informationResults),this.informationResultCallbacks.push(e)}addInitCallback(e){e(this.stepInitialised),this.initCallbacks.push(e)}addMandatoryCallback(e){e(this.mandatorySteps),this.mandatoryCallbacks.push(e)}addMetadataCallback(e){e(this.stepMetadata),this.metadataCallbacks.push(e)}async addSelectionCallback(e){e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(e)}addStepSpecificStorageCallback(e,t){Object.keys(this.storage).includes(t)||(this.storage[t]={}),e(this.storage[t]),Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].push(e)}addStorageCallback(e){e(this.storage),this.storageCallbacks.push(e)}addMakingAdjustmentsCallback(e){e(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(e)}addPoller(e){this.pollers.push(e)}addValidationCallback(e){this.validationCallbacks.push(e),e(this.validationErrors)}addRecipientCallback(e){this.recipientCallbacks.push(e),e(this.experience.getTransaction().recipient)}removeRecipientCallback(e){this.recipientCallbacks=this.recipientCallbacks.filter(t=>t!==e)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(e=>e.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getCommandContext(){return this.commandContext}getRegionElements(e){return this.stepElements[e]||[]}getStepSpecificServices(e){return this.stepSpecificServices[e]}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(e){this.ownerCustomer=e}setTransactionCustomerDetails(e){this.ownerCustomer={...this.ownerCustomer,emailAddress:e.email}}getModelContainer(){return this.modelContainer}setModelContainer(e){(!e||this.previewService&&this.previewService.getAllModels().includes(e))&&(this.modelContainer=e,e&&e.metadata&&e.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}getCommandDispatcher(){return e=>this.commandContext.apply(e,!this.initialized)}getWorkflowSelections(){const e={};return this.experience.getWorkflow()?.steps.forEach(t=>{const n=this.stepSelections[t.stepName];n&&n.selectedVariants&&n.selectedVariants.length>0&&(e[t.stepName]={selections:n.selectedVariants})}),e}getStepSelections(){return this.stepSelections}markStepsAsInitialised(e){const t={...this.stepInitialised};e.forEach(n=>{t[n]=!0}),this.stepInitialised=t,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(e){this.pendingUpdates=this.pendingUpdates.filter(t=>t!==e)}markUpdatePending(){const e=hr();return this.pendingUpdates=[...this.pendingUpdates,e],e}setEditedStatus(e,t){this.editedSteps={...this.editedSteps,[e]:t},this.onEditedChange()}setInformationResults(e){this.informationResults=[...e],this.onInformationResultChange()}setCurrentAdjustingStepId(e){this.currentAdjustingStepId=e,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(e,t){this.mandatorySteps[e]!==t&&(this.mandatorySteps={...this.mandatorySteps,[e]:t},this.onMandatoryChange())}async getMandatoryUnfulfilledSteps(){return(await Ja(this.allScenes,this.stepSelections)).flatMap(a=>a.renderableSteps).filter(a=>a.mandatory).filter(a=>!this.mandatorySteps[a.stepName]).map(a=>a.stepName)}setStepError(e,t,n){let i=!1;if(!this.validationErrors.steps.has(e)&&n)i=!0,this.validationErrors.steps.set(e,new Map([[t,n]]));else if(this.validationErrors.steps.has(e)){const a=this.validationErrors.steps.get(e);n&&n!==a.get(t)?(i=!0,a.set(t,n)):n||(i=!0,a.delete(t),a.size===0&&this.validationErrors.steps.delete(e))}i&&this.onValidationChange()}getStepErrors(e){return this.validationErrors.steps.get(e)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(e){e(this.mandatorySteps),this.mandatoryCallbacks.push(e)}async injectIntoPreviewService(e,t){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");this.previewService=e;const n=this.experience.getProduct();if(!n?.modelUrl||!this.previewService)return;const i=e.loadModel({model:n.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:t});this.setModelContainer(i),(await Ja(this.allScenes,this.stepSelections)).filter(o=>o).map(o=>o.renderableSteps).flat().filter(o=>o.type===Xe.Model||o.type===Xe.Material).forEach(o=>{if(!o.option?.id){console.error(`Failed to read option id from step: ${o.stepName}`);return}const l=this.stepSelections[o.stepName]?.selectedVariants||[];if(l.length===0)return;const u=l[0];if(o.type===Xe.Model){if(!this.modelContainer)throw new nn("We should always have a model container when injecting a preview!");const c=u.asset?.fileLink;if(!c){console.error(`Failed to read model url from variant: ${u.id} for step: ${o.stepName}`);return}const f=o.data;this.modelContainer.applyModelVariant(o.stepName,{model:c,contextService:this.getLayoutPreviewService()},f.replaceProductModel||!1)}else{const c=u.material;if(!c){console.error(`Failed to read material from variant: ${u.id} for step: ${o.stepName}`);return}o.data.targetMaterials.forEach(d=>{if(!this.modelContainer)throw new nn("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(d,o.option.id,c)})}}),await i.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(e,t){const n={...this.storage,[e]:{...this.storage[e],...t}};if(!vf(n,this.storage)){this.storage=n;const i=new BS(this.constructSerializableWorkflow());this.commandContext.apply(i,!0),this.onStepSpecificStorageChange(e),this.onStorageChange()}}constructSerializableWorkflow(){const e=[];return this.allScenes.forEach(t=>{t.renderableSteps.forEach(n=>{const i={stepName:n.stepName};i.storage=this.storage[n.stepName],i.selectedVariants=this.stepSelections[n.stepName]?.selectedVariants?.map(a=>({id:a.id,priceModifier:a.priceModifier})),e.push(i)})}),{steps:e}}updateStateWithServer(){if(this.readOnly)return;const e=this.serialize();this.workflowStatePromiseQueue.enqueue(new EE(async()=>{await new Promise(t=>{setTimeout(()=>{t()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:e}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const e=this.serialize();return new EE(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:e}})}).execute()}serialize(){const e=this.getCommandContext().getState();if(!e)throw new nn("Attempted to serialize state before it was initialized.");const t=mo(e.transaction),n=D9(t);return JSON.stringify(n,P9,void 0)}async getStateHash(){const e=this.getCommandContext().getState(),n=Object.values(e?.transaction.layouts||{}).map(s=>s.modificationID??"").sort().join(""),a=new TextEncoder().encode(n);if(typeof window<"u"&&window.crypto&&window.crypto.subtle&&window.crypto.subtle.digest){const s=await window.crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(s)).map(u=>u.toString(16).padStart(2,"0")).join("")}try{return(await import("crypto")).createHash("sha256").update(n,"utf8").digest("hex")}catch{throw new Error("Unable to compute SHA-256 hash: no suitable crypto implementation available.")}}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(e,t){this.stepMetadata={...this.stepMetadata,[e]:{...this.stepMetadata[e],...t}},this.onMetadataChange()}removeElements(e){const t=(n,i)=>Object.keys(n).reduce((a,s)=>{const o=[...n[s]||[]];return i.forEach(l=>{const u=o.findIndex(c=>c.id===l.id);u>-1&&o.splice(u,1)}),a[s]=o,a},{});this.stepElements=t(this.stepElements,e)}async getInvalidCanvasRegions(){let e=[];for(const t of this.experience.getWorkflow()?.steps||[])if(!await co(t,this.stepSelections)&&this.stepElements[t.stepName])for(const n of this.stepElements[t.stepName])e.push(n);return e}async getInvalidModelVariants(){let e=[];for(const t of this.experience.getWorkflow()?.steps||[])t.type===Xe.Model&&!await co(t,this.stepSelections)&&e.push(t.stepName);return e}async stepElementsForIntroducedSilentSteps(e,t){const n=this.experience.getProduct();if(!n)return Promise.resolve({stepElements:{},commands:[]});const i=async(u,c,f)=>{if(u.type===Xe.SilentIllustration){const d=await new MS(u,c).trigger();return{step:u,results:d}}else if(u.type===Xe.ProductOverlay){const d=await new MS(u,c,f).trigger();return{step:u,results:d}}return Promise.reject("Unknown silent step. This is a bug")},a=e.filter(u=>!this.stepInitialised[u.stepName]),s={stepElements:{},commands:[]},o=[];for(const u of a)this.markStepsAsInitialised([u.stepName]),t||o.push(i(u,this.layouts,n));const l=await Promise.all(o);for(const u of l)s.stepElements[u.step.stepName]=u.results.map(c=>c.regionElement),s.commands=[...s.commands,...u.results.map(c=>c.command)];return s}getStepStorage(e){return this.storage[e]}getMetadata(e){return this.stepMetadata[e]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(e){return this.stepTags[e]||[]}getSerializedStep(e,t){return t.find(n=>n.stepName===e)}async updateTransactionShareActions(){const e=await this.client.getShareActionsForTransaction(this.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=e}async updateTransactionStakeholders(){const e=await ze.getShadowGraphqlClient().query({query:H3,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!e?.data?.transactions||e.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=e.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=e.data.transactions[0].currentStakeholder)}async approveTransaction(e){await ze.getShadowGraphqlClient().mutate({mutation:C9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:e}})}async rejectTransaction(e){await ze.getShadowGraphqlClient().mutate({mutation:x9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:e}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(e,t,n,i){const a=this.experience.getWorkflow();if(!a)throw new Error("Attempted to set selections when no workflow is set!");const s=this.stepSelections;this.stepSelections={...this.stepSelections,[e]:{selectedVariants:t}};for(const R of a.steps)await co(R,this.stepSelections)||(this.stepInitialised[R.stepName]=!1,delete this.stepMetadata[R.stepName],delete this.stepSelections[R.stepName],delete this.storage[R.stepName]);const o=this.allScenes,l=await Ja(o,s),u=await Ja(o,this.stepSelections),c=l.map(R=>R.silentSteps).flat(),d=u.map(R=>R.silentSteps).flat().filter(R=>!c.some(B=>B.stepName===R.stepName));for(const R of c)await co(R,this.stepSelections)||(this.stepInitialised[R.stepName]=!1);const h=await this.getInvalidCanvasRegions(),{stepElements:g,commands:v}=await this.stepElementsForIntroducedSilentSteps(d,!1);this.stepElements={...this.stepElements,...g,[e]:n},this.removeElements(h);const y=a.steps.find(R=>R.stepName===e);y?.type===Xe.Frame&&this.getWorkflowExperience().getStepById(y.stepName)?.frameService?.setTargetElements(n.map(B=>B.id));const A=h.map(R=>new Ol(R.id)),C=new BS(this.constructSerializableWorkflow()),S=[...v,...A,C];S.length>0&&this.commandContext.apply(new In(S),!0),await this.ensureStepsAreLoaded(),this.selectionCost=Object.values(this.stepSelections).reduce((R,B)=>R+B.selectedVariants.map(j=>j.priceModifier||0).reduce((j,G)=>j+G,0),0),this.onElementsChange();const F=await this.getInvalidModelVariants(),E=this.modelContainer;if(E){const R=F.map(B=>E.applyModelVariant(B,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(R)}await this.onSelectionChange(),await this.reapplyMaterialSteps(),y?.type!==Xe.Frame&&y?.type!==Xe.Text&&this.setMandatoryFulfilled(e,!0),i&&await i()}async ensureStepsAreLoaded(){const t=(await Ja(this.allScenes,this.stepSelections)).map(l=>l.renderableSteps),n=[],i=t.flat();for(const l of i)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case Xe.DigitalContent:n.push(F1.init(l,this,this.reloadedState));break;case Xe.Frame:n.push(so.init(l,this,this.reloadedState));break;case Xe.Illustration:n.push(Jd.init(l,this,this.reloadedState));break;case Xe.Material:n.push(I1.init(l,this,this.reloadedState));break;case Xe.Model:n.push(P1.init(l,this,this.reloadedState));break;case Xe.Module:this.stepSpecificServices[l.stepName]={module:await cI(l.data.module)},n.push(D1.init(l,this,this.reloadedState));break;case Xe.Picture:n.push(R1.init(l,this,this.reloadedState));break;case Xe.Question:n.push(O1.init(l,this,this.reloadedState));break;case Xe.Shape:n.push(Nu.init(l,this,this.reloadedState));break;case Xe.Text:n.push(ri.init(l,this,this.reloadedState));break}const a=(await Promise.allSettled(n)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),s=a.flatMap(l=>l?.command?[l.command]:[]),o=a.flatMap(l=>l?.followup?[l.followup]:[]);s&&s.length>0&&this.commandContext.apply(new In(s),!0);for(const l of o)await l();o.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(e=>e(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(e=>e(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(e=>e(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(e=>e(this.informationResults))}onInitChange(){this.initCallbacks.forEach(e=>e(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(e=>{e(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(e=>e(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(e=>{e(this.stepMetadata)})}async onSelectionChange(){const e=await this.traversableScenes();for(const t of this.selectionCallbacks)t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:e})}onStepSpecificStorageChange(e){Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].forEach(t=>t(this.storage[e]))}onStorageChange(){this.storageCallbacks.forEach(e=>e(this.storage))}onValidationChange(){this.validationCallbacks.forEach(e=>e(this.validationErrors))}traversableScenes(){return O_(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}async reapplyMaterialSteps(){if(!this.modelContainer)return;const t=(await Ja(this.allScenes,this.stepSelections)).flatMap(n=>n.renderableSteps).filter(n=>n.type===Xe.Material);for(const n of t){const i=this.stepSelections[n.stepName]?.selectedVariants;if(!i||i.length===0)continue;const s=i[0].material;if(!s||!n.option?.id)continue;n.data.targetMaterials.forEach(l=>{this.modelContainer?.applyMaterialVariant(l,n.option.id,s)})}}};af.configurationPromiseMap=new Map;let fA=af;class Fa{constructor(e){this.variantData=e}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(e,t){return this.variantData.priceModifier.toLocaleString(e||"en-US",{style:"currency",currency:"USD",...t})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.asset?.fileLink}getAssetResource(){return this.variantData.asset}getThumbnail(e=256,t){const n=this.variantData.thumbnail;if(!(!n||!n.fileLink))return $g(n,e,"webp",t)}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}getCategory(){return this.variantData.category}getProduct(){return this.variantData.product}}const sf=class sf{constructor(e,t,n){this.manager=e,this.step=t,this.tags=n}setUpdateState(e){sf.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,e)}getUpdateState(){return!!sf.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const n=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(n)return new Fa(n)}async getAvailableVariants(){return(await this.getAllVariants()).filter(t=>t.isEnabled())||[]}async getAllVariants(){if(!this.step.option?.id)return[];if(this.step.option.variants)return(this.step.option.variants||[]).map(t=>new Fa(t))||[];const e=await ct.getOption(this.step.option?.id);if(!e)throw new Error("Option not found, cannot fetch variants.");return(e.variants||[]).map(t=>new Fa(t))||[]}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(e){return this.tags.includes(e)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(e){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[e.toString()]??!1}setOverrideGlobalPropertyConfiguration(e,t){const n=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...n,[e.toString()]:t}})}getGlobalPropertyAspects(e){return this.step.globalPropertyAspectConfigurations?.filter(t=>t.globalPropertyConfigurationId===e&&t.aspectName).map(t=>t.aspectName)??[]}executeAnimations(e){const t=this.manager.getPreviewService(),n=this.manager.getModelContainer(),i=this.step.data.modelAnimation,a=this.step.data.lookAtAnimation;t?a&&t.executeCameraAnimation(a):console.warn("No preview service available, cannot execute camera animations."),n?i&&n.executeAnimation(i,e):console.warn("No model container available, cannot execute model animations.")}};sf.updateState=new Map;let Ui=sf;class yI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(e){if(!this.getUpdateState()&&this.getCurrentVariant()!==e)return Jd.selectVariant(this.step,e.getResource(),this.manager.getRegionElements(this.step.stepName)||[],t=>this.setUpdateState(t),this.manager)}getColors(){const e=this.manager.getRegionElements(this.step.stepName)||[];if(e.length===0)return;const n=Un(e[0].id,this.manager.getAllLayoutData()).colors,a=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,s=a?.defaultColorVariants||[];if(s.length!==0){const o={};return s.forEach(l=>{const u=a.channelNumbers.find(c=>c.number===l.channelNumber);if(u){const c=u.id.replace(/\W/g,"");o[l.channelNumber]={browserValue:n[c]?.browserValue||""}}}),o}try{return n}catch(o){console.error(o)}}setColor(e,t,n){const i=new Map,s=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(s?.defaultColorVariants||[]).length!==0?s.channelNumbers.forEach(l=>{if(l.number.toString()===e){const u=l.id.replace(/\W/g,"");n?i.set(u,{browserValue:t,pmsValue:n}):i.set(u,t)}}):n?i.set(e,{browserValue:t,pmsValue:n}):i.set(e,t),Jd.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,i)}async getColorOption(){return await ct.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?Jd.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class AI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){return I1.selectVariant(this.step,e.getResource(),this.manager,t=>this.setUpdateState(t))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class wI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){return P1.selectVariant(this.step,e.getResource(),this.manager,t=>this.setUpdateState(t))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class bI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){return R1.selectVariant(this.step,e.getResource(),this.manager,t=>this.setUpdateState(t))}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class CI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(e){if(!e.getId())throw new Error("Unable to select variant with a null ID");await O1.selectVariant(this.step,e.getId(),this.manager)}async getDisplayType(){return this.step.data.displayType?this.step.data.displayType:(await ct.getOptionForStep(this.step))?.displayType}}class xI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){const t=e.getResource();return Nu.selectVariant(this.step,{fill:t.color,stroke:t.color,variant:t},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(e){return Nu.selectVariant(this.step,e,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Nu.availableColours(this.step)}setCustomColor(e){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),Nu.setCustomColor(e,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const e=this.manager.getStepStorage(this.step.stepName)?.colour;if(!e)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return e}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class SI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(e){await ri.selectVariant(this.step,e.getResource(),this.manager,t=>{if(t)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:t,messageType:Jf.Error,stepID:this.step.stepName}]);else{const n=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(n)}},()=>{})}async getAvailableFillColors(){return this.step.data.colorPickerEnabled?ri.availableFillColors(this.step):[]}async setFillColor(e){const t=this.manager.getRegionElements(this.step.stepName);await ri.changeFillColor(this.step,e,t,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return ri.availableFillImages(this.step)}async setFillImage(e){const t=this.manager.getRegionElements(this.step.stepName);await ri.changeFillImage(this.step,e,t,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return ri.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(e){const t=this.manager.getRegionElements(this.step.stepName);ri.changeAlignment(this.step,e,t,this.manager)}setFullTextCustomization(e){const t=this.manager.getStepStorage(this.step.stepName)?.inputText||"",n=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",t):t,i=e?n:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:e,text:i,defaultCleared:!1}),this.setText(i)}setText(e){const t={input:e,helperData:{}},n=ri.findLayoutElements(this.manager,this.step),i=ri.filterUnsupportedCharacters(e,n[0]?.fontData),a=ju(i,this.manager).length,s=!!this.step.data&&!!this.step.data.maxLength&&a>this.step.data.maxLength;s||(t.input=i);const o=n.length<=0,l=o?{inputText:i,text:i}:{inputText:i};this.manager.updateStorage(this.step.stepName,l);const u=this.manager.getStepStorage(this.step.stepName),c=ri.getProcessedInput(i,this.step.data,u?.customiseAllText??!1);if(o)s||this.manager.updateMetadata(this.step.stepName,{text:c});else{const{command:f,errorData:d,helperData:h}=ri.updateInputText(i,n,this.step,this.manager);f&&this.manager.getCommandDispatcher()(f),t.helperData=h,t.errorData=d,!s&&!d&&this.manager.updateMetadata(this.step.stepName,{text:c})}return t}getText(){const e=this.step.data.defaultText,t=this.manager.getStepStorage(this.step.stepName);return e&&t?.defaultCleared!==void 0&&!t?.defaultCleared?e:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const t=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const n=ri.findLayoutElements(this.manager,this.step);return ri.updateInputText("",n,this.step,this.manager),t}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const e=this.step.data.maxLength;if(e===void 0)return;const t=ju(this.getText(),this.manager);return e-t.length}setCustomColor(e){this.getFillColor()!=="#custom"&&console.warn(`setting custom color for text step ${this.step.stepName} but current fill is not #custom`);const t=this.manager.getRegionElements(this.step.stepName);ri.applyCustomFillColor(this.step,e,t,this.manager)}getCustomColor(){return this.manager.getStepStorage(this.step.stepName)?.customColor||"#000000"}async getAvailableStrokeColors(){return this.step.data.strokeEnabled?ri.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(e){const t=this.manager.getRegionElements(this.step.stepName);await ri.changeStrokeColor(this.step,e,t,this.manager)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class EI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){}getContent(){return this.step.data.content}}class kI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(e){return F1.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),e.key,this.manager,this.step)}}class TI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const e=this.step.data.maxLength;if(e===void 0)return;const t=ju(this.getText(),this.manager);return e-t.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(e){D1.changeText(this.step,e,this.manager,t=>{if(t){const n=[...this.manager.getInformationResults(),{message:t,messageType:Jf.Error,stepID:this.step.stepName}];this.manager.setInformationResults(n)}else{const n=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(n)}})}}class FI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){}async getAvailableVariants(){const e=await super.getAvailableVariants();if(!this.cachedProductIds){this.cachedProductIds=new Set;for(const t of e){const n=t.getProduct();n?.id&&this.cachedProductIds.add(n.id)}}return e}isPersonalisable(e){const t=e.getProduct();return!!t?.workflows&&t.workflows.length>0}async addProduct(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)throw new Error("Product step requires bundle context");const n=e.getProduct();if(!n)throw new Error("Variant has no product. Ensure the option query includes the product field on variants.");if(!this.isPersonalisable(e)){await this.incrementNonPersonalisable(e);return}const i=this.manager.getWorkflowExperience().getTransaction(),a=i.integrationProduct?.integration?.id;let s;if(a&&n.integrationProducts&&(s=n.integrationProducts.find(d=>d.integration?.id===a)?.id),!s)throw new Error("No integration product found for bundle context");const o=this.manager.getClient(),l=n?.workflows||[];let u;if(l.length===1)u=l[0].id;else if(l.length>1){const f=this.step.data.workflows,d=l.find(h=>f.includes(h.id));if(d)u=d.id;else throw new Error("Multiple workflows available but none match step configuration")}const c=await o.getWorkflowExperience({type:"integration",integrationProductId:s,workflowId:u,parentTransactionId:i.id});await t.addWorkflowExperience(c)}async incrementNonPersonalisable(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)return;const n=e.getProduct(),i=this.findExperienceForProduct(n.id);if(i){const c=i.getTransaction().quantity||1;await i.setQuantity(c+1);return}const a=this.manager.getWorkflowExperience().getTransaction(),s=a.integrationProduct?.integration?.id;let o;if(s&&n.integrationProducts&&(o=n.integrationProducts.find(f=>f.integration?.id===s)?.id),!o)throw new Error("No integration product found for bundle context");const u=await this.manager.getClient().getWorkflowExperience({type:"integration",integrationProductId:o,parentTransactionId:a.id});await t.addWorkflowExperience(u)}async removeProduct(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)throw new Error("Product step requires bundle context");const i=t.getWorkflowExperiences().find(o=>o.getTransaction().id===e);if(!i)throw new Error("Transaction is not a child of this product step");const a=i.getTransaction(),s=a.quantity||1;if(s>1){await i.setQuantity(s-1);return}await t.removeWorkflowExperienceByTransaction(a)}isCategoryFilterEnabled(){return this.step.data.categoryFilterEnabled??!1}isSearchBarEnabled(){return this.step.data.searchBarEnabled??!1}getMin(){return this.step.data.min}getMax(){return this.step.data.max}getPricing(){return this.step.data.pricing}getWorkflows(){return this.step.data.workflows||[]}getChildTransactions(){const e=this.manager.getWorkflowExperience().getBundle();if(!e)return[];const t=this.manager.getWorkflowExperience().getTransaction().id,n=e.getWorkflowExperiences(),i=this.getStepProductIds();return n.map(a=>a.getTransaction()).filter(a=>a.parentTransaction?.id!==t||i.size===0?!1:a.product?.id?i.has(a.product.id):!1)}getStepProductIds(){if(this.cachedProductIds&&this.cachedProductIds.size>0)return this.cachedProductIds;const e=this.step.option?.variants||[],t=new Set;for(const n of e)n.product?.id&&t.add(n.product.id);return t}getLockedAddOns(){return this.step.data.lockedAddOns||[]}findExperienceForProduct(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)return;const n=this.manager.getWorkflowExperience().getTransaction().id,i=this.getStepProductIds();return t.getWorkflowExperiences().find(a=>{const s=a.getTransaction();return s.parentTransaction?.id!==n||i.size>0&&!i.has(e)?!1:s.product?.id===e})}}class Ep{static get(e,t){switch(t.type){case Xe.DigitalContent:return new kI(e,t,e.getStepTags(t.stepName));case Xe.Information:return new EI(e,t,e.getStepTags(t.stepName));case Xe.Question:return new CI(e,t,e.getStepTags(t.stepName));case Xe.Text:return new SI(e,t,e.getStepTags(t.stepName));case Xe.Illustration:return new yI(e,t,e.getStepTags(t.stepName));case Xe.Picture:return new bI(e,t,e.getStepTags(t.stepName));case Xe.Shape:return new xI(e,t,e.getStepTags(t.stepName));case Xe.Material:return new AI(e,t,e.getStepTags(t.stepName));case Xe.Model:return new wI(e,t,e.getStepTags(t.stepName));case Xe.Frame:return new XP(e,t,e.getStepTags(t.stepName));case Xe.Module:return new TI(e,t,e.getStepTags(t.stepName));case Xe.Product:return new FI(e,t,e.getStepTags(t.stepName));default:throw new nn(`Step type ${t.type} not yet supported in Core SDK`)}}}var Dv,TE;function B9(){if(TE)return Dv;TE=1;var r=1/0,e=9007199254740991,t=17976931348623157e292,n=NaN,i="[object Function]",a="[object GeneratorFunction]",s="[object Symbol]",o=/^\s+|\s+$/g,l=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,c=/^0o[0-7]+$/i,f=/^(?:0|[1-9]\d*)$/,d=parseInt,h=Object.prototype,g=h.toString,v=Math.ceil,y=Math.max;function A(oe,he,ye){var Ue=-1,Re=oe.length;he<0&&(he=-he>Re?0:Re+he),ye=ye>Re?Re:ye,ye<0&&(ye+=Re),Re=he>ye?0:ye-he>>>0,he>>>=0;for(var Oe=Array(Re);++Ue<Re;)Oe[Ue]=oe[Ue+he];return Oe}function C(oe,he){return he=he??e,!!he&&(typeof oe=="number"||f.test(oe))&&oe>-1&&oe%1==0&&oe<he}function S(oe,he,ye){if(!G(ye))return!1;var Ue=typeof he;return(Ue=="number"?R(ye)&&C(he,ye.length):Ue=="string"&&he in ye)?E(ye[he],oe):!1}function F(oe,he,ye){(ye?S(oe,he,ye):he===void 0)?he=1:he=y(J(he),0);var Ue=oe?oe.length:0;if(!Ue||he<1)return[];for(var Re=0,Oe=0,ee=Array(v(Ue/he));Re<Ue;)ee[Oe++]=A(oe,Re,Re+=he);return ee}function E(oe,he){return oe===he||oe!==oe&&he!==he}function R(oe){return oe!=null&&j(oe.length)&&!B(oe)}function B(oe){var he=G(oe)?g.call(oe):"";return he==i||he==a}function j(oe){return typeof oe=="number"&&oe>-1&&oe%1==0&&oe<=e}function G(oe){var he=typeof oe;return!!oe&&(he=="object"||he=="function")}function ie(oe){return!!oe&&typeof oe=="object"}function q(oe){return typeof oe=="symbol"||ie(oe)&&g.call(oe)==s}function Y(oe){if(!oe)return oe===0?oe:0;if(oe=ae(oe),oe===r||oe===-r){var he=oe<0?-1:1;return he*t}return oe===oe?oe:0}function J(oe){var he=Y(oe),ye=he%1;return he===he?ye?he-ye:he:0}function ae(oe){if(typeof oe=="number")return oe;if(q(oe))return n;if(G(oe)){var he=typeof oe.valueOf=="function"?oe.valueOf():oe;oe=G(he)?he+"":he}if(typeof oe!="string")return oe===0?oe:+oe;oe=oe.replace(o,"");var ye=u.test(oe);return ye||c.test(oe)?d(oe.slice(2),ye?2:8):l.test(oe)?n:+oe}return Dv=F,Dv}var M9=B9();const hA=Ns(M9),_9=Se`
2655
+ `,P9=(r,e)=>e&&typeof e=="object"&&!Array.isArray(e)?Object.keys(e).sort().reduce((t,n)=>(t[n]=e[n],t),{}):e,D9=r=>{for(const e of Object.values(r.layouts).map(t=>t.elements).flat())e.type==="illustration"&&(delete e.cachedObjectURL,e.src&&delete e.svg),e.type==="frame"&&delete e.pattern?.svg;return vI(r,"__typename"),r},vI=(r,e)=>{if(!(typeof r!="object"||r===null))for(const t in r)t===e?delete r[t]:vI(r[t],e)};var Jf=(r=>(r.Error="Error",r.Warning="Warning",r.Info="Info",r))(Jf||{});const R9=1e3;class EE extends jg{constructor(e){super(),this.update=e}async execute(){await this.update(),await new Promise(e=>{window.setTimeout(()=>{e()},R9)})}}const O9=r=>r.sort((e,t)=>e.index-t.index).map(e=>({id:hr(),panelId:e.name,name:e.name,title:e.title,index:e.index,createdAt:new Date,updatedAt:new Date,transparentBackground:e.transparentBackground,height:e.height,width:e.width,previewRegion:e.previewRegion,useEditableArea:e.useEditableArea,editableArea:e.editableArea})),kE=(r,e)=>{const t=r.workflowState,n=t?JSON.parse(t):void 0;return n?Object.values(n.layouts).map(i=>i.layout):O9(e.panels)},af=class af{constructor(e,t,n,i,a,s=!1,o,l=!1,u=!1,c=!1){this.workflowStatePromiseQueue=new Gg(1),this.initialized=!1,this.readOnly=!1,this.isReloadedTransaction=!1,this.singleVariantsRenderable=!1,this.stepTags={},this.setWorkflow=async d=>{this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.reloadedState?this.layouts=Object.values(this.reloadedState.layouts||{}).map(g=>g.layout):d?this.layouts=kE(this.experience.getTransaction(),d):this.layouts=[],this.commandContext.initialize(this.layouts,this.reloadedState),this.renderableContextService=new zU(this.layouts),this.renderableContextService.setWorkflowManager(this),d.steps.forEach(g=>{this.stepTags[g.stepName]=g.tags??[]});const h=this.previewService;this.ejectFromPreviewService(),this.initializationPromise=this.initializeDefaultWorkflowState(d),this.initializationPromise.then(()=>{this.initialized=!0}),this.initializationPromise.catch(g=>{throw this.initialized=!1,new Error(g)}),this.initializationPromise.finally(()=>this.commandContext.registerStateCallback(()=>{this.updateStateWithServer(),this.renderLayouts()})),h&&await this.injectIntoPreviewService(h,!0)},this.renderLayouts=()=>{if(!this.previewService)return;const d=this.getCommandContext().getAllLayouts(),h=this.getLayoutPreviewService()?.getAll();if(h)for(const[,g]of h)g.render(d)},this.experience=e,this.client=t,this.updateTransaction=n,this.graphQlClient=i,this.reloadedState=a,this.readOnly=s,this.singleVariantsRenderable=u,this.commandContext=new WF,this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.validationCallbacks=[],this.recipientCallbacks=[],this.modelContainer=o,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.stepSpecificServices={},this.pollers=[],this.allScenes=[],this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.validationErrors={steps:new Map},this.currentAdjustingStepId="",this.isReloadedTransaction=l,c&&(this.workflowStatePromiseQueue.enabled=!1);const f=this.experience.getWorkflow();f&&this.setWorkflow(f)}async updateWorkflowConfiguration(e,t){t.panels&&await this.updatePanels(t.panels),t.steps&&await this.updateSteps(t.steps),t.stepGroups&&await this.updateScenes(t.stepGroups),this.renderLayouts(),await this.onSelectionChange()}async updatePanels(e){const t=new Map(this.layouts.map(a=>[a.panelId,a])),n=kE(this.experience.getTransaction(),{...this.experience.getWorkflow(),panels:e}),i=new Map;for(const a of n){const s=t.get(a.panelId);s?i.set(s.id,{...s,...a,id:s.id}):i.set(a.id,a)}this.layouts=Array.from(i.values()),this.commandContext.updateLayouts(this.layouts),this.renderableContextService&&this.renderableContextService.updateLayouts(this.layouts)}async updateSteps(e){const t=new Set(Object.keys(this.stepSelections)),n=new Set(e.map(i=>i.stepName));for(const i of t)n.has(i)||this.clearStepState(i);for(const i of e)t.has(i.stepName)&&await this.stepNeedsReinitialization(i)&&(this.stepInitialised[i.stepName]=!1);await this.ensureStepsAreLoaded(),await this.remapRegionElements(e)}clearStepState(e){delete this.stepSelections[e],delete this.stepMetadata[e],delete this.storage[e],delete this.stepElements[e],delete this.stepInitialised[e],delete this.stepSpecificServices[e],delete this.mandatorySteps[e],this.validationErrors.steps.delete(e)}async stepNeedsReinitialization(e){if("regions"in e.data){const n=this.stepElements[e.stepName]||[],i=e.data.regions,a=new Set(n.map(o=>o.region?.panelId).filter(Boolean)),s=new Set(i.map(o=>o.panelId));if(a.size!==s.size)return!0;for(const o of s)if(!a.has(o))return!0;for(let o=0;o<i.length;o++){const l=n[o]?.region,u=i[o];if(!l||l.width!==u.width||l.height!==u.height||l.top!==u.top||l.left!==u.left||l.panelId!==u.panelId)return!0}}return this.experience.getWorkflow()?.steps.find(n=>n.stepName===e.stepName)?.relevantPanelName!==e.relevantPanelName}async remapRegionElements(e){const t=[];for(const n of e){if(!("regions"in n.data))continue;const i=n.data.regions,a=this.stepElements[n.stepName]||[];for(let s=0;s<a.length&&s<i.length;s++){const o=a[s],l=i[s];if(o.region?.panelId!==l.panelId){const u=this.layouts.find(c=>c.panelId===l.panelId)?.id;u&&t.push(new eI(o.id,l,u))}}}t.length>0&&this.commandContext.apply(new In(t),!0)}async updateScenes(e){const t=this.experience.getWorkflow();t&&(this.allScenes=T0({...t,stepGroups:e}),await this.onSelectionChange())}getTemplatingContext(){const e=this.experience.getTransaction().recipient,t={recipient:e};return this.recipientConversionConfiguration?.requestedDataItems?.forEach(n=>{const i=n.uniqueIdentifier??n.title??"";n.type===Qd.FirstName?t[i]=e?.firstName:n.type===Qd.LastName?t[i]=e?.lastName:n.type===Qd.Custom&&(n.customFieldIndex===1?t[i]=e?.customField1:n.customFieldIndex===2?t[i]=e?.customField2:n.customFieldIndex===3?t[i]=e?.customField3:n.customFieldIndex===4?t[i]=e?.customField4:n.customFieldIndex===5&&(t[i]=e?.customField5),n.option&&(t[i]=n.option.variants?.find(a=>a.id===t[i])?.name))}),t}async updateRecipient(e,t,n,i,a,s,o,l,u,c,f,d,h,g,v,y,A,C){const S=this.experience.getTransaction();if(S.recipient?.id)this.experience.getTransaction().recipient={id:S.recipient.id,firstName:e??S.recipient.firstName,lastName:t??S.recipient.lastName,address:n??S.recipient.address,suburb:i??S.recipient.suburb,state:a??S.recipient.state,email:s??S.recipient.email,postalCode:o??S.recipient.postalCode,country:l??S.recipient.country,mobile:u??S.recipient.mobile,company:c??S.recipient.company,apartment:f??S.recipient.apartment,customField1:d??S.recipient.customField1,customField2:h??S.recipient.customField2,customField3:g??S.recipient.customField3,customField4:v??S.recipient.customField4,customField5:y??S.recipient.customField5,conversionConfigurationId:A||S.recipient.conversionConfigurationId},this.experience.callEvent(yg.RecipientChanged),await this.graphQlClient().mutate({mutation:E9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:S.recipient.id,firstName:e||S.recipient.firstName,lastName:t||S.recipient.lastName,address:n||S.recipient.address,suburb:i||S.recipient.suburb,state:a||S.recipient.state,email:s||S.recipient.email,postalCode:o||S.recipient.postalCode,country:l||S.recipient.country,mobile:u||S.recipient.mobile,company:c||S.recipient.company,apartment:f||S.recipient.apartment,customField1:d||S.recipient.customField1,customField2:h||S.recipient.customField2,customField3:g||S.recipient.customField3,customField4:v||S.recipient.customField4,customField5:y||S.recipient.customField5,conversionConfigurationId:A||S.recipient.conversionConfigurationId,prevalidated:C}});else{const F=await this.graphQlClient().mutate({mutation:S9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{firstName:e,lastName:t,address:n,suburb:i,state:a,email:s,postalCode:o,country:l,mobile:u,company:c,apartment:f,customField1:d,customField2:h,customField3:g,customField4:v,customField5:y,conversionConfigurationId:A}});S.recipient={id:F?.data?.recipientCreate?.id,firstName:e,lastName:t,address:n,suburb:i,state:a,email:s,postalCode:o,country:l,mobile:u,company:c,apartment:f,customField1:d,customField2:h,customField3:g,customField4:v,customField5:y,conversionConfigurationId:A},this.experience.callEvent(yg.RecipientChanged),await this.graphQlClient().mutate({mutation:k9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,recipientId:F.data?.recipientCreate?.id},context:{transactionOwnerId:this.experience.getTransaction().transactionOwnerId}})}await this.fetchConversionConfiguration(),this.recipientCallbacks.forEach(F=>F(this.experience.getTransaction().recipient))}async fetchConversionConfiguration(){const e=this.experience.getTransaction().recipient;if(e?.conversionConfigurationId&&!this.recipientConversionConfiguration){const t=af.configurationPromiseMap.get(e.conversionConfigurationId);if(t)this.recipientConversionConfiguration=await t;else{const i=(async()=>(await this.graphQlClient().query({query:N3,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e.conversionConfigurationId}})).data.conversionConfiguration)();af.configurationPromiseMap.set(e.conversionConfigurationId,i),this.recipientConversionConfiguration=await i}}}async initializeDefaultWorkflowState(e){const t=()=>{const c=e.finalizeStepConfig;if(!c)return;const f=c.lookAtAnimation,d=c.modelAnimation;f&&this.previewService?.executeCameraAnimation(f),d&&this.modelContainer?.executeAnimation(d)};this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach(c=>{this.storage[c.stepName]=c.storage||{}});const n=await this.getInitialOptionIds(this.reloadedState?.serializableWorkflow?.steps.reduce((c,f)=>(f.selectedVariants?.length&&(c[f.stepName]={selectedVariants:f.selectedVariants.map(d=>({id:d.id}))}),c),{})),i=ct.getOptions(Array.from(n)),a=this.fetchConversionConfiguration();await Promise.all([i,a]),this.allScenes=T0(e);const o=(await Ja(this.allScenes,this.stepSelections)).map(c=>c.silentSteps).flat(),{stepElements:l,commands:u}=await this.stepElementsForIntroducedSilentSteps(o,!!this.reloadedState);this.commandContext.apply(new In(u),!0),this.stepElements={...this.stepElements,...l},await this.ensureStepsAreLoaded(),this.isReloadedTransaction||this.updateStateWithServer(),this.renderLayouts(),this.reloadedState&&t()}getWorkflowExperience(){return this.experience}getClient(){return this.client}setWorkflowStateSyncEnabled(e){this.workflowStatePromiseQueue.enabled=e}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}async getInitialOptionIds(e){const t=new Set,n=this.experience.getWorkflow();if(!n)return t;const i=T0(n),a={...e};let s=-1;for(;;){const u=(await Ja(i,a)).flatMap(c=>c.renderableSteps);if(u.length===s)break;s=u.length;for(const c of u){if(a[c.stepName])continue;const f=c.option?.defaultVariant?.id;f&&(a[c.stepName]={selectedVariants:[{id:f}]})}}return(await Ja(i,a)).flatMap(l=>l.renderableSteps).forEach(l=>{l.option?.id&&!l.option?.variants&&t.add(l.option.id)}),t}addConfirmCallback(e){e(this.confirmedDesign),this.confirmCallbacks.push(e)}addEditedCallback(e){e(this.editedSteps),this.editedCallbacks.push(e)}addElementsCallback(e){e(this.stepElements),this.elementsCallbacks.push(e)}addInformationResultCallback(e){e(this.informationResults),this.informationResultCallbacks.push(e)}addInitCallback(e){e(this.stepInitialised),this.initCallbacks.push(e)}addMandatoryCallback(e){e(this.mandatorySteps),this.mandatoryCallbacks.push(e)}addMetadataCallback(e){e(this.stepMetadata),this.metadataCallbacks.push(e)}async addSelectionCallback(e){e({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(e)}addStepSpecificStorageCallback(e,t){Object.keys(this.storage).includes(t)||(this.storage[t]={}),e(this.storage[t]),Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].push(e)}addStorageCallback(e){e(this.storage),this.storageCallbacks.push(e)}addMakingAdjustmentsCallback(e){e(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(e)}addPoller(e){this.pollers.push(e)}addValidationCallback(e){this.validationCallbacks.push(e),e(this.validationErrors)}addRecipientCallback(e){this.recipientCallbacks.push(e),e(this.experience.getTransaction().recipient)}removeRecipientCallback(e){this.recipientCallbacks=this.recipientCallbacks.filter(t=>t!==e)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map(e=>e.layoutState)}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getCommandContext(){return this.commandContext}getRegionElements(e){return this.stepElements[e]||[]}getStepSpecificServices(e){return this.stepSpecificServices[e]}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(e){this.ownerCustomer=e}setTransactionCustomerDetails(e){this.ownerCustomer={...this.ownerCustomer,emailAddress:e.email}}getModelContainer(){return this.modelContainer}setModelContainer(e){(!e||this.previewService&&this.previewService.getAllModels().includes(e))&&(this.modelContainer=e,e&&e.metadata&&e.metadata instanceof Map&&this.modelContainer.metadata.set("workflowManager",this))}getCommandDispatcher(){return e=>this.commandContext.apply(e,!this.initialized)}getWorkflowSelections(){const e={};return this.experience.getWorkflow()?.steps.forEach(t=>{const n=this.stepSelections[t.stepName];n&&n.selectedVariants&&n.selectedVariants.length>0&&(e[t.stepName]={selections:n.selectedVariants})}),e}getStepSelections(){return this.stepSelections}markStepsAsInitialised(e){const t={...this.stepInitialised};e.forEach(n=>{t[n]=!0}),this.stepInitialised=t,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(e){this.pendingUpdates=this.pendingUpdates.filter(t=>t!==e)}markUpdatePending(){const e=hr();return this.pendingUpdates=[...this.pendingUpdates,e],e}setEditedStatus(e,t){this.editedSteps={...this.editedSteps,[e]:t},this.onEditedChange()}setInformationResults(e){this.informationResults=[...e],this.onInformationResultChange()}setCurrentAdjustingStepId(e){this.currentAdjustingStepId=e,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(e,t){this.mandatorySteps[e]!==t&&(this.mandatorySteps={...this.mandatorySteps,[e]:t},this.onMandatoryChange())}async getMandatoryUnfulfilledSteps(){return(await Ja(this.allScenes,this.stepSelections)).flatMap(a=>a.renderableSteps).filter(a=>a.mandatory).filter(a=>!this.mandatorySteps[a.stepName]).map(a=>a.stepName)}setStepError(e,t,n){let i=!1;if(!this.validationErrors.steps.has(e)&&n)i=!0,this.validationErrors.steps.set(e,new Map([[t,n]]));else if(this.validationErrors.steps.has(e)){const a=this.validationErrors.steps.get(e);n&&n!==a.get(t)?(i=!0,a.set(t,n)):n||(i=!0,a.delete(t),a.size===0&&this.validationErrors.steps.delete(e))}i&&this.onValidationChange()}getStepErrors(e){return this.validationErrors.steps.get(e)}getValidationErrors(){return this.validationErrors}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(e){e(this.mandatorySteps),this.mandatoryCallbacks.push(e)}async injectIntoPreviewService(e,t){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");this.previewService=e;const n=this.experience.getProduct();if(!n?.modelUrl||!this.previewService)return;const i=e.loadModel({model:n.modelUrl,contextService:this.getLayoutPreviewService()},{refocusCamera:t});this.setModelContainer(i),(await Ja(this.allScenes,this.stepSelections)).filter(o=>o).map(o=>o.renderableSteps).flat().filter(o=>o.type===Xe.Model||o.type===Xe.Material).forEach(o=>{if(!o.option?.id){console.error(`Failed to read option id from step: ${o.stepName}`);return}const l=this.stepSelections[o.stepName]?.selectedVariants||[];if(l.length===0)return;const u=l[0];if(o.type===Xe.Model){if(!this.modelContainer)throw new nn("We should always have a model container when injecting a preview!");const c=u.asset?.fileLink;if(!c){console.error(`Failed to read model url from variant: ${u.id} for step: ${o.stepName}`);return}const f=o.data;this.modelContainer.applyModelVariant(o.stepName,{model:c,contextService:this.getLayoutPreviewService()},f.replaceProductModel||!1)}else{const c=u.material;if(!c){console.error(`Failed to read material from variant: ${u.id} for step: ${o.stepName}`);return}o.data.targetMaterials.forEach(d=>{if(!this.modelContainer)throw new nn("We should always have a model container when injecting a preview!");this.modelContainer.applyMaterialVariant(d,o.option.id,c)})}}),await i.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(e,t){const n={...this.storage,[e]:{...this.storage[e],...t}};if(!vf(n,this.storage)){this.storage=n;const i=new BS(this.constructSerializableWorkflow());this.commandContext.apply(i,!0),this.onStepSpecificStorageChange(e),this.onStorageChange()}}constructSerializableWorkflow(){const e=[];return this.allScenes.forEach(t=>{t.renderableSteps.forEach(n=>{const i={stepName:n.stepName};i.storage=this.storage[n.stepName],i.selectedVariants=this.stepSelections[n.stepName]?.selectedVariants?.map(a=>({id:a.id,priceModifier:a.priceModifier})),e.push(i)})}),{steps:e}}updateStateWithServer(){if(this.readOnly)return;const e=this.serialize();this.workflowStatePromiseQueue.enqueue(new EE(async()=>{await new Promise(t=>{setTimeout(()=>{t()},1)}),await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:e}})}))}async updateStateWithServerImmediate(){if(this.readOnly)return;const e=this.serialize();return new EE(async()=>{await this.updateTransaction({variables:{id:this.experience.getTransaction().id,workflowState:e}})}).execute()}serialize(){const e=this.getCommandContext().getState();if(!e)throw new nn("Attempted to serialize state before it was initialized.");const t=mo(e.transaction),n=D9(t);return JSON.stringify(n,P9,void 0)}async getStateHash(){const e=this.getCommandContext().getState(),n=Object.values(e?.transaction.layouts||{}).map(s=>s.modificationID??"").sort().join(""),a=new TextEncoder().encode(n);if(typeof window<"u"&&window.crypto&&window.crypto.subtle&&window.crypto.subtle.digest){const s=await window.crypto.subtle.digest("SHA-256",a);return Array.from(new Uint8Array(s)).map(u=>u.toString(16).padStart(2,"0")).join("")}try{return(await import("crypto")).createHash("sha256").update(n,"utf8").digest("hex")}catch{throw new Error("Unable to compute SHA-256 hash: no suitable crypto implementation available.")}}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(e,t){this.stepMetadata={...this.stepMetadata,[e]:{...this.stepMetadata[e],...t}},this.onMetadataChange()}removeElements(e){const t=(n,i)=>Object.keys(n).reduce((a,s)=>{const o=[...n[s]||[]];return i.forEach(l=>{const u=o.findIndex(c=>c.id===l.id);u>-1&&o.splice(u,1)}),a[s]=o,a},{});this.stepElements=t(this.stepElements,e)}async getInvalidCanvasRegions(){let e=[];for(const t of this.experience.getWorkflow()?.steps||[])if(!await co(t,this.stepSelections)&&this.stepElements[t.stepName])for(const n of this.stepElements[t.stepName])e.push(n);return e}async getInvalidModelVariants(){let e=[];for(const t of this.experience.getWorkflow()?.steps||[])t.type===Xe.Model&&!await co(t,this.stepSelections)&&e.push(t.stepName);return e}async stepElementsForIntroducedSilentSteps(e,t){const n=this.experience.getProduct();if(!n)return Promise.resolve({stepElements:{},commands:[]});const i=async(u,c,f)=>{if(u.type===Xe.SilentIllustration){const d=await new MS(u,c).trigger();return{step:u,results:d}}else if(u.type===Xe.ProductOverlay){const d=await new MS(u,c,f).trigger();return{step:u,results:d}}return Promise.reject("Unknown silent step. This is a bug")},a=e.filter(u=>!this.stepInitialised[u.stepName]),s={stepElements:{},commands:[]},o=[];for(const u of a)this.markStepsAsInitialised([u.stepName]),t||o.push(i(u,this.layouts,n));const l=await Promise.all(o);for(const u of l)s.stepElements[u.step.stepName]=u.results.map(c=>c.regionElement),s.commands=[...s.commands,...u.results.map(c=>c.command)];return s}getStepStorage(e){return this.storage[e]}getMetadata(e){return this.stepMetadata[e]}getWorkflowMetadata(){return this.stepMetadata}getStepTags(e){return this.stepTags[e]||[]}getSerializedStep(e,t){return t.find(n=>n.stepName===e)}async updateTransactionShareActions(){const e=await this.client.getShareActionsForTransaction(this.experience.getTransaction().id);this.experience.getTransaction().transactionShareActions=e}async updateTransactionStakeholders(){const e=await ze.getShadowGraphqlClient().query({query:H3,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id}});!e?.data?.transactions||e.data.transactions.length!==1?(this.experience.getTransaction().currentStakeholder=void 0,this.experience.getTransaction().stakeholders=void 0):(this.experience.getTransaction().stakeholders=e.data.transactions[0].stakeholders,this.experience.getTransaction().currentStakeholder=e.data.transactions[0].currentStakeholder)}async approveTransaction(e){await ze.getShadowGraphqlClient().mutate({mutation:C9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:e}})}async rejectTransaction(e){await ze.getShadowGraphqlClient().mutate({mutation:x9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.experience.getTransaction().id,note:e}})}async reset(){this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},await this.ensureStepsAreLoaded()}async setSelectionsAndElements(e,t,n,i){const a=this.experience.getWorkflow();if(!a)throw new Error("Attempted to set selections when no workflow is set!");const s=this.stepSelections;this.stepSelections={...this.stepSelections,[e]:{selectedVariants:t}};for(const R of a.steps)await co(R,this.stepSelections)||(this.stepInitialised[R.stepName]=!1,delete this.stepMetadata[R.stepName],delete this.stepSelections[R.stepName],delete this.storage[R.stepName]);const o=this.allScenes,l=await Ja(o,s),u=await Ja(o,this.stepSelections),c=l.map(R=>R.silentSteps).flat(),d=u.map(R=>R.silentSteps).flat().filter(R=>!c.some(B=>B.stepName===R.stepName));for(const R of c)await co(R,this.stepSelections)||(this.stepInitialised[R.stepName]=!1);const h=await this.getInvalidCanvasRegions(),{stepElements:g,commands:v}=await this.stepElementsForIntroducedSilentSteps(d,!1);this.stepElements={...this.stepElements,...g,[e]:n},this.removeElements(h);const y=a.steps.find(R=>R.stepName===e);y?.type===Xe.Frame&&this.getWorkflowExperience().getStepById(y.stepName)?.frameService?.setTargetElements(n.map(B=>B.id));const A=h.map(R=>new Ol(R.id)),C=new BS(this.constructSerializableWorkflow()),S=[...v,...A,C];S.length>0&&this.commandContext.apply(new In(S),!0),await this.ensureStepsAreLoaded(),this.selectionCost=Object.values(this.stepSelections).reduce((R,B)=>R+B.selectedVariants.map(j=>j.priceModifier||0).reduce((j,G)=>j+G,0),0),this.onElementsChange();const F=await this.getInvalidModelVariants(),E=this.modelContainer;if(E){const R=F.map(B=>E.applyModelVariant(B,{contextService:this.getLayoutPreviewService()},!1));await Promise.all(R)}await this.onSelectionChange(),await this.reapplyMaterialSteps(),y?.type!==Xe.Frame&&y?.type!==Xe.Text&&this.setMandatoryFulfilled(e,!0),i&&await i()}async ensureStepsAreLoaded(){const t=(await Ja(this.allScenes,this.stepSelections)).map(l=>l.renderableSteps),n=[],i=t.flat();console.log("[ensureStepsAreLoaded] All steps:",i);for(const l of i)if(!this.stepInitialised[l.stepName])switch(this.stepInitialised[l.stepName]=!0,l.type){case Xe.DigitalContent:n.push(F1.init(l,this,this.reloadedState));break;case Xe.Frame:n.push(so.init(l,this,this.reloadedState));break;case Xe.Illustration:n.push(Jd.init(l,this,this.reloadedState));break;case Xe.Material:n.push(I1.init(l,this,this.reloadedState));break;case Xe.Model:n.push(P1.init(l,this,this.reloadedState));break;case Xe.Module:this.stepSpecificServices[l.stepName]={module:await cI(l.data.module)},n.push(D1.init(l,this,this.reloadedState));break;case Xe.Picture:n.push(R1.init(l,this,this.reloadedState));break;case Xe.Question:n.push(O1.init(l,this,this.reloadedState));break;case Xe.Shape:n.push(Nu.init(l,this,this.reloadedState));break;case Xe.Text:n.push(ri.init(l,this,this.reloadedState));break}const a=(await Promise.allSettled(n)).map(l=>{if(l.status==="rejected")throw new Error(`Step initialization failed: ${l.reason}`);return l.value}),s=a.flatMap(l=>l?.command?[l.command]:[]),o=a.flatMap(l=>l?.followup?[l.followup]:[]);s&&s.length>0&&this.commandContext.apply(new In(s),!0);for(const l of o)await l();o.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach(e=>e(this.confirmedDesign))}onEditedChange(){this.editedCallbacks.forEach(e=>e(this.editedSteps))}onElementsChange(){this.elementsCallbacks.forEach(e=>e(this.stepElements))}onInformationResultChange(){this.informationResultCallbacks.forEach(e=>e(this.informationResults))}onInitChange(){this.initCallbacks.forEach(e=>e(this.stepInitialised))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach(e=>{e(this.currentAdjustingStepId)})}onMandatoryChange(){this.mandatoryCallbacks.forEach(e=>e(this.mandatorySteps))}onMetadataChange(){this.metadataCallbacks.forEach(e=>{e(this.stepMetadata)})}async onSelectionChange(){const e=await this.traversableScenes();for(const t of this.selectionCallbacks)t({selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:e})}onStepSpecificStorageChange(e){Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].forEach(t=>t(this.storage[e]))}onStorageChange(){this.storageCallbacks.forEach(e=>e(this.storage))}onValidationChange(){this.validationCallbacks.forEach(e=>e(this.validationErrors))}traversableScenes(){return O_(this.allScenes,this.stepSelections,this.singleVariantsRenderable)}async reapplyMaterialSteps(){if(!this.modelContainer)return;const t=(await Ja(this.allScenes,this.stepSelections)).flatMap(n=>n.renderableSteps).filter(n=>n.type===Xe.Material);for(const n of t){const i=this.stepSelections[n.stepName]?.selectedVariants;if(!i||i.length===0)continue;const s=i[0].material;if(!s||!n.option?.id)continue;n.data.targetMaterials.forEach(l=>{this.modelContainer?.applyMaterialVariant(l,n.option.id,s)})}}};af.configurationPromiseMap=new Map;let fA=af;class Fa{constructor(e){this.variantData=e}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(e,t){return this.variantData.priceModifier.toLocaleString(e||"en-US",{style:"currency",currency:"USD",...t})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.asset?.fileLink}getAssetResource(){return this.variantData.asset}getThumbnail(e=256,t){const n=this.variantData.thumbnail;if(!(!n||!n.fileLink))return $g(n,e,"webp",t)}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}getCategory(){return this.variantData.category}getProduct(){return this.variantData.product}}const sf=class sf{constructor(e,t,n){this.manager=e,this.step=t,this.tags=n}setUpdateState(e){sf.updateState.set(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`,e)}getUpdateState(){return!!sf.updateState.get(`${this.step.stepName}-${this.manager.getWorkflowExperience().getTransaction().id}`)}getCurrentVariant(){const n=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(n)return new Fa(n)}async getAvailableVariants(){return(await this.getAllVariants()).filter(t=>t.isEnabled())||[]}async getAllVariants(){if(!this.step.option?.id)return[];if(this.step.option.variants)return(this.step.option.variants||[]).map(t=>new Fa(t))||[];const e=await ct.getOption(this.step.option?.id);if(!e)throw new Error("Option not found, cannot fetch variants.");return(e.variants||[]).map(t=>new Fa(t))||[]}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(e){return this.tags.includes(e)||!1}getMandatory(){return this.step.mandatory||!1}getOverrideGlobalPropertyConfiguration(e){return(this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{})[e.toString()]??!1}setOverrideGlobalPropertyConfiguration(e,t){const n=this.manager.getStepStorage(this.step.stepName)?.overrideGlobalConfigurations??{};this.manager.updateStorage(this.step.stepName,{overrideGlobalConfigurations:{...n,[e.toString()]:t}})}getGlobalPropertyAspects(e){return this.step.globalPropertyAspectConfigurations?.filter(t=>t.globalPropertyConfigurationId===e&&t.aspectName).map(t=>t.aspectName)??[]}executeAnimations(e){const t=this.manager.getPreviewService(),n=this.manager.getModelContainer(),i=this.step.data.modelAnimation,a=this.step.data.lookAtAnimation;t?a&&t.executeCameraAnimation(a):console.warn("No preview service available, cannot execute camera animations."),n?i&&n.executeAnimation(i,e):console.warn("No model container available, cannot execute model animations.")}};sf.updateState=new Map;let Ui=sf;class yI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(e){if(!this.getUpdateState()&&this.getCurrentVariant()!==e)return Jd.selectVariant(this.step,e.getResource(),this.manager.getRegionElements(this.step.stepName)||[],t=>this.setUpdateState(t),this.manager)}getColors(){const e=this.manager.getRegionElements(this.step.stepName)||[];if(e.length===0)return;const n=Un(e[0].id,this.manager.getAllLayoutData()).colors,a=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration,s=a?.defaultColorVariants||[];if(s.length!==0){const o={};return s.forEach(l=>{const u=a.channelNumbers.find(c=>c.number===l.channelNumber);if(u){const c=u.id.replace(/\W/g,"");o[l.channelNumber]={browserValue:n[c]?.browserValue||""}}}),o}try{return n}catch(o){console.error(o)}}setColor(e,t,n){const i=new Map,s=this.getCurrentVariant()?.getAssetResource()?.assetConfiguration;return(s?.defaultColorVariants||[]).length!==0?s.channelNumbers.forEach(l=>{if(l.number.toString()===e){const u=l.id.replace(/\W/g,"");n?i.set(u,{browserValue:t,pmsValue:n}):i.set(u,t)}}):n?i.set(e,{browserValue:t,pmsValue:n}):i.set(e,t),Jd.changeColors(this.step,this.manager.getRegionElements(this.step.stepName),this.manager,i)}async getColorOption(){return await ct.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?Jd.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}isPMSPickerEnabled(){return this.step.data.pmsPickerEnabled??!1}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class AI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){return I1.selectVariant(this.step,e.getResource(),this.manager,t=>this.setUpdateState(t))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class wI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){return P1.selectVariant(this.step,e.getResource(),this.manager,t=>this.setUpdateState(t))}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class bI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){return R1.selectVariant(this.step,e.getResource(),this.manager,t=>this.setUpdateState(t))}isVariantSearchEnabled(){return this.step.data.enableVariantSearch??!1}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class CI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(e){if(!e.getId())throw new Error("Unable to select variant with a null ID");await O1.selectVariant(this.step,e.getId(),this.manager)}async getDisplayType(){return this.step.data.displayType?this.step.data.displayType:(await ct.getOptionForStep(this.step))?.displayType}}class xI extends Ui{constructor(e,t,n){super(e,t,n)}selectVariant(e){const t=e.getResource();return Nu.selectVariant(this.step,{fill:t.color,stroke:t.color,variant:t},this.manager.getRegionElements(this.step.stepName)||[],this.manager)}setColor(e){return Nu.selectVariant(this.step,e,this.manager.getRegionElements(this.step.stepName)||[],this.manager)}getColors(){return Nu.availableColours(this.step)}setCustomColor(e){return this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`),Nu.setCustomColor(e,this.step,this.manager)}getCustomColor(){this.getCurrentVariant()?.getColor()!=="#custom"&&console.warn(`setting custom color for step ${this.step.stepName} but color is ${this.getCurrentVariant()?.getColor()}`);const e=this.manager.getStepStorage(this.step.stepName)?.colour;if(!e)throw new Error(`Color not available on step ${this.step.stepName}. Set a default on the workflow to fix this.`);return e}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class SI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(e){await ri.selectVariant(this.step,e.getResource(),this.manager,t=>{if(t)this.manager.setInformationResults([...this.manager.getInformationResults(),{message:t,messageType:Jf.Error,stepID:this.step.stepName}]);else{const n=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(n)}},()=>{})}async getAvailableFillColors(){return this.step.data.colorPickerEnabled?ri.availableFillColors(this.step):[]}async setFillColor(e){const t=this.manager.getRegionElements(this.step.stepName);await ri.changeFillColor(this.step,e,t,this.manager)}getFillColor(){return this.manager.getStepStorage(this.step.stepName)?.color||"#000000"}getAvailableFillImages(){return ri.availableFillImages(this.step)}async setFillImage(e){const t=this.manager.getRegionElements(this.step.stepName);await ri.changeFillImage(this.step,e,t,this.manager)}getFillImage(){return this.manager.getStepStorage(this.step.stepName)?.fillImage}getAlignment(){return ri.findLayoutElements(this.manager,this.step)?.[0].align}setAlignment(e){const t=this.manager.getRegionElements(this.step.stepName);ri.changeAlignment(this.step,e,t,this.manager)}setFullTextCustomization(e){const t=this.manager.getStepStorage(this.step.stepName)?.inputText||"",n=this.step.data.replaceableText!==void 0?this.step.data.replaceableText.replace("{{}}",t):t,i=e?n:this.step.data.defaultText;return this.manager.updateStorage(this.step.stepName,{customiseAllText:e,text:i,defaultCleared:!1}),this.setText(i)}setText(e){const t={input:e,helperData:{}},n=ri.findLayoutElements(this.manager,this.step),i=ri.filterUnsupportedCharacters(e,n[0]?.fontData),a=ju(i,this.manager).length,s=!!this.step.data&&!!this.step.data.maxLength&&a>this.step.data.maxLength;s||(t.input=i);const o=n.length<=0,l=o?{inputText:i,text:i}:{inputText:i};this.manager.updateStorage(this.step.stepName,l);const u=this.manager.getStepStorage(this.step.stepName),c=ri.getProcessedInput(i,this.step.data,u?.customiseAllText??!1);if(o)s||this.manager.updateMetadata(this.step.stepName,{text:c});else{const{command:f,errorData:d,helperData:h}=ri.updateInputText(i,n,this.step,this.manager);f&&this.manager.getCommandDispatcher()(f),t.helperData=h,t.errorData=d,!s&&!d&&this.manager.updateMetadata(this.step.stepName,{text:c})}return t}getText(){const e=this.step.data.defaultText,t=this.manager.getStepStorage(this.step.stepName);return e&&t?.defaultCleared!==void 0&&!t?.defaultCleared?e:this.manager.getStepStorage(this.step.stepName)?.text||""}isReplaceable(){return this.step.data.userCanReplaceText}newLinesSupported(){return this.step.data.allowNewlines||!1}clearDefaultTextIfNecessary(){if(!this.manager.getStepStorage(this.step.stepName)?.defaultCleared&&this.step.data.deleteDefaultOnFocus){const t=this.setText("");this.manager.updateStorage(this.step.stepName,{defaultCleared:!0,inputText:""});const n=ri.findLayoutElements(this.manager,this.step);return ri.updateInputText("",n,this.step,this.manager),t}}hasColorPicker(){return this.step.data.colorPickerEnabled}getRegions(){return this.step.data.regions}getCharacterLimit(){return this.step.data.maxLength}getCharactersRemaining(){const e=this.step.data.maxLength;if(e===void 0)return;const t=ju(this.getText(),this.manager);return e-t.length}setCustomColor(e){this.getFillColor()!=="#custom"&&console.warn(`setting custom color for text step ${this.step.stepName} but current fill is not #custom`);const t=this.manager.getRegionElements(this.step.stepName);ri.applyCustomFillColor(this.step,e,t,this.manager)}getCustomColor(){return this.manager.getStepStorage(this.step.stepName)?.customColor||"#000000"}async getAvailableStrokeColors(){return this.step.data.strokeEnabled?ri.availableStrokeColors(this.step):[]}getStrokeColor(){return this.manager.getStepStorage(this.step.stepName)?.strokeColor?.browserValue||"#000000"}async setStrokeColor(e){const t=this.manager.getRegionElements(this.step.stepName);await ri.changeStrokeColor(this.step,e,t,this.manager)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}class EI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){}getContent(){return this.step.data.content}}class kI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){}getPreviewURL(){return this.manager.getStepStorage(this.step.stepName)?.videoUrl||""}async selectVideo(e){return F1.regenerateQRCode(this.manager.getRegionElements(this.step.stepName),e.key,this.manager,this.step)}}class TI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){console.info("Text Modules don't support variants.")}getCharactersRemaining(){const e=this.step.data.maxLength;if(e===void 0)return;const t=ju(this.getText(),this.manager);return e-t.length}getCharacterLimit(){return this.step.data.maxLength}getText(){return this.manager.getStepStorage(this.step.stepName)?.text||""}setText(e){D1.changeText(this.step,e,this.manager,t=>{if(t){const n=[...this.manager.getInformationResults(),{message:t,messageType:Jf.Error,stepID:this.step.stepName}];this.manager.setInformationResults(n)}else{const n=this.manager.getInformationResults().filter(i=>i.stepID!==this.step.stepName);this.manager.setInformationResults(n)}})}}class FI extends Ui{constructor(e,t,n){super(e,t,n)}async selectVariant(){}async getAvailableVariants(){const e=await super.getAvailableVariants();if(!this.cachedProductIds){this.cachedProductIds=new Set;for(const t of e){const n=t.getProduct();n?.id&&this.cachedProductIds.add(n.id)}}return e}isPersonalisable(e){const t=e.getProduct();return!!t?.workflows&&t.workflows.length>0}async addProduct(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)throw new Error("Product step requires bundle context");const n=e.getProduct();if(!n)throw new Error("Variant has no product. Ensure the option query includes the product field on variants.");if(!this.isPersonalisable(e)){await this.incrementNonPersonalisable(e);return}const i=this.manager.getWorkflowExperience().getTransaction(),a=i.integrationProduct?.integration?.id;let s;if(a&&n.integrationProducts&&(s=n.integrationProducts.find(d=>d.integration?.id===a)?.id),!s)throw new Error("No integration product found for bundle context");const o=this.manager.getClient(),l=n?.workflows||[];let u;if(l.length===1)u=l[0].id;else if(l.length>1){const f=this.step.data.workflows,d=l.find(h=>f.includes(h.id));if(d)u=d.id;else throw new Error("Multiple workflows available but none match step configuration")}const c=await o.getWorkflowExperience({type:"integration",integrationProductId:s,workflowId:u,parentTransactionId:i.id});await t.addWorkflowExperience(c)}async incrementNonPersonalisable(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)return;const n=e.getProduct(),i=this.findExperienceForProduct(n.id);if(i){const c=i.getTransaction().quantity||1;await i.setQuantity(c+1);return}const a=this.manager.getWorkflowExperience().getTransaction(),s=a.integrationProduct?.integration?.id;let o;if(s&&n.integrationProducts&&(o=n.integrationProducts.find(f=>f.integration?.id===s)?.id),!o)throw new Error("No integration product found for bundle context");const u=await this.manager.getClient().getWorkflowExperience({type:"integration",integrationProductId:o,parentTransactionId:a.id});await t.addWorkflowExperience(u)}async removeProduct(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)throw new Error("Product step requires bundle context");const i=t.getWorkflowExperiences().find(o=>o.getTransaction().id===e);if(!i)throw new Error("Transaction is not a child of this product step");const a=i.getTransaction(),s=a.quantity||1;if(s>1){await i.setQuantity(s-1);return}await t.removeWorkflowExperienceByTransaction(a)}isCategoryFilterEnabled(){return this.step.data.categoryFilterEnabled??!1}isSearchBarEnabled(){return this.step.data.searchBarEnabled??!1}getMin(){return this.step.data.min}getMax(){return this.step.data.max}getPricing(){return this.step.data.pricing}getWorkflows(){return this.step.data.workflows||[]}getChildTransactions(){const e=this.manager.getWorkflowExperience().getBundle();if(!e)return[];const t=this.manager.getWorkflowExperience().getTransaction().id,n=e.getWorkflowExperiences(),i=this.getStepProductIds();return n.map(a=>a.getTransaction()).filter(a=>a.parentTransaction?.id!==t||i.size===0?!1:a.product?.id?i.has(a.product.id):!1)}getStepProductIds(){if(this.cachedProductIds&&this.cachedProductIds.size>0)return this.cachedProductIds;const e=this.step.option?.variants||[],t=new Set;for(const n of e)n.product?.id&&t.add(n.product.id);return t}getLockedAddOns(){return this.step.data.lockedAddOns||[]}findExperienceForProduct(e){const t=this.manager.getWorkflowExperience().getBundle();if(!t)return;const n=this.manager.getWorkflowExperience().getTransaction().id,i=this.getStepProductIds();return t.getWorkflowExperiences().find(a=>{const s=a.getTransaction();return s.parentTransaction?.id!==n||i.size>0&&!i.has(e)?!1:s.product?.id===e})}}class Ep{static get(e,t){switch(t.type){case Xe.DigitalContent:return new kI(e,t,e.getStepTags(t.stepName));case Xe.Information:return new EI(e,t,e.getStepTags(t.stepName));case Xe.Question:return new CI(e,t,e.getStepTags(t.stepName));case Xe.Text:return new SI(e,t,e.getStepTags(t.stepName));case Xe.Illustration:return new yI(e,t,e.getStepTags(t.stepName));case Xe.Picture:return new bI(e,t,e.getStepTags(t.stepName));case Xe.Shape:return new xI(e,t,e.getStepTags(t.stepName));case Xe.Material:return new AI(e,t,e.getStepTags(t.stepName));case Xe.Model:return new wI(e,t,e.getStepTags(t.stepName));case Xe.Frame:return new XP(e,t,e.getStepTags(t.stepName));case Xe.Module:return new TI(e,t,e.getStepTags(t.stepName));case Xe.Product:return new FI(e,t,e.getStepTags(t.stepName));default:throw new nn(`Step type ${t.type} not yet supported in Core SDK`)}}}var Dv,TE;function B9(){if(TE)return Dv;TE=1;var r=1/0,e=9007199254740991,t=17976931348623157e292,n=NaN,i="[object Function]",a="[object GeneratorFunction]",s="[object Symbol]",o=/^\s+|\s+$/g,l=/^[-+]0x[0-9a-f]+$/i,u=/^0b[01]+$/i,c=/^0o[0-7]+$/i,f=/^(?:0|[1-9]\d*)$/,d=parseInt,h=Object.prototype,g=h.toString,v=Math.ceil,y=Math.max;function A(oe,he,ye){var Ue=-1,Re=oe.length;he<0&&(he=-he>Re?0:Re+he),ye=ye>Re?Re:ye,ye<0&&(ye+=Re),Re=he>ye?0:ye-he>>>0,he>>>=0;for(var Oe=Array(Re);++Ue<Re;)Oe[Ue]=oe[Ue+he];return Oe}function C(oe,he){return he=he??e,!!he&&(typeof oe=="number"||f.test(oe))&&oe>-1&&oe%1==0&&oe<he}function S(oe,he,ye){if(!G(ye))return!1;var Ue=typeof he;return(Ue=="number"?R(ye)&&C(he,ye.length):Ue=="string"&&he in ye)?E(ye[he],oe):!1}function F(oe,he,ye){(ye?S(oe,he,ye):he===void 0)?he=1:he=y(J(he),0);var Ue=oe?oe.length:0;if(!Ue||he<1)return[];for(var Re=0,Oe=0,ee=Array(v(Ue/he));Re<Ue;)ee[Oe++]=A(oe,Re,Re+=he);return ee}function E(oe,he){return oe===he||oe!==oe&&he!==he}function R(oe){return oe!=null&&j(oe.length)&&!B(oe)}function B(oe){var he=G(oe)?g.call(oe):"";return he==i||he==a}function j(oe){return typeof oe=="number"&&oe>-1&&oe%1==0&&oe<=e}function G(oe){var he=typeof oe;return!!oe&&(he=="object"||he=="function")}function ie(oe){return!!oe&&typeof oe=="object"}function q(oe){return typeof oe=="symbol"||ie(oe)&&g.call(oe)==s}function Y(oe){if(!oe)return oe===0?oe:0;if(oe=ae(oe),oe===r||oe===-r){var he=oe<0?-1:1;return he*t}return oe===oe?oe:0}function J(oe){var he=Y(oe),ye=he%1;return he===he?ye?he-ye:he:0}function ae(oe){if(typeof oe=="number")return oe;if(q(oe))return n;if(G(oe)){var he=typeof oe.valueOf=="function"?oe.valueOf():oe;oe=G(he)?he+"":he}if(typeof oe!="string")return oe===0?oe:+oe;oe=oe.replace(o,"");var ye=u.test(oe);return ye||c.test(oe)?d(oe.slice(2),ye?2:8):l.test(oe)?n:+oe}return Dv=F,Dv}var M9=B9();const hA=Ns(M9),_9=Se`
2656
2656
  fragment CreateDesignTransaction on Transaction {
2657
2657
  id
2658
2658
  designName
@@ -3039,7 +3039,7 @@ Minimum version required to store current data is: `+q+`.
3039
3039
  `;class EV{constructor(e,t=ze.getShadowGraphqlClient.bind(ze)){this.options=e,this.client=t}query(e){const t=this.options?.onQuery?this.options?.onQuery(e):{};return this.client().query({...t,...e,context:{...t.context??{},...e.context??{}}})}mutate(e){const t=this.options?.onMutate?this.options?.onMutate(e):{};return this.client().mutate({...t,...e,context:{...t.context??{},...e.context??{}}})}}function kV(r,e,t){return r.$source||(r.$source={}),r.$source[e]=t,r}const TV=r=>r?.body instanceof ReadableStream,fl=(r,e)=>{const t=[];if(r&&t.push(r),e)for(const n of e)t.push(n);return t},to=(r,e)=>`${r||"anonymous"}${e&&e.length>0?` (a.k.a. ${e.join(",")})`:""}`,wg=()=>{let r=[],e=[],t=!1;const n=new Set,i=f=>f.sort((d,h)=>BE[h.step]-BE[d.step]||ME[h.priority||"normal"]-ME[d.priority||"normal"]),a=f=>{let d=!1;const h=g=>{const v=fl(g.name,g.aliases);if(v.includes(f)){d=!0;for(const y of v)n.delete(y);return!1}return!0};return r=r.filter(h),e=e.filter(h),d},s=f=>{let d=!1;const h=g=>{if(g.middleware===f){d=!0;for(const v of fl(g.name,g.aliases))n.delete(v);return!1}return!0};return r=r.filter(h),e=e.filter(h),d},o=f=>(r.forEach(d=>{f.add(d.middleware,{...d})}),e.forEach(d=>{f.addRelativeTo(d.middleware,{...d})}),f.identifyOnResolve?.(c.identifyOnResolve()),f),l=f=>{const d=[];return f.before.forEach(h=>{h.before.length===0&&h.after.length===0?d.push(h):d.push(...l(h))}),d.push(f),f.after.reverse().forEach(h=>{h.before.length===0&&h.after.length===0?d.push(h):d.push(...l(h))}),d},u=(f=!1)=>{const d=[],h=[],g={};return r.forEach(y=>{const A={...y,before:[],after:[]};for(const C of fl(A.name,A.aliases))g[C]=A;d.push(A)}),e.forEach(y=>{const A={...y,before:[],after:[]};for(const C of fl(A.name,A.aliases))g[C]=A;h.push(A)}),h.forEach(y=>{if(y.toMiddleware){const A=g[y.toMiddleware];if(A===void 0){if(f)return;throw new Error(`${y.toMiddleware} is not found when adding ${to(y.name,y.aliases)} middleware ${y.relation} ${y.toMiddleware}`)}y.relation==="after"&&A.after.push(y),y.relation==="before"&&A.before.push(y)}}),i(d).map(l).reduce((y,A)=>(y.push(...A),y),[])},c={add:(f,d={})=>{const{name:h,override:g,aliases:v}=d,y={step:"initialize",priority:"normal",middleware:f,...d},A=fl(h,v);if(A.length>0){if(A.some(C=>n.has(C))){if(!g)throw new Error(`Duplicate middleware name '${to(h,v)}'`);for(const C of A){const S=r.findIndex(E=>E.name===C||E.aliases?.some(R=>R===C));if(S===-1)continue;const F=r[S];if(F.step!==y.step||y.priority!==F.priority)throw new Error(`"${to(F.name,F.aliases)}" middleware with ${F.priority} priority in ${F.step} step cannot be overridden by "${to(h,v)}" middleware with ${y.priority} priority in ${y.step} step.`);r.splice(S,1)}}for(const C of A)n.add(C)}r.push(y)},addRelativeTo:(f,d)=>{const{name:h,override:g,aliases:v}=d,y={middleware:f,...d},A=fl(h,v);if(A.length>0){if(A.some(C=>n.has(C))){if(!g)throw new Error(`Duplicate middleware name '${to(h,v)}'`);for(const C of A){const S=e.findIndex(E=>E.name===C||E.aliases?.some(R=>R===C));if(S===-1)continue;const F=e[S];if(F.toMiddleware!==y.toMiddleware||F.relation!==y.relation)throw new Error(`"${to(F.name,F.aliases)}" middleware ${F.relation} "${F.toMiddleware}" middleware cannot be overridden by "${to(h,v)}" middleware ${y.relation} "${y.toMiddleware}" middleware.`);e.splice(S,1)}}for(const C of A)n.add(C)}e.push(y)},clone:()=>o(wg()),use:f=>{f.applyToStack(c)},remove:f=>typeof f=="string"?a(f):s(f),removeByTag:f=>{let d=!1;const h=g=>{const{tags:v,name:y,aliases:A}=g;if(v&&v.includes(f)){const C=fl(y,A);for(const S of C)n.delete(S);return d=!0,!1}return!0};return r=r.filter(h),e=e.filter(h),d},concat:f=>{const d=o(wg());return d.use(f),d.identifyOnResolve(t||d.identifyOnResolve()||(f.identifyOnResolve?.()??!1)),d},applyToStack:o,identify:()=>u(!0).map(f=>{const d=f.step??f.relation+" "+f.toMiddleware;return to(f.name,f.aliases)+" - "+d}),identifyOnResolve(f){return typeof f=="boolean"&&(t=f),t},resolve:(f,d)=>{for(const h of u().map(g=>g.middleware).reverse())f=h(f,d);return t&&console.log(c.identify()),f}};return c},BE={initialize:5,serialize:4,build:3,finalizeRequest:2,deserialize:1},ME={high:3,normal:2,low:1};var xf;(function(r){r.HTTP="http",r.HTTPS="https"})(xf||(xf={}));var Sf;(function(r){r.MD5="md5",r.CRC32="crc32",r.CRC32C="crc32c",r.SHA1="sha1",r.SHA256="sha256"})(Sf||(Sf={}));const vA="__smithy_context",vc=r=>r[vA]||(r[vA]={});class na{method;protocol;hostname;port;path;query;headers;username;password;fragment;body;constructor(e){this.method=e.method||"GET",this.hostname=e.hostname||"localhost",this.port=e.port,this.query=e.query||{},this.headers=e.headers||{},this.body=e.body,this.protocol=e.protocol?e.protocol.slice(-1)!==":"?`${e.protocol}:`:e.protocol:"https:",this.path=e.path?e.path.charAt(0)!=="/"?`/${e.path}`:e.path:"/",this.username=e.username,this.password=e.password,this.fragment=e.fragment}static clone(e){const t=new na({...e,headers:{...e.headers}});return t.query&&(t.query=FV(t.query)),t}static isInstance(e){if(!e)return!1;const t=e;return"method"in t&&"protocol"in t&&"hostname"in t&&"path"in t&&typeof t.query=="object"&&typeof t.headers=="object"}clone(){return na.clone(this)}}function FV(r){return Object.keys(r).reduce((e,t)=>{const n=r[t];return{...e,[t]:Array.isArray(n)?[...n]:n}},{})}class sc{statusCode;reason;headers;body;constructor(e){this.statusCode=e.statusCode,this.reason=e.reason,this.headers=e.headers||{},this.body=e.body}static isInstance(e){if(!e)return!1;const t=e;return typeof t.statusCode=="number"&&typeof t.headers=="object"}}const IV=new RegExp("^(?!.*-$)(?!-)[a-zA-Z0-9-]{1,63}$"),Kg=(r,e=!1)=>{if(!e)return IV.test(r);const t=r.split(".");for(const n of t)if(!Kg(n))return!1;return!0},Bs=r=>{if(typeof r=="function")return r;const e=Promise.resolve(r);return()=>e};function PV(r){const e={};if(r=r.replace(/^\?/,""),r)for(const t of r.split("&")){let[n,i=null]=t.split("=");n=decodeURIComponent(n),i&&(i=decodeURIComponent(i)),n in e?Array.isArray(e[n])?e[n].push(i):e[n]=[e[n],i]:e[n]=i}return e}const bg=r=>{if(typeof r=="string")return bg(new URL(r));const{hostname:e,pathname:t,port:n,protocol:i,search:a}=r;let s;return a&&(s=PV(a)),{hostname:e,port:n?parseInt(n):void 0,protocol:i,path:t,query:s}},V1=r=>{if(typeof r=="object"){if("url"in r){const e=bg(r.url);if(r.headers){e.headers={};for(const t in r.headers)e.headers[t.toLowerCase()]=r.headers[t].join(", ")}return e}return r}return bg(r)},DV=r=>()=>Promise.reject(r);class RV{config;middlewareStack=wg();initConfig;handlers;constructor(e){this.config=e;const{protocol:t,protocolSettings:n}=e;n&&typeof t=="function"&&(e.protocol=new t(n))}send(e,t,n){const i=typeof t!="function"?t:void 0,a=typeof t=="function"?t:n,s=i===void 0&&this.config.cacheMiddleware===!0;let o;if(s){this.handlers||(this.handlers=new WeakMap);const l=this.handlers;l.has(e.constructor)?o=l.get(e.constructor):(o=e.resolveMiddleware(this.middlewareStack,this.config,i),l.set(e.constructor,o))}else delete this.handlers,o=e.resolveMiddleware(this.middlewareStack,this.config,i);if(a)o(e).then(l=>a(null,l.output),l=>a(l)).catch(()=>{});else return o(e).then(l=>l.output)}destroy(){this.config?.requestHandler?.destroy?.(),delete this.handlers}}const Yp=r=>typeof r=="function"?r():r,VI=(r,e,t,n,i)=>({name:e,namespace:r,traits:t,input:n,output:i}),OV=r=>(e,t)=>async n=>{const{response:i}=await e(n),{operationSchema:a}=vc(t),[,s,o,l,u,c]=a??[];try{const f=await r.protocol.deserializeResponse(VI(s,o,l,u,c),{...r,...t},i);return{response:i,output:f}}catch(f){if(Object.defineProperty(f,"$response",{value:i,enumerable:!1,writable:!1,configurable:!1}),!("$metadata"in f)){const d="Deserialization error: to see the raw response, inspect the hidden field {error}.$response on this object.";try{f.message+=`
3040
3040
  `+d}catch{!t.logger||t.logger?.constructor?.name==="NoOpLogger"?console.warn(d):t.logger?.warn?.(d)}typeof f.$responseBodyText<"u"&&f.$response&&(f.$response.body=f.$responseBodyText);try{if(sc.isInstance(i)){const{headers:h={},statusCode:g}=i,v=Object.entries(h);f.$metadata={httpStatusCode:g,requestId:Mv(/^x-[\w-]+-request-?id$/,v),extendedRequestId:Mv(/^x-[\w-]+-id-2$/,v),cfId:Mv(/^x-[\w-]+-cf-id$/,v)}}}catch{}}throw f}},Mv=(r,e)=>(e.find(([t])=>t.match(r))||[void 0,void 0])[1],BV=r=>(e,t)=>async n=>{const{operationSchema:i}=vc(t),[,a,s,o,l,u]=i??[],c=t.endpointV2?async()=>V1(t.endpointV2):r.endpoint,f=await r.protocol.serializeRequest(VI(a,s,o,l,u),n.input,{...r,...t,endpoint:c});return e({...n,request:f})},MV={name:"deserializerMiddleware",step:"deserialize",tags:["DESERIALIZER"],override:!0},_V={name:"serializerMiddleware",step:"serialize",tags:["SERIALIZER"],override:!0};function NV(r){return{applyToStack:e=>{e.add(BV(r),_V),e.add(OV(r),MV),r.protocol.setSerdeContext(r)}}}const _v=[];function zd(r){if(typeof r=="object")return r;if(r=r|0,_v[r])return _v[r];const e={};let t=0;for(const n of["httpLabel","idempotent","idempotencyToken","sensitive","httpPayload","httpResponseCode","httpQueryParams"])(r>>t++&1)===1&&(e[n]=1);return _v[r]=e}const kd={it:Symbol.for("@smithy/nor-struct-it"),ns:Symbol.for("@smithy/ns")},Nv=[],Lv={};class vi{ref;memberName;static symbol=Symbol.for("@smithy/nor");symbol=vi.symbol;name;schema;_isMemberSchema;traits;memberTraits;normalizedTraits;constructor(e,t){this.ref=e,this.memberName=t;const n=[];let i=e,a=e;for(this._isMemberSchema=!1;Uv(i);)n.push(i[1]),i=i[0],a=Yp(i),this._isMemberSchema=!0;if(n.length>0){this.memberTraits={};for(let s=n.length-1;s>=0;--s){const o=n[s];Object.assign(this.memberTraits,zd(o))}}else this.memberTraits=0;if(a instanceof vi){const s=this.memberTraits;Object.assign(this,a),this.memberTraits=Object.assign({},s,a.getMemberTraits(),this.getMemberTraits()),this.normalizedTraits=void 0,this.memberName=t??a.memberName;return}if(this.schema=Yp(a),LV(this.schema)?(this.name=`${this.schema[1]}#${this.schema[2]}`,this.traits=this.schema[3]):(this.name=this.memberName??String(a),this.traits=0),this._isMemberSchema&&!t)throw new Error(`@smithy/core/schema - NormalizedSchema member init ${this.getName(!0)} missing member name.`)}static[Symbol.hasInstance](e){const t=this.prototype.isPrototypeOf(e);return!t&&typeof e=="object"&&e!==null?e.symbol===this.symbol:t}static of(e){const t=typeof e=="function"||typeof e=="object"&&e!==null;if(typeof e=="number"){if(Nv[e])return Nv[e]}else if(typeof e=="string"){if(Lv[e])return Lv[e]}else if(t&&e[kd.ns])return e[kd.ns];const n=Yp(e);if(n instanceof vi)return n;if(Uv(n)){const[a,s]=n;if(a instanceof vi)return Object.assign(a.getMergedTraits(),zd(s)),a;throw new Error(`@smithy/core/schema - may not init unwrapped member schema=${JSON.stringify(e,null,2)}.`)}const i=new vi(n);return t?e[kd.ns]=i:typeof n=="string"?Lv[n]=i:typeof n=="number"?Nv[n]=i:i}getSchema(){const e=this.schema;return Array.isArray(e)&&e[0]===0?e[4]:e}getName(e=!1){const{name:t}=this;return!e&&t&&t.includes("#")?t.split("#")[1]:t||void 0}getMemberName(){return this.memberName}isMemberSchema(){return this._isMemberSchema}isListSchema(){const e=this.getSchema();return typeof e=="number"?e>=64&&e<128:e[0]===1}isMapSchema(){const e=this.getSchema();return typeof e=="number"?e>=128&&e<=255:e[0]===2}isStructSchema(){const e=this.getSchema();if(typeof e!="object")return!1;const t=e[0];return t===3||t===-3||t===4}isUnionSchema(){const e=this.getSchema();return typeof e!="object"?!1:e[0]===4}isBlobSchema(){const e=this.getSchema();return e===21||e===42}isTimestampSchema(){const e=this.getSchema();return typeof e=="number"&&e>=4&&e<=7}isUnitSchema(){return this.getSchema()==="unit"}isDocumentSchema(){return this.getSchema()===15}isStringSchema(){return this.getSchema()===0}isBooleanSchema(){return this.getSchema()===2}isNumericSchema(){return this.getSchema()===1}isBigIntegerSchema(){return this.getSchema()===17}isBigDecimalSchema(){return this.getSchema()===19}isStreaming(){const{streaming:e}=this.getMergedTraits();return!!e||this.getSchema()===42}isIdempotencyToken(){return!!this.getMergedTraits().idempotencyToken}getMergedTraits(){return this.normalizedTraits??(this.normalizedTraits={...this.getOwnTraits(),...this.getMemberTraits()})}getMemberTraits(){return zd(this.memberTraits)}getOwnTraits(){return zd(this.traits)}getKeySchema(){const[e,t]=[this.isDocumentSchema(),this.isMapSchema()];if(!e&&!t)throw new Error(`@smithy/core/schema - cannot get key for non-map: ${this.getName(!0)}`);const n=this.getSchema(),i=e?15:n[4]??0;return Td([i,0],"key")}getValueSchema(){const e=this.getSchema(),[t,n,i]=[this.isDocumentSchema(),this.isMapSchema(),this.isListSchema()],a=typeof e=="number"?63&e:e&&typeof e=="object"&&(n||i)?e[3+e[0]]:t?15:void 0;if(a!=null)return Td([a,0],n?"value":"member");throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no value member.`)}getMemberSchema(e){const t=this.getSchema();if(this.isStructSchema()&&t[4].includes(e)){const n=t[4].indexOf(e),i=t[5][n];return Td(Uv(i)?i:[i,0],e)}if(this.isDocumentSchema())return Td([15,0],e);throw new Error(`@smithy/core/schema - ${this.getName(!0)} has no member=${e}.`)}getMemberSchemas(){const e={};try{for(const[t,n]of this.structIterator())e[t]=n}catch{}return e}getEventStreamMember(){if(this.isStructSchema()){for(const[e,t]of this.structIterator())if(t.isStreaming()&&t.isStructSchema())return e}return""}*structIterator(){if(this.isUnitSchema())return;if(!this.isStructSchema())throw new Error("@smithy/core/schema - cannot iterate non-struct schema.");const e=this.getSchema(),t=e[4].length;let n=e[kd.it];if(n&&t===n.length){yield*n;return}n=Array(t);for(let i=0;i<t;++i){const a=e[4][i],s=Td([e[5][i],0],a);yield n[i]=[a,s]}e[kd.it]=n}}function Td(r,e){if(r instanceof vi)return Object.assign(r,{memberName:e,_isMemberSchema:!0});const t=vi;return new t(r,e)}const Uv=r=>Array.isArray(r)&&r.length===2,LV=r=>Array.isArray(r)&&r.length>=5;class Zi{namespace;schemas;exceptions;static registries=new Map;constructor(e,t=new Map,n=new Map){this.namespace=e,this.schemas=t,this.exceptions=n}static for(e){return Zi.registries.has(e)||Zi.registries.set(e,new Zi(e)),Zi.registries.get(e)}copyFrom(e){const{schemas:t,exceptions:n}=this;for(const[i,a]of e.schemas)t.has(i)||t.set(i,a);for(const[i,a]of e.exceptions)n.has(i)||n.set(i,a)}register(e,t){const n=this.normalizeShapeId(e);for(const i of[this,Zi.for(n.split("#")[0])])i.schemas.set(n,t)}getSchema(e){const t=this.normalizeShapeId(e);if(!this.schemas.has(t)){if(!e.includes("#")){const n="#"+e,i=[];for(const[a,s]of this.schemas.entries())a.endsWith(n)&&i.push(s);if(i.length===1)return i[0]}throw new Error(`@smithy/core/schema - schema not found for ${t}`)}return this.schemas.get(t)}registerError(e,t){const n=e,i=n[1];for(const a of[this,Zi.for(i)])a.schemas.set(i+"#"+n[2],n),a.exceptions.set(n,t)}getErrorCtor(e){const t=e;return this.exceptions.has(t)?this.exceptions.get(t):Zi.for(t[1]).exceptions.get(t)}getBaseException(){for(const e of this.exceptions.keys())if(Array.isArray(e)){const[,t,n]=e,i=t+"#"+n;if(i.startsWith("smithy.ts.sdk.synthetic.")&&i.endsWith("ServiceException"))return e}}find(e){for(const t of this.schemas.values())if(e(t))return t}clear(){this.schemas.clear(),this.exceptions.clear()}normalizeShapeId(e){return e.includes("#")?e:this.namespace+"#"+e}}const Vv="***SensitiveInformation***";function yA(r,e){if(e==null)return e;const t=vi.of(r);if(t.getMergedTraits().sensitive)return Vv;if(t.isListSchema()){if(!!t.getValueSchema().getMergedTraits().sensitive)return Vv}else if(t.isMapSchema()){if(!!t.getKeySchema().getMergedTraits().sensitive||!!t.getValueSchema().getMergedTraits().sensitive)return Vv}else if(t.isStructSchema()&&typeof e=="object"){const n=e,i={};for(const[a,s]of t.structIterator())n[a]!=null&&(i[a]=yA(s,n[a]));return i}return e}class z1{middlewareStack=wg();schema;static classBuilder(){return new UV}resolveMiddlewareWithContext(e,t,n,{middlewareFn:i,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,smithyContext:u,additionalContext:c,CommandCtor:f}){for(const A of i.bind(this)(f,e,t,n))this.middlewareStack.use(A);const d=e.concat(this.middlewareStack),{logger:h}=t,g={logger:h,clientName:a,commandName:s,inputFilterSensitiveLog:o,outputFilterSensitiveLog:l,[vA]:{commandInstance:this,...u},...c},{requestHandler:v}=t;let y=n??{};return u.eventStream&&(y={isEventStream:!0,...y}),d.resolve(A=>v.handle(A.request,y),g)}}class UV{_init=()=>{};_ep={};_middlewareFn=()=>[];_commandName="";_clientName="";_additionalContext={};_smithyContext={};_inputFilterSensitiveLog=void 0;_outputFilterSensitiveLog=void 0;_serializer=null;_deserializer=null;_operationSchema;init(e){this._init=e}ep(e){return this._ep=e,this}m(e){return this._middlewareFn=e,this}s(e,t,n={}){return this._smithyContext={service:e,operation:t,...n},this}c(e={}){return this._additionalContext=e,this}n(e,t){return this._clientName=e,this._commandName=t,this}f(e=n=>n,t=n=>n){return this._inputFilterSensitiveLog=e,this._outputFilterSensitiveLog=t,this}ser(e){return this._serializer=e,this}de(e){return this._deserializer=e,this}sc(e){return this._operationSchema=e,this._smithyContext.operationSchema=e,this}build(){const e=this;let t;return t=class extends z1{input;static getEndpointParameterInstructions(){return e._ep}constructor(...[n]){super(),this.input=n??{},e._init(this),this.schema=e._operationSchema}resolveMiddleware(n,i,a){const s=e._operationSchema,o=s?.[4]??s?.input,l=s?.[5]??s?.output;return this.resolveMiddlewareWithContext(n,i,a,{CommandCtor:t,middlewareFn:e._middlewareFn,clientName:e._clientName,commandName:e._commandName,inputFilterSensitiveLog:e._inputFilterSensitiveLog??(s?yA.bind(null,o):u=>u),outputFilterSensitiveLog:e._outputFilterSensitiveLog??(s?yA.bind(null,l):u=>u),smithyContext:e._smithyContext,additionalContext:e._additionalContext})}serialize=e._serializer;deserialize=e._deserializer}}}class Lu extends Error{$fault;$response;$retryable;$metadata;constructor(e){super(e.message),Object.setPrototypeOf(this,Object.getPrototypeOf(this).constructor.prototype),this.name=e.name,this.$fault=e.$fault,this.$metadata=e.$metadata}static isInstance(e){if(!e)return!1;const t=e;return Lu.prototype.isPrototypeOf(t)||!!t.$fault&&!!t.$metadata&&(t.$fault==="client"||t.$fault==="server")}static[Symbol.hasInstance](e){if(!e)return!1;const t=e;return this===Lu?Lu.isInstance(e):Lu.isInstance(e)?t.name&&this.name?this.prototype.isPrototypeOf(e)||t.name===this.name:this.prototype.isPrototypeOf(e):!1}}const _E=(r,e={})=>{Object.entries(e).filter(([,n])=>n!==void 0).forEach(([n,i])=>{(r[n]==null||r[n]==="")&&(r[n]=i)});const t=r.message||r.Message||"UnknownError";return r.message=t,delete r.Message,r},VV=r=>{switch(r){case"standard":return{retryMode:"standard",connectionTimeout:3100};case"in-region":return{retryMode:"standard",connectionTimeout:1100};case"cross-region":return{retryMode:"standard",connectionTimeout:3100};case"mobile":return{retryMode:"standard",connectionTimeout:3e4};default:return{}}},zI=Object.values(Sf),zV=r=>{const e=[];for(const t in Sf){const n=Sf[t];r[n]!==void 0&&e.push({algorithmId:()=>n,checksumConstructor:()=>r[n]})}for(const[t,n]of Object.entries(r.checksumAlgorithms??{}))e.push({algorithmId:()=>t,checksumConstructor:()=>n});return{addChecksumAlgorithm(t){r.checksumAlgorithms=r.checksumAlgorithms??{};const n=t.algorithmId(),i=t.checksumConstructor();zI.includes(n)?r.checksumAlgorithms[n.toUpperCase()]=i:r.checksumAlgorithms[n]=i,e.push(t)},checksumAlgorithms(){return e}}},$V=r=>{const e={};return r.checksumAlgorithms().forEach(t=>{const n=t.algorithmId();zI.includes(n)&&(e[n]=t.checksumConstructor())}),e},HV=r=>({setRetryStrategy(e){r.retryStrategy=e},retryStrategy(){return r.retryStrategy}}),jV=r=>{const e={};return e.retryStrategy=r.retryStrategy(),e},GV=r=>Object.assign(zV(r),HV(r)),qV=r=>Object.assign($V(r),jV(r));class $I{trace(){}debug(){}info(){}warn(){}error(){}}const HI="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",NE=Object.entries(HI).reduce((r,[e,t])=>(r[t]=Number(e),r),{}),WV=HI.split(""),Gu=6,Zd=8,QV=63,Zg=r=>{let e=r.length/4*3;r.slice(-2)==="=="?e-=2:r.slice(-1)==="="&&e--;const t=new ArrayBuffer(e),n=new DataView(t);for(let i=0;i<r.length;i+=4){let a=0,s=0;for(let u=i,c=i+3;u<=c;u++)if(r[u]!=="="){if(!(r[u]in NE))throw new TypeError(`Invalid character ${r[u]} in base64 string.`);a|=NE[r[u]]<<(c-u)*Gu,s+=Gu}else a>>=Gu;const o=i/4*3;a>>=s%Zd;const l=Math.floor(s/Zd);for(let u=0;u<l;u++){const c=(l-u-1)*Zd;n.setUint8(o+u,(a&255<<c)>>c)}}return new Uint8Array(t)},kl=r=>new TextEncoder().encode(r);function Cg(r){let e;typeof r=="string"?e=kl(r):e=r;const t=typeof e=="object"&&typeof e.length=="number",n=typeof e=="object"&&typeof e.byteOffset=="number"&&typeof e.byteLength=="number";if(!t&&!n)throw new Error("@smithy/util-base64: toBase64 encoder function only accepts string | Uint8Array.");let i="";for(let a=0;a<e.length;a+=3){let s=0,o=0;for(let u=a,c=Math.min(a+3,e.length);u<c;u++)s|=e[u]<<(c-u-1)*Zd,o+=Zd;const l=Math.ceil(o/Gu);s<<=l*Gu-o;for(let u=1;u<=l;u++){const c=(l-u)*Gu;i+=WV[(s&QV<<c)>>c]}i+="==".slice(0,4-l)}return i}function YV(r,e,t,n){return class Xp extends Uint8Array{static fromString(a,s="utf-8"){if(typeof a=="string")return s==="base64"?Xp.mutate(n(a)):Xp.mutate(e(a));throw new Error(`Unsupported conversion from ${typeof a} to Uint8ArrayBlobAdapter.`)}static mutate(a){return Object.setPrototypeOf(a,Xp.prototype),a}transformToString(a="utf-8"){return a==="base64"?t(this):r(this)}}}const em=r=>{if(typeof r=="string")return r;if(typeof r!="object"||typeof r.byteOffset!="number"||typeof r.byteLength!="number")throw new Error("@smithy/util-utf8: toUtf8 encoder function only accepts string | Uint8Array.");return new TextDecoder("utf-8").decode(r)},Ii=Array.from({length:256},(r,e)=>e.toString(16).padStart(2,"0"));function XV(r){return typeof crypto<"u"&&typeof crypto.randomUUID=="function"?()=>crypto.randomUUID():()=>{const e=new Uint8Array(16);return r(e),e[6]=e[6]&15|64,e[8]=e[8]&63|128,Ii[e[0]]+Ii[e[1]]+Ii[e[2]]+Ii[e[3]]+"-"+Ii[e[4]]+Ii[e[5]]+"-"+Ii[e[6]]+Ii[e[7]]+"-"+Ii[e[8]]+Ii[e[9]]+"-"+Ii[e[10]]+Ii[e[11]]+Ii[e[12]]+Ii[e[13]]+Ii[e[14]]+Ii[e[15]]}}const AA=r=>{if(r!=null){if(typeof r=="string"){const e=parseFloat(r);if(!Number.isNaN(e))return String(e)!==String(r)&&az.warn(iz(`Expected number but observed string: ${r}`)),e}if(typeof r=="number")return r;throw new TypeError(`Expected number, got ${typeof r}: ${r}`)}},JV=Math.ceil(2**127*(2-2**-23)),LE=r=>{const e=AA(r);if(e!==void 0&&!Number.isNaN(e)&&e!==1/0&&e!==-1/0&&Math.abs(e)>JV)throw new TypeError(`Expected 32-bit float, got ${r}`);return e},KV=r=>{if(r!=null){if(Number.isInteger(r)&&!Number.isNaN(r))return r;throw new TypeError(`Expected integer, got ${typeof r}: ${r}`)}},UE=r=>jI(r,16),VE=r=>jI(r,8),jI=(r,e)=>{const t=KV(r);if(t!==void 0&&ZV(t,e)!==t)throw new TypeError(`Expected ${e}-bit integer, got ${r}`);return t},ZV=(r,e)=>{switch(e){case 32:return Int32Array.of(r)[0];case 16:return Int16Array.of(r)[0];case 8:return Int8Array.of(r)[0]}},ez=r=>AA(typeof r=="string"?tm(r):r),tz=r=>LE(typeof r=="string"?tm(r):r),rz=/(-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)|(-?Infinity)|(NaN)/g,tm=r=>{const e=r.match(rz);if(e===null||e[0].length!==r.length)throw new TypeError("Expected real number, got implicit NaN");return parseFloat(r)},xg=r=>UE(typeof r=="string"?tm(r):r),nz=r=>VE(typeof r=="string"?tm(r):r),iz=r=>String(new TypeError(r).stack||r).split(`
3041
3041
  `).slice(0,5).filter(e=>!e.includes("stackTraceWarning")).join(`
3042
- `),az={warn:console.warn},sz=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],$1=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function oz(r){const e=r.getUTCFullYear(),t=r.getUTCMonth(),n=r.getUTCDay(),i=r.getUTCDate(),a=r.getUTCHours(),s=r.getUTCMinutes(),o=r.getUTCSeconds(),l=i<10?`0${i}`:`${i}`,u=a<10?`0${a}`:`${a}`,c=s<10?`0${s}`:`${s}`,f=o<10?`0${o}`:`${o}`;return`${sz[n]}, ${l} ${$1[t]} ${e} ${u}:${c}:${f} GMT`}const lz=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),uz=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const e=lz.exec(r);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");const[t,n,i,a,s,o,l,u,c]=e,f=xg(Ef(n)),d=yo(i,"month",1,12),h=yo(a,"day",1,31),g=Jp(f,d,h,{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u});return c.toUpperCase()!="Z"&&g.setTime(g.getTime()-bz(c)),g},cz=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),dz=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),fz=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),GI=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=cz.exec(r);if(e){const[t,n,i,a,s,o,l,u]=e;return Jp(xg(Ef(a)),zv(i),yo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u})}if(e=dz.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return mz(Jp(pz(a),zv(i),yo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u}))}if(e=fz.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return Jp(xg(Ef(u)),zv(n),yo(i.trimLeft(),"day",1,31),{hours:a,minutes:s,seconds:o,fractionalMilliseconds:l})}throw new TypeError("Invalid RFC-7231 date-time value")},hz=r=>{if(r==null)return;let e;if(typeof r=="number")e=r;else if(typeof r=="string")e=ez(r);else if(typeof r=="object"&&r.tag===1)e=r.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},Jp=(r,e,t,n)=>{const i=e-1;return yz(r,i,t),new Date(Date.UTC(r,i,t,yo(n.hours,"hour",0,23),yo(n.minutes,"minute",0,59),yo(n.seconds,"seconds",0,60),wz(n.fractionalMilliseconds)))},pz=r=>{const e=new Date().getUTCFullYear(),t=Math.floor(e/100)*100+xg(Ef(r));return t<e?t+100:t},gz=50*365*24*60*60*1e3,mz=r=>r.getTime()-new Date().getTime()>gz?new Date(Date.UTC(r.getUTCFullYear()-100,r.getUTCMonth(),r.getUTCDate(),r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds())):r,zv=r=>{const e=$1.indexOf(r);if(e<0)throw new TypeError(`Invalid month: ${r}`);return e+1},vz=[31,28,31,30,31,30,31,31,30,31,30,31],yz=(r,e,t)=>{let n=vz[e];if(e===1&&Az(r)&&(n=29),t>n)throw new TypeError(`Invalid day for ${$1[e]} in ${r}: ${t}`)},Az=r=>r%4===0&&(r%100!==0||r%400===0),yo=(r,e,t,n)=>{const i=nz(Ef(r));if(i<t||i>n)throw new TypeError(`${e} must be between ${t} and ${n}, inclusive`);return i},wz=r=>r==null?0:tz("0."+r)*1e3,bz=r=>{const e=r[0];let t=1;if(e=="+")t=1;else if(e=="-")t=-1;else throw new TypeError(`Offset direction, ${e}, must be "+" or "-"`);const n=Number(r.substring(1,3)),i=Number(r.substring(4,6));return t*(n*60+i)*60*1e3},Ef=r=>{let e=0;for(;e<r.length-1&&r.charAt(e)==="0";)e++;return e===0?r:r.slice(e)},po=function(e){return Object.assign(new String(e),{deserializeJSON(){return JSON.parse(String(e))},toString(){return String(e)},toJSON(){return String(e)}})};po.from=r=>r&&typeof r=="object"&&(r instanceof po||"deserializeJSON"in r)?r:typeof r=="string"||Object.getPrototypeOf(r)===String.prototype?po(String(r)):po(JSON.stringify(r));po.fromObject=po.from;const zE=/^-?\d*(\.\d+)?$/;class ns{string;type;constructor(e,t){if(this.string=e,this.type=t,!zE.test(e))throw new Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](e){if(!e||typeof e!="object")return!1;const t=e;return ns.prototype.isPrototypeOf(e)||t.type==="bigDecimal"&&zE.test(t.string)}}const qI={},wA={};for(let r=0;r<256;r++){let e=r.toString(16).toLowerCase();e.length===1&&(e=`0${e}`),qI[r]=e,wA[e]=r}function WI(r){if(r.length%2!==0)throw new Error("Hex encoded strings must have an even number length");const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2){const n=r.slice(t,t+2).toLowerCase();if(n in wA)e[t/2]=wA[n];else throw new Error(`Cannot decode unrecognized sequence ${n} as hexadecimal`)}return e}function Ao(r){let e="";for(let t=0;t<r.byteLength;t++)e+=qI[r[t]];return e}const $E=typeof TextEncoder=="function"?new TextEncoder:null,Cz=r=>{if(typeof r=="string"){if($E)return $E.encode(r).byteLength;let e=r.length;for(let t=e-1;t>=0;t--){const n=r.charCodeAt(t);n>127&&n<=2047?e++:n>2047&&n<=65535&&(e+=2),n>=56320&&n<=57343&&t--}return e}else{if(typeof r.byteLength=="number")return r.byteLength;if(typeof r.size=="number")return r.size}throw new Error(`Body Length computation failed for ${r}`)},kf=r=>typeof r=="string"?kl(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r),xz=r=>typeof ArrayBuffer=="function"&&r instanceof ArrayBuffer||Object.prototype.toString.call(r)==="[object ArrayBuffer]",QI=async r=>{},Sz=async r=>{const e=r?.Bucket||"";if(typeof r.Bucket=="string"&&(r.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),Iz(e)){if(r.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!Fz(e)||e.indexOf(".")!==-1&&!String(r.Endpoint).startsWith("http:")||e.toLowerCase()!==e||e.length<3)&&(r.ForcePathStyle=!0);return r.DisableMultiRegionAccessPoints&&(r.disableMultiRegionAccessPoints=!0,r.DisableMRAP=!0),r},Ez=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,kz=/(\d+\.){3}\d+/,Tz=/\.\./,Fz=r=>Ez.test(r)&&!kz.test(r)&&!Tz.test(r),Iz=r=>{const[e,t,n,,,i]=r.split(":"),a=e==="arn"&&r.split(":").length>=6,s=!!(a&&t&&n&&i);if(a&&!s)throw new Error(`Invalid ARN: ${r} was an invalid ARN.`);return s},Pz=(r,e,t,n=!1)=>{const i=async()=>{let a;return n?a=t.clientContextParams?.[r]??t[r]??t[e]:a=t[r]??t[e],typeof a=="function"?a():a};return r==="credentialScope"||e==="CredentialScope"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.credentialScope??a?.CredentialScope}:r==="accountId"||e==="AccountId"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.accountId??a?.AccountId}:r==="endpoint"||e==="endpoint"?async()=>{if(t.isCustomEndpoint===!1)return;const a=await i();if(a&&typeof a=="object"){if("url"in a)return a.url.href;if("hostname"in a){const{protocol:s,hostname:o,port:l,path:u}=a;return`${s}//${o}${l?":"+l:""}${u}`}}return a}:i};function Dz(r){return async(e,t,n,i)=>{if(!n.isCustomEndpoint){let o;n.serviceConfiguredEndpoint?o=await n.serviceConfiguredEndpoint():o=await r(n.serviceId),o&&(n.endpoint=()=>Promise.resolve(V1(o)),n.isCustomEndpoint=!0)}const a=await Rz(e,t,n);if(typeof n.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");const s=n.endpointProvider(a,i);if(n.isCustomEndpoint&&n.endpoint){const o=await n.endpoint();if(o?.headers){s.headers??={};for(const[l,u]of Object.entries(o.headers))s.headers[l]=Array.isArray(u)?u:[u]}}return s}}const Rz=async(r,e,t)=>{const n={},i=e?.getEndpointParameterInstructions?.()||{};for(const[a,s]of Object.entries(i))switch(s.type){case"staticContextParams":n[a]=s.value;break;case"contextParams":n[a]=r[s.name];break;case"clientContextParams":case"builtInParams":n[a]=await Pz(s.name,a,t,s.type!=="builtInParams")();break;case"operationContextParams":n[a]=s.get(r);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(s))}return Object.keys(i).length===0&&Object.assign(n,t),String(t.serviceId).toLowerCase()==="s3"&&await Sz(n),n};function Oz(r,e,t){r.__smithy_context?r.__smithy_context.features||(r.__smithy_context.features={}):r.__smithy_context={features:{}},r.__smithy_context.features[e]=t}function Bz(r){const e=Dz(r);return({config:t,instructions:n})=>(i,a)=>async s=>{t.isCustomEndpoint&&Oz(a,"ENDPOINT_OVERRIDE","N");const o=await e(s.input,{getEndpointParameterInstructions(){return n}},{...t},a);a.endpointV2=o,a.authSchemes=o.properties?.authSchemes;const l=a.authSchemes?.[0];if(l){a.signing_region=l.signingRegion,a.signing_service=l.signingName;const c=vc(a)?.selectedHttpAuthScheme?.httpAuthOption;c&&(c.signingProperties=Object.assign(c.signingProperties||{},{signing_region:l.signingRegion,signingRegion:l.signingRegion,signing_service:l.signingName,signingName:l.signingName,signingRegionSet:l.signingRegionSet},l.properties))}return i({...s})}}const Mz={name:"serializerMiddleware"},_z={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:Mz.name};function Nz(r){const e=Bz(r);return(t,n)=>({applyToStack:i=>{i.addRelativeTo(e({config:t,instructions:n}),_z)}})}function Lz(r){return e=>{const t=e.tls??!0,{endpoint:n,useDualstackEndpoint:i,useFipsEndpoint:a}=e,s=n!=null?async()=>V1(await Bs(n)()):void 0,l=Object.assign(e,{endpoint:s,tls:t,isCustomEndpoint:!!n,useDualstackEndpoint:Bs(i??!1),useFipsEndpoint:Bs(a??!1)});let u;return l.serviceConfiguredEndpoint=async()=>(e.serviceId&&!u&&(u=r(e.serviceId)),u),l}}class H1{nodes;root;conditions;results;constructor(e,t,n,i){this.nodes=e,this.root=t,this.conditions=n,this.results=i}static from(e,t,n,i){return new H1(e,t,n,i)}}class Uz{capacity;data=new Map;parameters=[];constructor({size:e,params:t}){this.capacity=e??50,t&&(this.parameters=t)}get(e,t){const n=this.hash(e);if(n===!1)return t();if(!this.data.has(n)){if(this.data.size>this.capacity+10){const i=this.data.keys();let a=0;for(;;){const{value:s,done:o}=i.next();if(this.data.delete(s),o||++a>10)break}}this.data.set(n,t())}return this.data.get(n)}size(){return this.data.size}hash(e){let t="";const{parameters:n}=this;if(n.length===0)return!1;for(const i of n){const a=String(e[i]??"");if(a.includes("|;"))return!1;t+=a+"|;"}return t}}class Ba extends Error{constructor(e){super(e),this.name="EndpointError"}}const Vz="endpoints";function Sg(r){return typeof r!="object"||r==null?r:"ref"in r?`$${Sg(r.ref)}`:"fn"in r?`${r.fn}(${(r.argv||[]).map(Sg).join(", ")})`:JSON.stringify(r,null,2)}const j1={},zz=(r,e)=>r===e;function $z(...r){for(const e of r)if(e!=null)return e}const Hz=r=>{const e=r.split("."),t=[];for(const n of e){const i=n.indexOf("[");if(i!==-1){if(n.indexOf("]")!==n.length-1)throw new Ba(`Path: '${r}' does not end with ']'`);const a=n.slice(i+1,-1);if(Number.isNaN(parseInt(a)))throw new Ba(`Invalid array index: '${a}' in path: '${r}'`);i!==0&&t.push(n.slice(0,i)),t.push(a)}else t.push(n)}return t},YI=(r,e)=>Hz(e).reduce((t,n)=>{if(typeof t!="object")throw new Ba(`Index '${n}' in '${e}' not found in '${JSON.stringify(r)}'`);if(Array.isArray(t)){const i=parseInt(n);return t[i<0?t.length+i:i]}return t[n]},r),jz=r=>r!=null;function Gz(r,e,t){return r?e:t}const qz=r=>!r,Wz=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),XI=r=>Wz.test(r)||r.startsWith("[")&&r.endsWith("]"),$v={[xf.HTTP]:80,[xf.HTTPS]:443},Qz=r=>{const e=(()=>{try{if(r instanceof URL)return r;if(typeof r=="object"&&"hostname"in r){const{hostname:d,port:h,protocol:g="",path:v="",query:y={}}=r,A=new URL(`${g}//${d}${h?`:${h}`:""}${v}`);return A.search=Object.entries(y).map(([C,S])=>`${C}=${S}`).join("&"),A}return new URL(r)}catch{return null}})();if(!e)return console.error(`Unable to parse ${JSON.stringify(r)} as a whatwg URL.`),null;const t=e.href,{host:n,hostname:i,pathname:a,protocol:s,search:o}=e;if(o)return null;const l=s.slice(0,-1);if(!Object.values(xf).includes(l))return null;const u=XI(i),c=t.includes(`${n}:${$v[l]}`)||typeof r=="string"&&r.includes(`${n}:${$v[l]}`),f=`${n}${c?`:${$v[l]}`:""}`;return{scheme:l,authority:f,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:u}};function Yz(r,e,t){if(t===1)return[r];if(r==="")return[""];const n=r.split(e);return t===0?n:n.slice(0,t-1).concat(n.slice(1).join(e))}const Xz=(r,e)=>r===e,Jz=(r,e,t,n)=>r==null||e>=t||r.length<t||/[^\u0000-\u007f]/.test(r)?null:n?r.substring(r.length-t,r.length-e):r.substring(e,t),Kz=r=>encodeURIComponent(r).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Zz={booleanEquals:zz,coalesce:$z,getAttr:YI,isSet:jz,isValidHostLabel:Kg,ite:Gz,not:qz,parseURL:Qz,split:Yz,stringEquals:Xz,substring:Jz,uriEncode:Kz},JI=(r,e)=>{const t=[],{referenceRecord:n,endpointParams:i}=e;let a=0;for(;a<r.length;){const s=r.indexOf("{",a);if(s===-1){t.push(r.slice(a));break}t.push(r.slice(a,s));const o=r.indexOf("}",s);if(o===-1){t.push(r.slice(s));break}r[s+1]==="{"&&r[o+1]==="}"&&(t.push(r.slice(s+1,o)),a=o+2);const l=r.substring(s+1,o);if(l.includes("#")){const[u,c]=l.split("#");t.push(YI(n[u]??i[u],c))}else t.push(n[l]??i[l]);a=o+1}return t.join("")},e$=({ref:r},e)=>e.referenceRecord[r]??e.endpointParams[r],rm=(r,e,t)=>{if(typeof r=="string")return JI(r,t);if(r.fn)return ZI.callFunction(r,t);if(r.ref)return e$(r,t);throw new Ba(`'${e}': ${String(r)} is not a string, function or reference.`)},KI=({fn:r,argv:e},t)=>{const n=Array(e.length);for(let s=0;s<n.length;++s){const o=e[s];typeof o=="boolean"||typeof o=="number"?n[s]=o:n[s]=ZI.evaluateExpression(o,"arg",t)}const i=r.indexOf(".");if(i!==-1){const o=j1[r.slice(0,i)]?.[r.slice(i+1)];if(typeof o=="function")return o(...n)}const a=Zz[r];if(typeof a=="function")return a(...n);throw new Error(`function ${r} not loaded in endpointFunctions.`)},ZI={evaluateExpression:rm,callFunction:KI},t$=(r,e)=>{const{assign:t}=r;if(t&&t in e.referenceRecord)throw new Ba(`'${t}' is already defined in Reference Record.`);const n=KI(r,e);e.logger?.debug?.(`${Vz} evaluateCondition: ${Sg(r)} = ${Sg(n)}`);const i=n===""?!0:!!n;return t!=null?{result:i,toAssign:{name:t,value:n}}:{result:i}},r$=(r,e)=>Object.entries(r??{}).reduce((t,[n,i])=>(t[n]=i.map(a=>{const s=rm(a,"Header value entry",e);if(typeof s!="string")throw new Ba(`Header '${n}' value '${s}' is not a string`);return s}),t),{}),eP=(r,e)=>Object.entries(r).reduce((t,[n,i])=>(t[n]=rP.getEndpointProperty(i,e),t),{}),tP=(r,e)=>{if(Array.isArray(r))return r.map(t=>tP(t,e));switch(typeof r){case"string":return JI(r,e);case"object":if(r===null)throw new Ba(`Unexpected endpoint property: ${r}`);return rP.getEndpointProperties(r,e);case"boolean":return r;default:throw new Ba(`Unexpected endpoint property type: ${typeof r}`)}},rP={getEndpointProperty:tP,getEndpointProperties:eP},n$=(r,e)=>{const t=rm(r,"Endpoint URL",e);if(typeof t=="string")try{return new URL(t)}catch(n){throw console.error(`Failed to construct URL with ${t}`,n),n}throw new Ba(`Endpoint URL must be a string, got ${typeof t}`)},Hv=1e8,i$=(r,e)=>{const{nodes:t,root:n,results:i,conditions:a}=r;let s=n;const o={},l={referenceRecord:o,endpointParams:e.endpointParams,logger:e.logger};for(;s!==1&&s!==-1&&s<Hv;){const u=3*(Math.abs(s)-1),[c,f,d]=[t[u],t[u+1],t[u+2]],[h,g,v]=a[c],y=t$({fn:h,assign:v,argv:g},l);if(y.toAssign){const{name:A,value:C}=y.toAssign;o[A]=C}s=s>=0===y.result?f:d}if(s>=Hv){const u=i[s-Hv];if(u[0]===-1){const[,h]=u;throw new Ba(rm(h,"Error",l))}const[c,f,d]=u;return{url:n$(c,l),properties:eP(f,l),headers:r$(d??{},l)}}throw new Ba("No matching endpoint.")},a$=Lz(QI),nP=Nz(QI);class jv extends YV(em,kl,Cg,Zg){}const s$=r=>crypto.getRandomValues(r),iP=XV(s$),o$=iP,bA=async(r=new Uint8Array,e)=>{if(r instanceof Uint8Array)return jv.mutate(r);if(!r)return jv.mutate(new Uint8Array);const t=e.streamCollector(r);return jv.mutate(await t)};class l${serdeContext;setSerdeContext(e){this.serdeContext=e}}class u$ extends l${options;compositeErrorRegistry;constructor(e){super(),this.options=e,this.compositeErrorRegistry=Zi.for(e.defaultNamespace);for(const t of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return na}getResponseType(){return sc}setSerdeContext(e){this.serdeContext=e,this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e),this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(e)}updateServiceEndpoint(e,t){if("url"in t){e.protocol=t.url.protocol,e.hostname=t.url.hostname,e.port=t.url.port?Number(t.url.port):void 0,e.path=t.url.pathname,e.fragment=t.url.hash||void 0,e.username=t.url.username||void 0,e.password=t.url.password||void 0,e.query||(e.query={});for(const[n,i]of t.url.searchParams.entries())e.query[n]=i;if(t.headers)for(const n in t.headers)e.headers[n]=t.headers[n].join(", ");return e}else{if(e.protocol=t.protocol,e.hostname=t.hostname,e.port=t.port?Number(t.port):void 0,e.path=t.path,e.query={...t.query},t.headers)for(const n in t.headers)e.headers[n]=t.headers[n];return e}}setHostPrefix(e,t,n){if(this.serdeContext?.disableHostPrefix)return;const i=vi.of(t.input),a=zd(t.traits??{});if(a.endpoint){let s=a.endpoint?.[0];if(typeof s=="string"){for(const[o,l]of i.structIterator()){if(!l.getMergedTraits().hostLabel)continue;const u=n[o];if(typeof u!="string")throw new Error(`@smithy/core/schema - ${o} in input must be a string as hostLabel.`);s=s.replace(`{${o}}`,u)}e.hostname=s+e.hostname}}}deserializeMetadata(e){return{httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:e,requestSchema:t,initialRequest:n}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:e,requestSchema:t,initialRequest:n})}async deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:n}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:n})}async loadEventStreamCapability(){const{EventStreamSerde:e,eventStreamSerdeProvider:t}=await Promise.resolve().then(()=>require("./index.browser-DxAfP6M1.cjs")),n=this.resolveEventStreamMarshaller(t);return new e({marshaller:n,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(e){const t=this.serdeContext;return t.eventStreamMarshaller?t.eventStreamMarshaller:e(this.serdeContext)}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(e,t,n,i,a){return[]}getEventStreamMarshaller(){const e=this.serdeContext;if(!e.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return e.eventStreamMarshaller}}class c$ extends u${async serializeRequest(e,t,n){const i=this.serializer,a={},s={},o=await n.endpoint(),l=vi.of(e?.input),u=l.getSchema();let c;const f=t&&typeof t=="object"?t:{},d=new na({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:a,headers:s,body:void 0});if(o&&(this.updateServiceEndpoint(d,o),this.setHostPrefix(d,e,f)),f){const h=l.getEventStreamMember();if(h){if(f[h]){const g={};for(const[v,y]of l.structIterator())v!==h&&f[v]&&(i.write(y,f[v]),g[v]=i.flush());c=await this.serializeEventStream({eventStream:f[h],requestSchema:l,initialRequest:g})}}else i.write(u,f),c=i.flush()}return d.headers=Object.assign(d.headers,s),d.query=a,d.body=c,d.method="POST",d}async deserializeResponse(e,t,n){const i=this.deserializer,a=vi.of(e.output),s={};if(n.statusCode>=300){const l=await bA(n.body,t);throw l.byteLength>0&&Object.assign(s,await i.read(15,l)),await this.handleError(e,t,n,s,this.deserializeMetadata(n)),new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(const l in n.headers){const u=n.headers[l];delete n.headers[l],n.headers[l.toLowerCase()]=u}const o=a.getEventStreamMember();if(o)s[o]=await this.deserializeEventStream({response:n,responseSchema:a,initialResponseContainer:s});else{const l=await bA(n.body,t);l.byteLength>0&&Object.assign(s,await i.read(a,l))}return s.$metadata=this.deserializeMetadata(n),s}}function aP(r,e){if(e.timestampFormat.useTrait&&r.isTimestampSchema()&&(r.getSchema()===5||r.getSchema()===6||r.getSchema()===7))return r.getSchema();const{httpLabel:t,httpPrefixHeaders:n,httpHeader:i,httpQuery:a}=r.getMergedTraits();return(e.httpBindings?typeof n=="string"||i?6:a||t?5:void 0:void 0)??e.timestampFormat.default}const d$=r=>({setHttpHandler(e){r.httpHandler=e},httpHandler(){return r.httpHandler},updateHttpClientConfig(e,t){r.httpHandler?.updateHttpClientConfig(e,t)},httpHandlerConfigs(){return r.httpHandler.httpHandlerConfigs()}}),f$=r=>({httpHandler:r.httpHandler()}),HE="content-length";function h$(r){return e=>async t=>{const n=t.request;if(na.isInstance(n)){const{body:i,headers:a}=n;if(i&&Object.keys(a).map(s=>s.toLowerCase()).indexOf(HE)===-1)try{const s=r(i);n.headers={...n.headers,[HE]:String(s)}}catch{}}return e({...t,request:n})}}const p$={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},g$=r=>({applyToStack:e=>{e.add(h$(r.bodyLengthChecker),p$)}}),Cl=r=>encodeURIComponent(r).replace(/[!'()*]/g,m$),m$=r=>`%${r.charCodeAt(0).toString(16).toUpperCase()}`;function v$(r){const e=[];for(let t of Object.keys(r).sort()){const n=r[t];if(t=Cl(t),Array.isArray(n))for(let i=0,a=n.length;i<a;i++)e.push(`${t}=${Cl(n[i])}`);else{let i=t;(n||typeof n=="string")&&(i+=`=${Cl(n)}`),e.push(i)}}return e.join("&")}const y$=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],A$=["TimeoutError","RequestTimeout","RequestTimeoutException"],w$=[500,502,503,504],b$=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],C$=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],x$=r=>r?.$retryable!==void 0,S$=r=>r.$metadata?.clockSkewCorrected,E$=r=>{const e=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);return r&&r instanceof TypeError?e.has(r.message):!1},sP=r=>r.$metadata?.httpStatusCode===429||y$.includes(r.name)||r.$retryable?.throttling==!0,G1=(r,e=0)=>x$(r)||S$(r)||r.name==="InvalidSignatureException"&&r.message?.includes("Signature expired")||A$.includes(r.name)||b$.includes(r?.code||"")||C$.includes(r?.code||"")||w$.includes(r.$metadata?.httpStatusCode||0)||E$(r)||T$(r)||r.cause!==void 0&&e<=10&&G1(r.cause,e+1),k$=r=>{if(r.$metadata?.httpStatusCode!==void 0){const e=r.$metadata.httpStatusCode;return 500<=e&&e<=599&&!G1(r)}return!1};function T$(r){return r.code==="ERR_HTTP2_STREAM_ERROR"&&r.message.includes("NGHTTP2_REFUSED_STREAM")}const oP=20*1e3,jE=500,F$=1,I$="amz-sdk-invocation-id",P$="amz-sdk-request";function D$(r,e){if(sc.isInstance(r))for(const t of Object.keys(r.headers)){const n=t.toLowerCase();if(n==="retry-after"){const i=r.headers[t];let a=NaN;if(i.endsWith("GMT"))try{a=(GI(i).getTime()-Date.now())/1e3}catch(s){e?.trace?.("Failed to parse retry-after header"),e?.trace?.(s)}else i.match(/ GMT, ((\d+)|(\d+\.\d+))$/)?a=Number(i.match(/ GMT, ([\d.]+)$/)?.[1]):i.match(/^((\d+)|(\d+\.\d+))$/)?a=Number(i):Date.parse(i)>=Date.now()&&(a=(Date.parse(i)-Date.now())/1e3);return isNaN(a)?void 0:new Date(Date.now()+a*1e3)}else if(n==="x-amz-retry-after"){const i=r.headers[t],a=Number(i);if(isNaN(a)){e?.trace?.(`Failed to parse x-amz-retry-after=${i}`);return}return new Date(Date.now()+a)}}}const R$=r=>r instanceof Error?r:r instanceof Object?Object.assign(new Error,r):typeof r=="string"?new Error(r):new Error(`AWS SDK error wrapper for ${r}`);function O$(r){return e=>(t,n)=>async i=>{let a=await e.retryStrategy();const s=await e.maxAttempts();if(M$(a)){a=a;let o=await a.acquireInitialRetryToken((n.partition_id??"")+(n.__retryLongPoll?":longpoll":"")),l=new Error,u=0,c=0;const{request:f}=i,d=na.isInstance(f);for(d&&(f.headers[I$]=iP());;)try{d&&(f.headers[P$]=`attempt=${u+1}; max=${s}`);const{response:h,output:g}=await t(i);return a.recordSuccess(o),g.$metadata.attempts=u+1,g.$metadata.totalRetryDelay=c,{response:h,output:g}}catch(h){const g=_$(h,e.logger);if(l=R$(h),d&&r(f))throw(n.logger instanceof $I?console:n.logger)?.warn("An error was encountered in a non-retryable streaming request."),l;try{o=await a.refreshRetryTokenForRetry(o,g)}catch{throw l.$metadata||(l.$metadata={}),l.$metadata.attempts=u+1,l.$metadata.totalRetryDelay=c,l}u=o.getRetryCount();const v=o.getRetryDelay();c+=(o?.$retryLog?.acquisitionDelay??0)+v,v>0&&await B$(v)}}else return a=a,a?.mode&&(n.userAgent=[...n.userAgent||[],["cfg/retry-mode",a.mode]]),a.retry(t,i)}}const B$=r=>new Promise(e=>setTimeout(e,r)),M$=r=>typeof r.acquireInitialRetryToken<"u"&&typeof r.refreshRetryTokenForRetry<"u"&&typeof r.recordSuccess<"u",_$=(r,e)=>{const t={error:r,errorType:N$(r)},n=D$(r.$response,e);return n&&(t.retryAfterHint=n),t},N$=r=>sP(r)?"THROTTLING":G1(r)?"TRANSIENT":k$(r)?"SERVER_ERROR":"CLIENT_ERROR",L$={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function U$(r){const e=O$(r);return t=>({applyToStack:n=>{n.add(e(t),L$)}})}class q1{static setTimeoutFn=(e,t)=>setTimeout(e,t);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(e){this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(e){let t;this.updateMeasuredRate();const n=e;if(n?.errorType==="THROTTLING"||sP(n?.error??e)){const s=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=s,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(s),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());const a=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(a)}getCurrentTimeInSeconds(){return Date.now()/1e3}async acquireTokenBucket(e){if(this.enabled){for(this.refillTokenBucket();e>this.availableTokens;){const t=(e-this.availableTokens)/this.fillRate*1e3;await new Promise(n=>q1.setTimeoutFn(n,t)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-e}}refillTokenBucket(){const e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=e;return}const t=(e-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+t),this.lastTimestamp=e}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){const e=this.getCurrentTimeInSeconds(),t=Math.floor(e*2)/2;if(this.requestCount++,t>this.lastTxRateBucket){const n=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(n*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(e){return parseFloat(e.toFixed(8))}}class Ei{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return Ei.v2026?50:100}static throttlingDelay(){return Ei.v2026?1e3:500}static cost(){return Ei.v2026?14:5}static throttlingCost(){return Ei.v2026?5:10}static modifiedCostType(){return Ei.v2026?"THROTTLING":"TRANSIENT"}}class V${x=Ei.delay();computeNextBackoffDelay(e){const i=Math.random()*Math.min(this.x*2**e,oP);return Math.floor(i)}setDelayBase(e){this.x=e}}class GE{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(e,t,n,i){this.delay=e,this.count=t,this.cost=n,this.longPoll=i}getRetryCount(){return this.count}getRetryDelay(){return Math.min(oP,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var Po;(function(r){r.STANDARD="standard",r.ADAPTIVE="adaptive"})(Po||(Po={}));const ef=3,z$=Po.STANDARD,kp={incompatible:1,attempts:2,capacity:3};class CA{mode=Po.STANDARD;retryBackoffStrategy;capacity=jE;maxAttemptsProvider;baseDelay;constructor(e){typeof e=="number"?this.maxAttemptsProvider=async()=>e:typeof e=="function"?this.maxAttemptsProvider=e:e&&typeof e=="object"&&(this.maxAttemptsProvider=async()=>e.maxAttempts,this.baseDelay=e.baseDelay,this.retryBackoffStrategy=e.backoff),this.maxAttemptsProvider??=async()=>ef,this.baseDelay??=Ei.delay(),this.retryBackoffStrategy??=new V$}async acquireInitialRetryToken(e){return new GE(Ei.delay(),0,void 0,Ei.v2026&&e.includes(":longpoll"))}async refreshRetryTokenForRetry(e,t){const n=await this.getMaxAttempts(),i=this.retryCode(e,t,n),a=i===0,s=e.isLongPoll?.();if(a||s){const o=t.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?Ei.throttlingDelay():this.baseDelay);const l=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount());let u=l;if(t.retryAfterHint instanceof Date&&(u=Math.max(l,Math.min(t.retryAfterHint.getTime()-Date.now(),l+5e3))),a){const c=this.getCapacityCost(o);this.capacity-=c;const f=new GE(0,e.getRetryCount()+1,c,e.isLongPoll?.()??!1);return await new Promise(d=>setTimeout(d,u)),f.$retryLog.acquisitionDelay=u,f}else{const c=Ei.v2026&&i===kp.capacity&&s?u:0;c>0&&await new Promise(f=>setTimeout(f,c))}}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.min(jE,this.capacity+(e.getRetryCost()??F$))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${ef}`),ef}}retryCode(e,t,n){const i=e.getRetryCount()+1,a=this.isRetryableError(t.errorType)?0:kp.incompatible,s=i<n?0:kp.attempts,o=this.capacity>=this.getCapacityCost(t.errorType)?0:kp.capacity;return a||s||o}getCapacityCost(e){return e===Ei.modifiedCostType()?Ei.throttlingCost():Ei.cost()}isRetryableError(e){return e==="THROTTLING"||e==="TRANSIENT"}}class $${mode=Po.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(e,t){const{rateLimiter:n}=t??{};this.rateLimiter=n??new q1,this.standardRetryStrategy=t?new CA({maxAttempts:typeof e=="number"?e:3,...t}):new CA(e)}async acquireInitialRetryToken(e){const t=await this.standardRetryStrategy.acquireInitialRetryToken(e);return await this.rateLimiter.getSendToken(),t}async refreshRetryTokenForRetry(e,t){this.rateLimiter.updateClientSendingRate(t);const n=await this.standardRetryStrategy.refreshRetryTokenForRetry(e,t);return await this.rateLimiter.getSendToken(),n}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}}const H$=(r,e)=>{const{retryStrategy:t,retryMode:n}=r,{defaultMaxAttempts:i=ef,defaultBaseDelay:a=Ei.delay()}={},s=Bs(r.maxAttempts??i);let o=t?Promise.resolve(t):void 0;const l=async()=>{const u=await s();return await Bs(n)()===Po.ADAPTIVE?new $$(s,{maxAttempts:u,baseDelay:a}):new CA({maxAttempts:u,baseDelay:a})};return Object.assign(r,{maxAttempts:s,retryStrategy:()=>o??=l()})},j$=U$(TV);Ei.v2026||=typeof process=="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function Is(r,e,t){r.__aws_sdk_context?r.__aws_sdk_context.features||(r.__aws_sdk_context.features={}):r.__aws_sdk_context={features:{}},r.__aws_sdk_context.features[e]=t}const G$=r=>e=>async t=>{if(!na.isInstance(t.request))return e(t);const{request:n}=t,{handlerProtocol:i=""}=r.requestHandler.metadata||{};if(i.indexOf("h2")>=0&&!n.headers[":authority"])delete n.headers.host,n.headers[":authority"]=n.hostname+(n.port?":"+n.port:"");else if(!n.headers.host){let a=n.hostname;n.port!=null&&(a+=`:${n.port}`),n.headers.host=a}return e(t)},q$={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},W$=r=>({applyToStack:e=>{e.add(G$(r),q$)}}),Q$=()=>(r,e)=>async t=>{try{const n=await r(t),{clientName:i,commandName:a,logger:s,dynamoDbDocumentClientOptions:o={}}=e,{overrideInputFilterSensitiveLog:l,overrideOutputFilterSensitiveLog:u}=o,c=l??e.inputFilterSensitiveLog,f=u??e.outputFilterSensitiveLog,{$metadata:d,...h}=n.output;return s?.info?.({clientName:i,commandName:a,input:c(t.input),output:f(h),metadata:d}),n}catch(n){const{clientName:i,commandName:a,logger:s,dynamoDbDocumentClientOptions:o={}}=e,{overrideInputFilterSensitiveLog:l}=o,u=l??e.inputFilterSensitiveLog;throw s?.error?.({clientName:i,commandName:a,input:u(t.input),error:n,metadata:n.$metadata}),n}},Y$={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},X$=r=>({applyToStack:e=>{e.add(Q$(),Y$)}}),J$=r=>({applyToStack:e=>{}}),K$=(r,e)=>{if(!e||e.length===0)return r;const t=[];for(const n of e)for(const i of r)i.schemeId.split("#")[1]===n&&t.push(i);for(const n of r)t.find(({schemeId:i})=>i===n.schemeId)||t.push(n);return t};function Z$(r){const e=new Map;for(const t of r)e.set(t.schemeId,t);return e}const eH=(r,e)=>(t,n)=>async i=>{const a=r.httpAuthSchemeProvider(await e.httpAuthSchemeParametersProvider(r,n,i.input)),s=r.authSchemePreference?await r.authSchemePreference():[],o=K$(a,s),l=Z$(r.httpAuthSchemes),u=vc(n),c=[];for(const f of o){const d=l.get(f.schemeId);if(!d){c.push(`HttpAuthScheme \`${f.schemeId}\` was not enabled for this service.`);continue}const h=d.identityProvider(await e.identityProviderConfigProvider(r));if(!h){c.push(`HttpAuthScheme \`${f.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties:g={},signingProperties:v={}}=f.propertiesExtractor?.(r,n)||{};f.identityProperties=Object.assign(f.identityProperties||{},g),f.signingProperties=Object.assign(f.signingProperties||{},v),u.selectedHttpAuthScheme={httpAuthOption:f,identity:await h(f.identityProperties),signer:d.signer};break}if(!u.selectedHttpAuthScheme)throw new Error(c.join(`
3042
+ `),az={warn:console.warn},sz=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],$1=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function oz(r){const e=r.getUTCFullYear(),t=r.getUTCMonth(),n=r.getUTCDay(),i=r.getUTCDate(),a=r.getUTCHours(),s=r.getUTCMinutes(),o=r.getUTCSeconds(),l=i<10?`0${i}`:`${i}`,u=a<10?`0${a}`:`${a}`,c=s<10?`0${s}`:`${s}`,f=o<10?`0${o}`:`${o}`;return`${sz[n]}, ${l} ${$1[t]} ${e} ${u}:${c}:${f} GMT`}const lz=new RegExp(/^(\d{4})-(\d{2})-(\d{2})[tT](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(([-+]\d{2}\:\d{2})|[zZ])$/),uz=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-3339 date-times must be expressed as strings");const e=lz.exec(r);if(!e)throw new TypeError("Invalid RFC-3339 date-time value");const[t,n,i,a,s,o,l,u,c]=e,f=xg(Ef(n)),d=yo(i,"month",1,12),h=yo(a,"day",1,31),g=Jp(f,d,h,{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u});return c.toUpperCase()!="Z"&&g.setTime(g.getTime()-bz(c)),g},cz=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),dz=new RegExp(/^(?:Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday), (\d{2})-(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)-(\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? GMT$/),fz=new RegExp(/^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) ( [1-9]|\d{2}) (\d{1,2}):(\d{2}):(\d{2})(?:\.(\d+))? (\d{4})$/),GI=r=>{if(r==null)return;if(typeof r!="string")throw new TypeError("RFC-7231 date-times must be expressed as strings");let e=cz.exec(r);if(e){const[t,n,i,a,s,o,l,u]=e;return Jp(xg(Ef(a)),zv(i),yo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u})}if(e=dz.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return mz(Jp(pz(a),zv(i),yo(n,"day",1,31),{hours:s,minutes:o,seconds:l,fractionalMilliseconds:u}))}if(e=fz.exec(r),e){const[t,n,i,a,s,o,l,u]=e;return Jp(xg(Ef(u)),zv(n),yo(i.trimLeft(),"day",1,31),{hours:a,minutes:s,seconds:o,fractionalMilliseconds:l})}throw new TypeError("Invalid RFC-7231 date-time value")},hz=r=>{if(r==null)return;let e;if(typeof r=="number")e=r;else if(typeof r=="string")e=ez(r);else if(typeof r=="object"&&r.tag===1)e=r.value;else throw new TypeError("Epoch timestamps must be expressed as floating point numbers or their string representation");if(Number.isNaN(e)||e===1/0||e===-1/0)throw new TypeError("Epoch timestamps must be valid, non-Infinite, non-NaN numerics");return new Date(Math.round(e*1e3))},Jp=(r,e,t,n)=>{const i=e-1;return yz(r,i,t),new Date(Date.UTC(r,i,t,yo(n.hours,"hour",0,23),yo(n.minutes,"minute",0,59),yo(n.seconds,"seconds",0,60),wz(n.fractionalMilliseconds)))},pz=r=>{const e=new Date().getUTCFullYear(),t=Math.floor(e/100)*100+xg(Ef(r));return t<e?t+100:t},gz=50*365*24*60*60*1e3,mz=r=>r.getTime()-new Date().getTime()>gz?new Date(Date.UTC(r.getUTCFullYear()-100,r.getUTCMonth(),r.getUTCDate(),r.getUTCHours(),r.getUTCMinutes(),r.getUTCSeconds(),r.getUTCMilliseconds())):r,zv=r=>{const e=$1.indexOf(r);if(e<0)throw new TypeError(`Invalid month: ${r}`);return e+1},vz=[31,28,31,30,31,30,31,31,30,31,30,31],yz=(r,e,t)=>{let n=vz[e];if(e===1&&Az(r)&&(n=29),t>n)throw new TypeError(`Invalid day for ${$1[e]} in ${r}: ${t}`)},Az=r=>r%4===0&&(r%100!==0||r%400===0),yo=(r,e,t,n)=>{const i=nz(Ef(r));if(i<t||i>n)throw new TypeError(`${e} must be between ${t} and ${n}, inclusive`);return i},wz=r=>r==null?0:tz("0."+r)*1e3,bz=r=>{const e=r[0];let t=1;if(e=="+")t=1;else if(e=="-")t=-1;else throw new TypeError(`Offset direction, ${e}, must be "+" or "-"`);const n=Number(r.substring(1,3)),i=Number(r.substring(4,6));return t*(n*60+i)*60*1e3},Ef=r=>{let e=0;for(;e<r.length-1&&r.charAt(e)==="0";)e++;return e===0?r:r.slice(e)},po=function(e){return Object.assign(new String(e),{deserializeJSON(){return JSON.parse(String(e))},toString(){return String(e)},toJSON(){return String(e)}})};po.from=r=>r&&typeof r=="object"&&(r instanceof po||"deserializeJSON"in r)?r:typeof r=="string"||Object.getPrototypeOf(r)===String.prototype?po(String(r)):po(JSON.stringify(r));po.fromObject=po.from;const zE=/^-?\d*(\.\d+)?$/;class ns{string;type;constructor(e,t){if(this.string=e,this.type=t,!zE.test(e))throw new Error('@smithy/core/serde - NumericValue must only contain [0-9], at most one decimal point ".", and an optional negation prefix "-".')}toString(){return this.string}static[Symbol.hasInstance](e){if(!e||typeof e!="object")return!1;const t=e;return ns.prototype.isPrototypeOf(e)||t.type==="bigDecimal"&&zE.test(t.string)}}const qI={},wA={};for(let r=0;r<256;r++){let e=r.toString(16).toLowerCase();e.length===1&&(e=`0${e}`),qI[r]=e,wA[e]=r}function WI(r){if(r.length%2!==0)throw new Error("Hex encoded strings must have an even number length");const e=new Uint8Array(r.length/2);for(let t=0;t<r.length;t+=2){const n=r.slice(t,t+2).toLowerCase();if(n in wA)e[t/2]=wA[n];else throw new Error(`Cannot decode unrecognized sequence ${n} as hexadecimal`)}return e}function Ao(r){let e="";for(let t=0;t<r.byteLength;t++)e+=qI[r[t]];return e}const $E=typeof TextEncoder=="function"?new TextEncoder:null,Cz=r=>{if(typeof r=="string"){if($E)return $E.encode(r).byteLength;let e=r.length;for(let t=e-1;t>=0;t--){const n=r.charCodeAt(t);n>127&&n<=2047?e++:n>2047&&n<=65535&&(e+=2),n>=56320&&n<=57343&&t--}return e}else{if(typeof r.byteLength=="number")return r.byteLength;if(typeof r.size=="number")return r.size}throw new Error(`Body Length computation failed for ${r}`)},kf=r=>typeof r=="string"?kl(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r),xz=r=>typeof ArrayBuffer=="function"&&r instanceof ArrayBuffer||Object.prototype.toString.call(r)==="[object ArrayBuffer]",QI=async r=>{},Sz=async r=>{const e=r?.Bucket||"";if(typeof r.Bucket=="string"&&(r.Bucket=e.replace(/#/g,encodeURIComponent("#")).replace(/\?/g,encodeURIComponent("?"))),Iz(e)){if(r.ForcePathStyle===!0)throw new Error("Path-style addressing cannot be used with ARN buckets")}else(!Fz(e)||e.indexOf(".")!==-1&&!String(r.Endpoint).startsWith("http:")||e.toLowerCase()!==e||e.length<3)&&(r.ForcePathStyle=!0);return r.DisableMultiRegionAccessPoints&&(r.disableMultiRegionAccessPoints=!0,r.DisableMRAP=!0),r},Ez=/^[a-z0-9][a-z0-9\.\-]{1,61}[a-z0-9]$/,kz=/(\d+\.){3}\d+/,Tz=/\.\./,Fz=r=>Ez.test(r)&&!kz.test(r)&&!Tz.test(r),Iz=r=>{const[e,t,n,,,i]=r.split(":"),a=e==="arn"&&r.split(":").length>=6,s=!!(a&&t&&n&&i);if(a&&!s)throw new Error(`Invalid ARN: ${r} was an invalid ARN.`);return s},Pz=(r,e,t,n=!1)=>{const i=async()=>{let a;return n?a=t.clientContextParams?.[r]??t[r]??t[e]:a=t[r]??t[e],typeof a=="function"?a():a};return r==="credentialScope"||e==="CredentialScope"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.credentialScope??a?.CredentialScope}:r==="accountId"||e==="AccountId"?async()=>{const a=typeof t.credentials=="function"?await t.credentials():t.credentials;return a?.accountId??a?.AccountId}:r==="endpoint"||e==="endpoint"?async()=>{if(t.isCustomEndpoint===!1)return;const a=await i();if(a&&typeof a=="object"){if("url"in a)return a.url.href;if("hostname"in a){const{protocol:s,hostname:o,port:l,path:u}=a;return`${s}//${o}${l?":"+l:""}${u}`}}return a}:i};function Dz(r){return async(e,t,n,i)=>{if(!n.isCustomEndpoint){let o;n.serviceConfiguredEndpoint?o=await n.serviceConfiguredEndpoint():o=await r(n.serviceId),o&&(n.endpoint=()=>Promise.resolve(V1(o)),n.isCustomEndpoint=!0)}const a=await Rz(e,t,n);if(typeof n.endpointProvider!="function")throw new Error("config.endpointProvider is not set.");const s=n.endpointProvider(a,i);if(n.isCustomEndpoint&&n.endpoint){const o=await n.endpoint();if(o?.headers){s.headers??={};for(const[l,u]of Object.entries(o.headers))s.headers[l]=Array.isArray(u)?u:[u]}}return s}}const Rz=async(r,e,t)=>{const n={},i=e?.getEndpointParameterInstructions?.()||{};for(const[a,s]of Object.entries(i))switch(s.type){case"staticContextParams":n[a]=s.value;break;case"contextParams":n[a]=r[s.name];break;case"clientContextParams":case"builtInParams":n[a]=await Pz(s.name,a,t,s.type!=="builtInParams")();break;case"operationContextParams":n[a]=s.get(r);break;default:throw new Error("Unrecognized endpoint parameter instruction: "+JSON.stringify(s))}return Object.keys(i).length===0&&Object.assign(n,t),String(t.serviceId).toLowerCase()==="s3"&&await Sz(n),n};function Oz(r,e,t){r.__smithy_context?r.__smithy_context.features||(r.__smithy_context.features={}):r.__smithy_context={features:{}},r.__smithy_context.features[e]=t}function Bz(r){const e=Dz(r);return({config:t,instructions:n})=>(i,a)=>async s=>{t.isCustomEndpoint&&Oz(a,"ENDPOINT_OVERRIDE","N");const o=await e(s.input,{getEndpointParameterInstructions(){return n}},{...t},a);a.endpointV2=o,a.authSchemes=o.properties?.authSchemes;const l=a.authSchemes?.[0];if(l){a.signing_region=l.signingRegion,a.signing_service=l.signingName;const c=vc(a)?.selectedHttpAuthScheme?.httpAuthOption;c&&(c.signingProperties=Object.assign(c.signingProperties||{},{signing_region:l.signingRegion,signingRegion:l.signingRegion,signing_service:l.signingName,signingName:l.signingName,signingRegionSet:l.signingRegionSet},l.properties))}return i({...s})}}const Mz={name:"serializerMiddleware"},_z={step:"serialize",tags:["ENDPOINT_PARAMETERS","ENDPOINT_V2","ENDPOINT"],name:"endpointV2Middleware",override:!0,relation:"before",toMiddleware:Mz.name};function Nz(r){const e=Bz(r);return(t,n)=>({applyToStack:i=>{i.addRelativeTo(e({config:t,instructions:n}),_z)}})}function Lz(r){return e=>{const t=e.tls??!0,{endpoint:n,useDualstackEndpoint:i,useFipsEndpoint:a}=e,s=n!=null?async()=>V1(await Bs(n)()):void 0,l=Object.assign(e,{endpoint:s,tls:t,isCustomEndpoint:!!n,useDualstackEndpoint:Bs(i??!1),useFipsEndpoint:Bs(a??!1)});let u;return l.serviceConfiguredEndpoint=async()=>(e.serviceId&&!u&&(u=r(e.serviceId)),u),l}}class H1{nodes;root;conditions;results;constructor(e,t,n,i){this.nodes=e,this.root=t,this.conditions=n,this.results=i}static from(e,t,n,i){return new H1(e,t,n,i)}}class Uz{capacity;data=new Map;parameters=[];constructor({size:e,params:t}){this.capacity=e??50,t&&(this.parameters=t)}get(e,t){const n=this.hash(e);if(n===!1)return t();if(!this.data.has(n)){if(this.data.size>this.capacity+10){const i=this.data.keys();let a=0;for(;;){const{value:s,done:o}=i.next();if(this.data.delete(s),o||++a>10)break}}this.data.set(n,t())}return this.data.get(n)}size(){return this.data.size}hash(e){let t="";const{parameters:n}=this;if(n.length===0)return!1;for(const i of n){const a=String(e[i]??"");if(a.includes("|;"))return!1;t+=a+"|;"}return t}}class Ba extends Error{constructor(e){super(e),this.name="EndpointError"}}const Vz="endpoints";function Sg(r){return typeof r!="object"||r==null?r:"ref"in r?`$${Sg(r.ref)}`:"fn"in r?`${r.fn}(${(r.argv||[]).map(Sg).join(", ")})`:JSON.stringify(r,null,2)}const j1={},zz=(r,e)=>r===e;function $z(...r){for(const e of r)if(e!=null)return e}const Hz=r=>{const e=r.split("."),t=[];for(const n of e){const i=n.indexOf("[");if(i!==-1){if(n.indexOf("]")!==n.length-1)throw new Ba(`Path: '${r}' does not end with ']'`);const a=n.slice(i+1,-1);if(Number.isNaN(parseInt(a)))throw new Ba(`Invalid array index: '${a}' in path: '${r}'`);i!==0&&t.push(n.slice(0,i)),t.push(a)}else t.push(n)}return t},YI=(r,e)=>Hz(e).reduce((t,n)=>{if(typeof t!="object")throw new Ba(`Index '${n}' in '${e}' not found in '${JSON.stringify(r)}'`);if(Array.isArray(t)){const i=parseInt(n);return t[i<0?t.length+i:i]}return t[n]},r),jz=r=>r!=null;function Gz(r,e,t){return r?e:t}const qz=r=>!r,Wz=new RegExp("^(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)(?:\\.(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]\\d|\\d)){3}$"),XI=r=>Wz.test(r)||r.startsWith("[")&&r.endsWith("]"),$v={[xf.HTTP]:80,[xf.HTTPS]:443},Qz=r=>{const e=(()=>{try{if(r instanceof URL)return r;if(typeof r=="object"&&"hostname"in r){const{hostname:d,port:h,protocol:g="",path:v="",query:y={}}=r,A=new URL(`${g}//${d}${h?`:${h}`:""}${v}`);return A.search=Object.entries(y).map(([C,S])=>`${C}=${S}`).join("&"),A}return new URL(r)}catch{return null}})();if(!e)return console.error(`Unable to parse ${JSON.stringify(r)} as a whatwg URL.`),null;const t=e.href,{host:n,hostname:i,pathname:a,protocol:s,search:o}=e;if(o)return null;const l=s.slice(0,-1);if(!Object.values(xf).includes(l))return null;const u=XI(i),c=t.includes(`${n}:${$v[l]}`)||typeof r=="string"&&r.includes(`${n}:${$v[l]}`),f=`${n}${c?`:${$v[l]}`:""}`;return{scheme:l,authority:f,path:a,normalizedPath:a.endsWith("/")?a:`${a}/`,isIp:u}};function Yz(r,e,t){if(t===1)return[r];if(r==="")return[""];const n=r.split(e);return t===0?n:n.slice(0,t-1).concat(n.slice(1).join(e))}const Xz=(r,e)=>r===e,Jz=(r,e,t,n)=>r==null||e>=t||r.length<t||/[^\u0000-\u007f]/.test(r)?null:n?r.substring(r.length-t,r.length-e):r.substring(e,t),Kz=r=>encodeURIComponent(r).replace(/[!*'()]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase()}`),Zz={booleanEquals:zz,coalesce:$z,getAttr:YI,isSet:jz,isValidHostLabel:Kg,ite:Gz,not:qz,parseURL:Qz,split:Yz,stringEquals:Xz,substring:Jz,uriEncode:Kz},JI=(r,e)=>{const t=[],{referenceRecord:n,endpointParams:i}=e;let a=0;for(;a<r.length;){const s=r.indexOf("{",a);if(s===-1){t.push(r.slice(a));break}t.push(r.slice(a,s));const o=r.indexOf("}",s);if(o===-1){t.push(r.slice(s));break}r[s+1]==="{"&&r[o+1]==="}"&&(t.push(r.slice(s+1,o)),a=o+2);const l=r.substring(s+1,o);if(l.includes("#")){const[u,c]=l.split("#");t.push(YI(n[u]??i[u],c))}else t.push(n[l]??i[l]);a=o+1}return t.join("")},e$=({ref:r},e)=>e.referenceRecord[r]??e.endpointParams[r],rm=(r,e,t)=>{if(typeof r=="string")return JI(r,t);if(r.fn)return ZI.callFunction(r,t);if(r.ref)return e$(r,t);throw new Ba(`'${e}': ${String(r)} is not a string, function or reference.`)},KI=({fn:r,argv:e},t)=>{const n=Array(e.length);for(let s=0;s<n.length;++s){const o=e[s];typeof o=="boolean"||typeof o=="number"?n[s]=o:n[s]=ZI.evaluateExpression(o,"arg",t)}const i=r.indexOf(".");if(i!==-1){const o=j1[r.slice(0,i)]?.[r.slice(i+1)];if(typeof o=="function")return o(...n)}const a=Zz[r];if(typeof a=="function")return a(...n);throw new Error(`function ${r} not loaded in endpointFunctions.`)},ZI={evaluateExpression:rm,callFunction:KI},t$=(r,e)=>{const{assign:t}=r;if(t&&t in e.referenceRecord)throw new Ba(`'${t}' is already defined in Reference Record.`);const n=KI(r,e);e.logger?.debug?.(`${Vz} evaluateCondition: ${Sg(r)} = ${Sg(n)}`);const i=n===""?!0:!!n;return t!=null?{result:i,toAssign:{name:t,value:n}}:{result:i}},r$=(r,e)=>Object.entries(r??{}).reduce((t,[n,i])=>(t[n]=i.map(a=>{const s=rm(a,"Header value entry",e);if(typeof s!="string")throw new Ba(`Header '${n}' value '${s}' is not a string`);return s}),t),{}),eP=(r,e)=>Object.entries(r).reduce((t,[n,i])=>(t[n]=rP.getEndpointProperty(i,e),t),{}),tP=(r,e)=>{if(Array.isArray(r))return r.map(t=>tP(t,e));switch(typeof r){case"string":return JI(r,e);case"object":if(r===null)throw new Ba(`Unexpected endpoint property: ${r}`);return rP.getEndpointProperties(r,e);case"boolean":return r;default:throw new Ba(`Unexpected endpoint property type: ${typeof r}`)}},rP={getEndpointProperty:tP,getEndpointProperties:eP},n$=(r,e)=>{const t=rm(r,"Endpoint URL",e);if(typeof t=="string")try{return new URL(t)}catch(n){throw console.error(`Failed to construct URL with ${t}`,n),n}throw new Ba(`Endpoint URL must be a string, got ${typeof t}`)},Hv=1e8,i$=(r,e)=>{const{nodes:t,root:n,results:i,conditions:a}=r;let s=n;const o={},l={referenceRecord:o,endpointParams:e.endpointParams,logger:e.logger};for(;s!==1&&s!==-1&&s<Hv;){const u=3*(Math.abs(s)-1),[c,f,d]=[t[u],t[u+1],t[u+2]],[h,g,v]=a[c],y=t$({fn:h,assign:v,argv:g},l);if(y.toAssign){const{name:A,value:C}=y.toAssign;o[A]=C}s=s>=0===y.result?f:d}if(s>=Hv){const u=i[s-Hv];if(u[0]===-1){const[,h]=u;throw new Ba(rm(h,"Error",l))}const[c,f,d]=u;return{url:n$(c,l),properties:eP(f,l),headers:r$(d??{},l)}}throw new Ba("No matching endpoint.")},a$=Lz(QI),nP=Nz(QI);class jv extends YV(em,kl,Cg,Zg){}const s$=r=>crypto.getRandomValues(r),iP=XV(s$),o$=iP,bA=async(r=new Uint8Array,e)=>{if(r instanceof Uint8Array)return jv.mutate(r);if(!r)return jv.mutate(new Uint8Array);const t=e.streamCollector(r);return jv.mutate(await t)};class l${serdeContext;setSerdeContext(e){this.serdeContext=e}}class u$ extends l${options;compositeErrorRegistry;constructor(e){super(),this.options=e,this.compositeErrorRegistry=Zi.for(e.defaultNamespace);for(const t of e.errorTypeRegistries??[])this.compositeErrorRegistry.copyFrom(t)}getRequestType(){return na}getResponseType(){return sc}setSerdeContext(e){this.serdeContext=e,this.serializer.setSerdeContext(e),this.deserializer.setSerdeContext(e),this.getPayloadCodec()&&this.getPayloadCodec().setSerdeContext(e)}updateServiceEndpoint(e,t){if("url"in t){e.protocol=t.url.protocol,e.hostname=t.url.hostname,e.port=t.url.port?Number(t.url.port):void 0,e.path=t.url.pathname,e.fragment=t.url.hash||void 0,e.username=t.url.username||void 0,e.password=t.url.password||void 0,e.query||(e.query={});for(const[n,i]of t.url.searchParams.entries())e.query[n]=i;if(t.headers)for(const n in t.headers)e.headers[n]=t.headers[n].join(", ");return e}else{if(e.protocol=t.protocol,e.hostname=t.hostname,e.port=t.port?Number(t.port):void 0,e.path=t.path,e.query={...t.query},t.headers)for(const n in t.headers)e.headers[n]=t.headers[n];return e}}setHostPrefix(e,t,n){if(this.serdeContext?.disableHostPrefix)return;const i=vi.of(t.input),a=zd(t.traits??{});if(a.endpoint){let s=a.endpoint?.[0];if(typeof s=="string"){for(const[o,l]of i.structIterator()){if(!l.getMergedTraits().hostLabel)continue;const u=n[o];if(typeof u!="string")throw new Error(`@smithy/core/schema - ${o} in input must be a string as hostLabel.`);s=s.replace(`{${o}}`,u)}e.hostname=s+e.hostname}}}deserializeMetadata(e){return{httpStatusCode:e.statusCode,requestId:e.headers["x-amzn-requestid"]??e.headers["x-amzn-request-id"]??e.headers["x-amz-request-id"],extendedRequestId:e.headers["x-amz-id-2"],cfId:e.headers["x-amz-cf-id"]}}async serializeEventStream({eventStream:e,requestSchema:t,initialRequest:n}){return(await this.loadEventStreamCapability()).serializeEventStream({eventStream:e,requestSchema:t,initialRequest:n})}async deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:n}){return(await this.loadEventStreamCapability()).deserializeEventStream({response:e,responseSchema:t,initialResponseContainer:n})}async loadEventStreamCapability(){const{EventStreamSerde:e,eventStreamSerdeProvider:t}=await Promise.resolve().then(()=>require("./index.browser-D4JoLiDS.cjs")),n=this.resolveEventStreamMarshaller(t);return new e({marshaller:n,serializer:this.serializer,deserializer:this.deserializer,serdeContext:this.serdeContext,defaultContentType:this.getDefaultContentType()})}resolveEventStreamMarshaller(e){const t=this.serdeContext;return t.eventStreamMarshaller?t.eventStreamMarshaller:e(this.serdeContext)}getDefaultContentType(){throw new Error(`@smithy/core/protocols - ${this.constructor.name} getDefaultContentType() implementation missing.`)}async deserializeHttpMessage(e,t,n,i,a){return[]}getEventStreamMarshaller(){const e=this.serdeContext;if(!e.eventStreamMarshaller)throw new Error("@smithy/core - HttpProtocol: eventStreamMarshaller missing in serdeContext.");return e.eventStreamMarshaller}}class c$ extends u${async serializeRequest(e,t,n){const i=this.serializer,a={},s={},o=await n.endpoint(),l=vi.of(e?.input),u=l.getSchema();let c;const f=t&&typeof t=="object"?t:{},d=new na({protocol:"",hostname:"",port:void 0,path:"/",fragment:void 0,query:a,headers:s,body:void 0});if(o&&(this.updateServiceEndpoint(d,o),this.setHostPrefix(d,e,f)),f){const h=l.getEventStreamMember();if(h){if(f[h]){const g={};for(const[v,y]of l.structIterator())v!==h&&f[v]&&(i.write(y,f[v]),g[v]=i.flush());c=await this.serializeEventStream({eventStream:f[h],requestSchema:l,initialRequest:g})}}else i.write(u,f),c=i.flush()}return d.headers=Object.assign(d.headers,s),d.query=a,d.body=c,d.method="POST",d}async deserializeResponse(e,t,n){const i=this.deserializer,a=vi.of(e.output),s={};if(n.statusCode>=300){const l=await bA(n.body,t);throw l.byteLength>0&&Object.assign(s,await i.read(15,l)),await this.handleError(e,t,n,s,this.deserializeMetadata(n)),new Error("@smithy/core/protocols - RPC Protocol error handler failed to throw.")}for(const l in n.headers){const u=n.headers[l];delete n.headers[l],n.headers[l.toLowerCase()]=u}const o=a.getEventStreamMember();if(o)s[o]=await this.deserializeEventStream({response:n,responseSchema:a,initialResponseContainer:s});else{const l=await bA(n.body,t);l.byteLength>0&&Object.assign(s,await i.read(a,l))}return s.$metadata=this.deserializeMetadata(n),s}}function aP(r,e){if(e.timestampFormat.useTrait&&r.isTimestampSchema()&&(r.getSchema()===5||r.getSchema()===6||r.getSchema()===7))return r.getSchema();const{httpLabel:t,httpPrefixHeaders:n,httpHeader:i,httpQuery:a}=r.getMergedTraits();return(e.httpBindings?typeof n=="string"||i?6:a||t?5:void 0:void 0)??e.timestampFormat.default}const d$=r=>({setHttpHandler(e){r.httpHandler=e},httpHandler(){return r.httpHandler},updateHttpClientConfig(e,t){r.httpHandler?.updateHttpClientConfig(e,t)},httpHandlerConfigs(){return r.httpHandler.httpHandlerConfigs()}}),f$=r=>({httpHandler:r.httpHandler()}),HE="content-length";function h$(r){return e=>async t=>{const n=t.request;if(na.isInstance(n)){const{body:i,headers:a}=n;if(i&&Object.keys(a).map(s=>s.toLowerCase()).indexOf(HE)===-1)try{const s=r(i);n.headers={...n.headers,[HE]:String(s)}}catch{}}return e({...t,request:n})}}const p$={step:"build",tags:["SET_CONTENT_LENGTH","CONTENT_LENGTH"],name:"contentLengthMiddleware",override:!0},g$=r=>({applyToStack:e=>{e.add(h$(r.bodyLengthChecker),p$)}}),Cl=r=>encodeURIComponent(r).replace(/[!'()*]/g,m$),m$=r=>`%${r.charCodeAt(0).toString(16).toUpperCase()}`;function v$(r){const e=[];for(let t of Object.keys(r).sort()){const n=r[t];if(t=Cl(t),Array.isArray(n))for(let i=0,a=n.length;i<a;i++)e.push(`${t}=${Cl(n[i])}`);else{let i=t;(n||typeof n=="string")&&(i+=`=${Cl(n)}`),e.push(i)}}return e.join("&")}const y$=["BandwidthLimitExceeded","EC2ThrottledException","LimitExceededException","PriorRequestNotComplete","ProvisionedThroughputExceededException","RequestLimitExceeded","RequestThrottled","RequestThrottledException","SlowDown","ThrottledException","Throttling","ThrottlingException","TooManyRequestsException","TransactionInProgressException"],A$=["TimeoutError","RequestTimeout","RequestTimeoutException"],w$=[500,502,503,504],b$=["ECONNRESET","ECONNREFUSED","EPIPE","ETIMEDOUT"],C$=["EHOSTUNREACH","ENETUNREACH","ENOTFOUND","EAI_AGAIN"],x$=r=>r?.$retryable!==void 0,S$=r=>r.$metadata?.clockSkewCorrected,E$=r=>{const e=new Set(["Failed to fetch","NetworkError when attempting to fetch resource","The Internet connection appears to be offline","Load failed","Network request failed"]);return r&&r instanceof TypeError?e.has(r.message):!1},sP=r=>r.$metadata?.httpStatusCode===429||y$.includes(r.name)||r.$retryable?.throttling==!0,G1=(r,e=0)=>x$(r)||S$(r)||r.name==="InvalidSignatureException"&&r.message?.includes("Signature expired")||A$.includes(r.name)||b$.includes(r?.code||"")||C$.includes(r?.code||"")||w$.includes(r.$metadata?.httpStatusCode||0)||E$(r)||T$(r)||r.cause!==void 0&&e<=10&&G1(r.cause,e+1),k$=r=>{if(r.$metadata?.httpStatusCode!==void 0){const e=r.$metadata.httpStatusCode;return 500<=e&&e<=599&&!G1(r)}return!1};function T$(r){return r.code==="ERR_HTTP2_STREAM_ERROR"&&r.message.includes("NGHTTP2_REFUSED_STREAM")}const oP=20*1e3,jE=500,F$=1,I$="amz-sdk-invocation-id",P$="amz-sdk-request";function D$(r,e){if(sc.isInstance(r))for(const t of Object.keys(r.headers)){const n=t.toLowerCase();if(n==="retry-after"){const i=r.headers[t];let a=NaN;if(i.endsWith("GMT"))try{a=(GI(i).getTime()-Date.now())/1e3}catch(s){e?.trace?.("Failed to parse retry-after header"),e?.trace?.(s)}else i.match(/ GMT, ((\d+)|(\d+\.\d+))$/)?a=Number(i.match(/ GMT, ([\d.]+)$/)?.[1]):i.match(/^((\d+)|(\d+\.\d+))$/)?a=Number(i):Date.parse(i)>=Date.now()&&(a=(Date.parse(i)-Date.now())/1e3);return isNaN(a)?void 0:new Date(Date.now()+a*1e3)}else if(n==="x-amz-retry-after"){const i=r.headers[t],a=Number(i);if(isNaN(a)){e?.trace?.(`Failed to parse x-amz-retry-after=${i}`);return}return new Date(Date.now()+a)}}}const R$=r=>r instanceof Error?r:r instanceof Object?Object.assign(new Error,r):typeof r=="string"?new Error(r):new Error(`AWS SDK error wrapper for ${r}`);function O$(r){return e=>(t,n)=>async i=>{let a=await e.retryStrategy();const s=await e.maxAttempts();if(M$(a)){a=a;let o=await a.acquireInitialRetryToken((n.partition_id??"")+(n.__retryLongPoll?":longpoll":"")),l=new Error,u=0,c=0;const{request:f}=i,d=na.isInstance(f);for(d&&(f.headers[I$]=iP());;)try{d&&(f.headers[P$]=`attempt=${u+1}; max=${s}`);const{response:h,output:g}=await t(i);return a.recordSuccess(o),g.$metadata.attempts=u+1,g.$metadata.totalRetryDelay=c,{response:h,output:g}}catch(h){const g=_$(h,e.logger);if(l=R$(h),d&&r(f))throw(n.logger instanceof $I?console:n.logger)?.warn("An error was encountered in a non-retryable streaming request."),l;try{o=await a.refreshRetryTokenForRetry(o,g)}catch{throw l.$metadata||(l.$metadata={}),l.$metadata.attempts=u+1,l.$metadata.totalRetryDelay=c,l}u=o.getRetryCount();const v=o.getRetryDelay();c+=(o?.$retryLog?.acquisitionDelay??0)+v,v>0&&await B$(v)}}else return a=a,a?.mode&&(n.userAgent=[...n.userAgent||[],["cfg/retry-mode",a.mode]]),a.retry(t,i)}}const B$=r=>new Promise(e=>setTimeout(e,r)),M$=r=>typeof r.acquireInitialRetryToken<"u"&&typeof r.refreshRetryTokenForRetry<"u"&&typeof r.recordSuccess<"u",_$=(r,e)=>{const t={error:r,errorType:N$(r)},n=D$(r.$response,e);return n&&(t.retryAfterHint=n),t},N$=r=>sP(r)?"THROTTLING":G1(r)?"TRANSIENT":k$(r)?"SERVER_ERROR":"CLIENT_ERROR",L$={name:"retryMiddleware",tags:["RETRY"],step:"finalizeRequest",priority:"high",override:!0};function U$(r){const e=O$(r);return t=>({applyToStack:n=>{n.add(e(t),L$)}})}class q1{static setTimeoutFn=(e,t)=>setTimeout(e,t);beta;minCapacity;minFillRate;scaleConstant;smooth;enabled=!1;availableTokens=0;lastMaxRate=0;measuredTxRate=0;requestCount=0;fillRate;lastThrottleTime;lastTimestamp=0;lastTxRateBucket;maxCapacity;timeWindow=0;constructor(e){this.beta=e?.beta??.7,this.minCapacity=e?.minCapacity??1,this.minFillRate=e?.minFillRate??.5,this.scaleConstant=e?.scaleConstant??.4,this.smooth=e?.smooth??.8,this.lastThrottleTime=this.getCurrentTimeInSeconds(),this.lastTxRateBucket=Math.floor(this.getCurrentTimeInSeconds()),this.fillRate=this.minFillRate,this.maxCapacity=this.minCapacity}async getSendToken(){return this.acquireTokenBucket(1)}updateClientSendingRate(e){let t;this.updateMeasuredRate();const n=e;if(n?.errorType==="THROTTLING"||sP(n?.error??e)){const s=this.enabled?Math.min(this.measuredTxRate,this.fillRate):this.measuredTxRate;this.lastMaxRate=s,this.calculateTimeWindow(),this.lastThrottleTime=this.getCurrentTimeInSeconds(),t=this.cubicThrottle(s),this.enableTokenBucket()}else this.calculateTimeWindow(),t=this.cubicSuccess(this.getCurrentTimeInSeconds());const a=Math.min(t,2*this.measuredTxRate);this.updateTokenBucketRate(a)}getCurrentTimeInSeconds(){return Date.now()/1e3}async acquireTokenBucket(e){if(this.enabled){for(this.refillTokenBucket();e>this.availableTokens;){const t=(e-this.availableTokens)/this.fillRate*1e3;await new Promise(n=>q1.setTimeoutFn(n,t)),this.refillTokenBucket()}this.availableTokens=this.availableTokens-e}}refillTokenBucket(){const e=this.getCurrentTimeInSeconds();if(!this.lastTimestamp){this.lastTimestamp=e;return}const t=(e-this.lastTimestamp)*this.fillRate;this.availableTokens=Math.min(this.maxCapacity,this.availableTokens+t),this.lastTimestamp=e}calculateTimeWindow(){this.timeWindow=this.getPrecise(Math.pow(this.lastMaxRate*(1-this.beta)/this.scaleConstant,1/3))}cubicThrottle(e){return this.getPrecise(e*this.beta)}cubicSuccess(e){return this.getPrecise(this.scaleConstant*Math.pow(e-this.lastThrottleTime-this.timeWindow,3)+this.lastMaxRate)}enableTokenBucket(){this.enabled=!0}updateTokenBucketRate(e){this.refillTokenBucket(),this.fillRate=Math.max(e,this.minFillRate),this.maxCapacity=Math.max(e,this.minCapacity),this.availableTokens=Math.min(this.availableTokens,this.maxCapacity)}updateMeasuredRate(){const e=this.getCurrentTimeInSeconds(),t=Math.floor(e*2)/2;if(this.requestCount++,t>this.lastTxRateBucket){const n=this.requestCount/(t-this.lastTxRateBucket);this.measuredTxRate=this.getPrecise(n*this.smooth+this.measuredTxRate*(1-this.smooth)),this.requestCount=0,this.lastTxRateBucket=t}}getPrecise(e){return parseFloat(e.toFixed(8))}}class Ei{static v2026=typeof process<"u"&&process.env?.SMITHY_NEW_RETRIES_2026==="true";static delay(){return Ei.v2026?50:100}static throttlingDelay(){return Ei.v2026?1e3:500}static cost(){return Ei.v2026?14:5}static throttlingCost(){return Ei.v2026?5:10}static modifiedCostType(){return Ei.v2026?"THROTTLING":"TRANSIENT"}}class V${x=Ei.delay();computeNextBackoffDelay(e){const i=Math.random()*Math.min(this.x*2**e,oP);return Math.floor(i)}setDelayBase(e){this.x=e}}class GE{delay;count;cost;longPoll;$retryLog={acquisitionDelay:0};constructor(e,t,n,i){this.delay=e,this.count=t,this.cost=n,this.longPoll=i}getRetryCount(){return this.count}getRetryDelay(){return Math.min(oP,this.delay)}getRetryCost(){return this.cost}isLongPoll(){return this.longPoll}}var Po;(function(r){r.STANDARD="standard",r.ADAPTIVE="adaptive"})(Po||(Po={}));const ef=3,z$=Po.STANDARD,kp={incompatible:1,attempts:2,capacity:3};class CA{mode=Po.STANDARD;retryBackoffStrategy;capacity=jE;maxAttemptsProvider;baseDelay;constructor(e){typeof e=="number"?this.maxAttemptsProvider=async()=>e:typeof e=="function"?this.maxAttemptsProvider=e:e&&typeof e=="object"&&(this.maxAttemptsProvider=async()=>e.maxAttempts,this.baseDelay=e.baseDelay,this.retryBackoffStrategy=e.backoff),this.maxAttemptsProvider??=async()=>ef,this.baseDelay??=Ei.delay(),this.retryBackoffStrategy??=new V$}async acquireInitialRetryToken(e){return new GE(Ei.delay(),0,void 0,Ei.v2026&&e.includes(":longpoll"))}async refreshRetryTokenForRetry(e,t){const n=await this.getMaxAttempts(),i=this.retryCode(e,t,n),a=i===0,s=e.isLongPoll?.();if(a||s){const o=t.errorType;this.retryBackoffStrategy.setDelayBase(o==="THROTTLING"?Ei.throttlingDelay():this.baseDelay);const l=this.retryBackoffStrategy.computeNextBackoffDelay(e.getRetryCount());let u=l;if(t.retryAfterHint instanceof Date&&(u=Math.max(l,Math.min(t.retryAfterHint.getTime()-Date.now(),l+5e3))),a){const c=this.getCapacityCost(o);this.capacity-=c;const f=new GE(0,e.getRetryCount()+1,c,e.isLongPoll?.()??!1);return await new Promise(d=>setTimeout(d,u)),f.$retryLog.acquisitionDelay=u,f}else{const c=Ei.v2026&&i===kp.capacity&&s?u:0;c>0&&await new Promise(f=>setTimeout(f,c))}}throw new Error("No retry token available")}recordSuccess(e){this.capacity=Math.min(jE,this.capacity+(e.getRetryCost()??F$))}getCapacity(){return this.capacity}async maxAttempts(){return this.maxAttemptsProvider()}async getMaxAttempts(){try{return await this.maxAttemptsProvider()}catch{return console.warn(`Max attempts provider could not resolve. Using default of ${ef}`),ef}}retryCode(e,t,n){const i=e.getRetryCount()+1,a=this.isRetryableError(t.errorType)?0:kp.incompatible,s=i<n?0:kp.attempts,o=this.capacity>=this.getCapacityCost(t.errorType)?0:kp.capacity;return a||s||o}getCapacityCost(e){return e===Ei.modifiedCostType()?Ei.throttlingCost():Ei.cost()}isRetryableError(e){return e==="THROTTLING"||e==="TRANSIENT"}}class $${mode=Po.ADAPTIVE;rateLimiter;standardRetryStrategy;constructor(e,t){const{rateLimiter:n}=t??{};this.rateLimiter=n??new q1,this.standardRetryStrategy=t?new CA({maxAttempts:typeof e=="number"?e:3,...t}):new CA(e)}async acquireInitialRetryToken(e){const t=await this.standardRetryStrategy.acquireInitialRetryToken(e);return await this.rateLimiter.getSendToken(),t}async refreshRetryTokenForRetry(e,t){this.rateLimiter.updateClientSendingRate(t);const n=await this.standardRetryStrategy.refreshRetryTokenForRetry(e,t);return await this.rateLimiter.getSendToken(),n}recordSuccess(e){this.rateLimiter.updateClientSendingRate({}),this.standardRetryStrategy.recordSuccess(e)}async maxAttemptsProvider(){return this.standardRetryStrategy.maxAttempts()}}const H$=(r,e)=>{const{retryStrategy:t,retryMode:n}=r,{defaultMaxAttempts:i=ef,defaultBaseDelay:a=Ei.delay()}={},s=Bs(r.maxAttempts??i);let o=t?Promise.resolve(t):void 0;const l=async()=>{const u=await s();return await Bs(n)()===Po.ADAPTIVE?new $$(s,{maxAttempts:u,baseDelay:a}):new CA({maxAttempts:u,baseDelay:a})};return Object.assign(r,{maxAttempts:s,retryStrategy:()=>o??=l()})},j$=U$(TV);Ei.v2026||=typeof process=="object"&&process.env?.AWS_NEW_RETRIES_2026==="true";function Is(r,e,t){r.__aws_sdk_context?r.__aws_sdk_context.features||(r.__aws_sdk_context.features={}):r.__aws_sdk_context={features:{}},r.__aws_sdk_context.features[e]=t}const G$=r=>e=>async t=>{if(!na.isInstance(t.request))return e(t);const{request:n}=t,{handlerProtocol:i=""}=r.requestHandler.metadata||{};if(i.indexOf("h2")>=0&&!n.headers[":authority"])delete n.headers.host,n.headers[":authority"]=n.hostname+(n.port?":"+n.port:"");else if(!n.headers.host){let a=n.hostname;n.port!=null&&(a+=`:${n.port}`),n.headers.host=a}return e(t)},q$={name:"hostHeaderMiddleware",step:"build",priority:"low",tags:["HOST"],override:!0},W$=r=>({applyToStack:e=>{e.add(G$(r),q$)}}),Q$=()=>(r,e)=>async t=>{try{const n=await r(t),{clientName:i,commandName:a,logger:s,dynamoDbDocumentClientOptions:o={}}=e,{overrideInputFilterSensitiveLog:l,overrideOutputFilterSensitiveLog:u}=o,c=l??e.inputFilterSensitiveLog,f=u??e.outputFilterSensitiveLog,{$metadata:d,...h}=n.output;return s?.info?.({clientName:i,commandName:a,input:c(t.input),output:f(h),metadata:d}),n}catch(n){const{clientName:i,commandName:a,logger:s,dynamoDbDocumentClientOptions:o={}}=e,{overrideInputFilterSensitiveLog:l}=o,u=l??e.inputFilterSensitiveLog;throw s?.error?.({clientName:i,commandName:a,input:u(t.input),error:n,metadata:n.$metadata}),n}},Y$={name:"loggerMiddleware",tags:["LOGGER"],step:"initialize",override:!0},X$=r=>({applyToStack:e=>{e.add(Q$(),Y$)}}),J$=r=>({applyToStack:e=>{}}),K$=(r,e)=>{if(!e||e.length===0)return r;const t=[];for(const n of e)for(const i of r)i.schemeId.split("#")[1]===n&&t.push(i);for(const n of r)t.find(({schemeId:i})=>i===n.schemeId)||t.push(n);return t};function Z$(r){const e=new Map;for(const t of r)e.set(t.schemeId,t);return e}const eH=(r,e)=>(t,n)=>async i=>{const a=r.httpAuthSchemeProvider(await e.httpAuthSchemeParametersProvider(r,n,i.input)),s=r.authSchemePreference?await r.authSchemePreference():[],o=K$(a,s),l=Z$(r.httpAuthSchemes),u=vc(n),c=[];for(const f of o){const d=l.get(f.schemeId);if(!d){c.push(`HttpAuthScheme \`${f.schemeId}\` was not enabled for this service.`);continue}const h=d.identityProvider(await e.identityProviderConfigProvider(r));if(!h){c.push(`HttpAuthScheme \`${f.schemeId}\` did not have an IdentityProvider configured.`);continue}const{identityProperties:g={},signingProperties:v={}}=f.propertiesExtractor?.(r,n)||{};f.identityProperties=Object.assign(f.identityProperties||{},g),f.signingProperties=Object.assign(f.signingProperties||{},v),u.selectedHttpAuthScheme={httpAuthOption:f,identity:await h(f.identityProperties),signer:d.signer};break}if(!u.selectedHttpAuthScheme)throw new Error(c.join(`
3043
3043
  `));return t(i)},tH={step:"serialize",tags:["HTTP_AUTH_SCHEME"],name:"httpAuthSchemeMiddleware",override:!0,relation:"before",toMiddleware:"endpointV2Middleware"},rH=(r,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:t})=>({applyToStack:n=>{n.addRelativeTo(eH(r,{httpAuthSchemeParametersProvider:e,identityProviderConfigProvider:t}),tH)}}),nH=r=>e=>{throw e},iH=(r,e)=>{},aH=r=>(e,t)=>async n=>{if(!na.isInstance(n.request))return e(n);const a=vc(t).selectedHttpAuthScheme;if(!a)throw new Error("No HttpAuthScheme was selected: unable to sign request");const{httpAuthOption:{signingProperties:s={}},identity:o,signer:l}=a,u=await e({...n,request:await l.sign(n.request,o,s)}).catch((l.errorHandler||nH)(s));return(l.successHandler||iH)(u.response,s),u},sH={step:"finalizeRequest",tags:["HTTP_SIGNING"],name:"httpSigningMiddleware",aliases:["apiKeyMiddleware","tokenMiddleware","awsAuthMiddleware"],override:!0,relation:"after",toMiddleware:"retryMiddleware"},oH=r=>({applyToStack:e=>{e.addRelativeTo(aH(),sH)}}),tf=r=>{if(typeof r=="function")return r;const e=Promise.resolve(r);return()=>e};class lH{authSchemes=new Map;constructor(e){for(const t in e){const n=e[t];n!==void 0&&this.authSchemes.set(t,n)}}getIdentityProvider(e){return this.authSchemes.get(e)}}class uH{async sign(e,t,n){return e}}const cH=r=>function(t){return lP(t)&&t.expiration.getTime()-Date.now()<r},dH=3e5,fH=cH(dH),lP=r=>r.expiration!==void 0,hH=(r,e,t)=>{if(r===void 0)return;const n=typeof r!="function"?async()=>Promise.resolve(r):r;let i,a,s,o=!1;const l=async u=>{a||(a=n(u));try{i=await a,s=!0,o=!1}finally{a=void 0}return i};return e===void 0?async u=>((!s||u?.forceRefresh)&&(i=await l(u)),i):async u=>((!s||u?.forceRefresh)&&(i=await l(u)),o?i:t(i)?(e(i)&&await l(u),i):(o=!0,i))},pH=void 0;function gH(r){return r===void 0?!0:typeof r=="string"&&r.length<=50}function mH(r){const e=tf(r.userAgentAppId??pH),{customUserAgent:t}=r;return Object.assign(r,{customUserAgent:typeof t=="string"?[[t]]:t,userAgentAppId:async()=>{const n=await e();if(!gH(n)){const i=r.logger?.constructor?.name==="NoOpLogger"||!r.logger?console:r.logger;typeof n!="string"?i?.warn("userAgentAppId must be a string or undefined."):n.length>50&&i?.warn("The provided userAgentAppId exceeds the maximum length of 50 characters.")}return n}})}const vH={partitions:[{id:"aws",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-east-1",name:"aws",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^(us|eu|ap|sa|ca|me|af|il|mx)\\-\\w+\\-\\d+$",regions:{"af-south-1":{description:"Africa (Cape Town)"},"ap-east-1":{description:"Asia Pacific (Hong Kong)"},"ap-east-2":{description:"Asia Pacific (Taipei)"},"ap-northeast-1":{description:"Asia Pacific (Tokyo)"},"ap-northeast-2":{description:"Asia Pacific (Seoul)"},"ap-northeast-3":{description:"Asia Pacific (Osaka)"},"ap-south-1":{description:"Asia Pacific (Mumbai)"},"ap-south-2":{description:"Asia Pacific (Hyderabad)"},"ap-southeast-1":{description:"Asia Pacific (Singapore)"},"ap-southeast-2":{description:"Asia Pacific (Sydney)"},"ap-southeast-3":{description:"Asia Pacific (Jakarta)"},"ap-southeast-4":{description:"Asia Pacific (Melbourne)"},"ap-southeast-5":{description:"Asia Pacific (Malaysia)"},"ap-southeast-6":{description:"Asia Pacific (New Zealand)"},"ap-southeast-7":{description:"Asia Pacific (Thailand)"},"aws-global":{description:"aws global region"},"ca-central-1":{description:"Canada (Central)"},"ca-west-1":{description:"Canada West (Calgary)"},"eu-central-1":{description:"Europe (Frankfurt)"},"eu-central-2":{description:"Europe (Zurich)"},"eu-north-1":{description:"Europe (Stockholm)"},"eu-south-1":{description:"Europe (Milan)"},"eu-south-2":{description:"Europe (Spain)"},"eu-west-1":{description:"Europe (Ireland)"},"eu-west-2":{description:"Europe (London)"},"eu-west-3":{description:"Europe (Paris)"},"il-central-1":{description:"Israel (Tel Aviv)"},"me-central-1":{description:"Middle East (UAE)"},"me-south-1":{description:"Middle East (Bahrain)"},"mx-central-1":{description:"Mexico (Central)"},"sa-east-1":{description:"South America (Sao Paulo)"},"us-east-1":{description:"US East (N. Virginia)"},"us-east-2":{description:"US East (Ohio)"},"us-west-1":{description:"US West (N. California)"},"us-west-2":{description:"US West (Oregon)"}}},{id:"aws-cn",outputs:{dnsSuffix:"amazonaws.com.cn",dualStackDnsSuffix:"api.amazonwebservices.com.cn",implicitGlobalRegion:"cn-northwest-1",name:"aws-cn",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^cn\\-\\w+\\-\\d+$",regions:{"aws-cn-global":{description:"aws-cn global region"},"cn-north-1":{description:"China (Beijing)"},"cn-northwest-1":{description:"China (Ningxia)"}}},{id:"aws-eusc",outputs:{dnsSuffix:"amazonaws.eu",dualStackDnsSuffix:"api.amazonwebservices.eu",implicitGlobalRegion:"eusc-de-east-1",name:"aws-eusc",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eusc\\-(de)\\-\\w+\\-\\d+$",regions:{"eusc-de-east-1":{description:"AWS European Sovereign Cloud (Germany)"}}},{id:"aws-iso",outputs:{dnsSuffix:"c2s.ic.gov",dualStackDnsSuffix:"api.aws.ic.gov",implicitGlobalRegion:"us-iso-east-1",name:"aws-iso",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-iso\\-\\w+\\-\\d+$",regions:{"aws-iso-global":{description:"aws-iso global region"},"us-iso-east-1":{description:"US ISO East"},"us-iso-west-1":{description:"US ISO WEST"}}},{id:"aws-iso-b",outputs:{dnsSuffix:"sc2s.sgov.gov",dualStackDnsSuffix:"api.aws.scloud",implicitGlobalRegion:"us-isob-east-1",name:"aws-iso-b",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isob\\-\\w+\\-\\d+$",regions:{"aws-iso-b-global":{description:"aws-iso-b global region"},"us-isob-east-1":{description:"US ISOB East (Ohio)"},"us-isob-west-1":{description:"US ISOB West"}}},{id:"aws-iso-e",outputs:{dnsSuffix:"cloud.adc-e.uk",dualStackDnsSuffix:"api.cloud-aws.adc-e.uk",implicitGlobalRegion:"eu-isoe-west-1",name:"aws-iso-e",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^eu\\-isoe\\-\\w+\\-\\d+$",regions:{"aws-iso-e-global":{description:"aws-iso-e global region"},"eu-isoe-west-1":{description:"EU ISOE West"}}},{id:"aws-iso-f",outputs:{dnsSuffix:"csp.hci.ic.gov",dualStackDnsSuffix:"api.aws.hci.ic.gov",implicitGlobalRegion:"us-isof-south-1",name:"aws-iso-f",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-isof\\-\\w+\\-\\d+$",regions:{"aws-iso-f-global":{description:"aws-iso-f global region"},"us-isof-east-1":{description:"US ISOF EAST"},"us-isof-south-1":{description:"US ISOF SOUTH"}}},{id:"aws-us-gov",outputs:{dnsSuffix:"amazonaws.com",dualStackDnsSuffix:"api.aws",implicitGlobalRegion:"us-gov-west-1",name:"aws-us-gov",supportsDualStack:!0,supportsFIPS:!0},regionRegex:"^us\\-gov\\-\\w+\\-\\d+$",regions:{"aws-us-gov-global":{description:"aws-us-gov global region"},"us-gov-east-1":{description:"AWS GovCloud (US-East)"},"us-gov-west-1":{description:"AWS GovCloud (US-West)"}}}]};let yH=vH;const AH=r=>{const{partitions:e}=yH;for(const n of e){const{regions:i,outputs:a}=n;for(const[s,o]of Object.entries(i))if(s===r)return{...a,...o}}for(const n of e){const{regionRegex:i,outputs:a}=n;if(new RegExp(i).test(r))return{...a}}const t=e.find(n=>n.id==="aws");if(!t)throw new Error("Provided region was not found in the partition array or regex, and default partition with id 'aws' doesn't exist.");return{...t.outputs}},wH=/\d{12}\.ddb/;async function bH(r,e,t){if(t.request?.headers?.["smithy-protocol"]==="rpc-v2-cbor"&&Is(r,"PROTOCOL_RPC_V2_CBOR","M"),typeof e.retryStrategy=="function"){const a=await e.retryStrategy();if(typeof a.mode=="string")switch(a.mode){case Po.ADAPTIVE:Is(r,"RETRY_MODE_ADAPTIVE","F");break;case Po.STANDARD:Is(r,"RETRY_MODE_STANDARD","E");break}}if(typeof e.accountIdEndpointMode=="function"){const a=r.endpointV2;switch(String(a?.url?.hostname).match(wH)&&Is(r,"ACCOUNT_ID_ENDPOINT","O"),await e.accountIdEndpointMode?.()){case"disabled":Is(r,"ACCOUNT_ID_MODE_DISABLED","Q");break;case"preferred":Is(r,"ACCOUNT_ID_MODE_PREFERRED","P");break;case"required":Is(r,"ACCOUNT_ID_MODE_REQUIRED","R");break}}const i=r.__smithy_context?.selectedHttpAuthScheme?.identity;if(i?.$source){const a=i;a.accountId&&Is(r,"RESOLVED_ACCOUNT_ID","T");for(const[s,o]of Object.entries(a.$source??{}))Is(r,s,o)}}const qE="user-agent",Gv="x-amz-user-agent",WE=" ",qv="/",CH=/[^!$%&'*+\-.^_`|~\w]/g,xH=/[^!$%&'*+\-.^_`|~\w#]/g,QE="-",SH=1024;function EH(r){let e="";for(const t in r){const n=r[t];if(e.length+n.length+1<=SH){e.length?e+=","+n:e+=n;continue}break}return e}const kH=r=>(e,t)=>async n=>{const{request:i}=n;if(!na.isInstance(i))return e(n);const{headers:a}=i,s=t?.userAgent?.map(Tp)||[],o=(await r.defaultUserAgentProvider()).map(Tp);await bH(t,r,n);const l=t;o.push(`m/${EH(Object.assign({},t.__smithy_context?.features,l.__aws_sdk_context?.features))}`);const u=r?.customUserAgent?.map(Tp)||[],c=await r.userAgentAppId();c&&o.push(Tp(["app",`${c}`]));const f=[].concat([...o,...s,...u]).join(WE),d=[...o.filter(h=>h.startsWith("aws-sdk-")),...u].join(WE);return r.runtime!=="browser"?(d&&(a[Gv]=a[Gv]?`${a[qE]} ${d}`:d),a[qE]=f):a[Gv]=f,e({...n,request:i})},Tp=r=>{const e=r[0].split(qv).map(s=>s.replace(CH,QE)).join(qv),t=r[1]?.replace(xH,QE),n=e.indexOf(qv),i=e.substring(0,n);let a=e.substring(n+1);return i==="api"&&(a=a.toLowerCase()),[i,a,t].filter(s=>s&&s.length>0).reduce((s,o,l)=>{switch(l){case 0:return o;case 1:return`${s}/${o}`;default:return`${s}#${o}`}},"")},TH={name:"getUserAgentMiddleware",step:"build",priority:"low",tags:["SET_USER_AGENT","USER_AGENT"],override:!0},FH=r=>({applyToStack:e=>{e.add(kH(r),TH)}}),IH=({serviceId:r,clientVersion:e})=>async t=>{const n=typeof window<"u"?window.navigator:void 0,i=n?.userAgent??"",a=n?.userAgentData?.platform??YE.os(i)??"other",s=void 0,o=n?.userAgentData?.brands??[],l=o[o.length-1],u=l?.brand??YE.browser(i)??"unknown",c=l?.version??"unknown",f=[["aws-sdk-js",e],["ua","2.1"],[`os/${a}`,s],["lang/js"],["md/browser",`${u}_${c}`]];r&&f.push([`api/${r}`,e]);const d=await t?.userAgentAppId?.();return d&&f.push([`app/${d}`]),f},YE={os(r){if(/iPhone|iPad|iPod/.test(r))return"iOS";if(/Macintosh|Mac OS X/.test(r))return"macOS";if(/Windows NT/.test(r))return"Windows";if(/Android/.test(r))return"Android";if(/Linux/.test(r))return"Linux"},browser(r){if(/EdgiOS|EdgA|Edg\//.test(r))return"Microsoft Edge";if(/Firefox\//.test(r))return"Firefox";if(/Chrome\//.test(r))return"Chrome";if(/Safari\//.test(r))return"Safari"}},uP=(r,e=!1)=>{if(e){for(const t of r.split("."))if(!uP(t))return!1;return!0}return!(!Kg(r)||r.length<3||r.length>63||r!==r.toLowerCase()||XI(r))},XE=":",PH="/",DH=r=>{const e=r.split(XE);if(e.length<6)return null;const[t,n,i,a,s,...o]=e;if(t!=="arn"||n===""||i===""||o.join(XE)==="")return null;const l=o.map(u=>u.split(PH)).flat();return{partition:n,service:i,region:a,accountId:s,resourceId:l}},cP={isVirtualHostableS3Bucket:uP,parseArn:DH,partition:AH};j1.aws=cP;const RH=(r,e,t)=>{let n,i,a,s=!1;const o=async()=>{i||(i=r());try{n=await i,a=!0,s=!1}finally{i=void 0}return n};return async l=>((!a||l?.forceRefresh)&&(n=await o()),n)},JE=new Set,OH=(r,e=Kg)=>{if(!JE.has(r)&&!e(r))if(r==="*")console.warn('@smithy/config-resolver WARN - Please use the caller region instead of "*". See "sigv4a" in https://github.com/aws/aws-sdk-js-v3/blob/main/supplemental-docs/CLIENTS.md.');else throw new Error(`Region not accepted: region="${r}" is not a valid hostname component.`);else JE.add(r)},dP=r=>typeof r=="string"&&(r.startsWith("fips-")||r.endsWith("-fips")),BH=r=>dP(r)?["fips-aws-global","aws-fips"].includes(r)?"us-east-1":r.replace(/fips-(dkr-|prod-)?|-fips/,""):r,MH=r=>{const{region:e,useFipsEndpoint:t}=r;if(!e)throw new Error("Region is missing");return Object.assign(r,{region:async()=>{const n=typeof e=="function"?await e():e,i=BH(n);return OH(i),i},useFipsEndpoint:async()=>{const n=typeof e=="string"?e:await e();return dP(n)?!0:typeof t!="function"?Promise.resolve(!!t):t()}})},_H=["in-region","cross-region","mobile","standard","legacy"],NH=({defaultsMode:r}={})=>RH(async()=>{const e=typeof r=="function"?await r():r;switch(e?.toLowerCase()){case"auto":return Promise.resolve(LH()?"mobile":"standard");case"mobile":case"in-region":case"cross-region":case"standard":case"legacy":return Promise.resolve(e?.toLocaleLowerCase());case void 0:return Promise.resolve("legacy");default:throw new Error(`Invalid parameter for "defaultsMode", expect ${_H.join(", ")}, got ${e}`)}}),LH=()=>{const r=window?.navigator;if(r?.connection){const{effectiveType:e,rtt:t,downlink:n}=r?.connection;if(typeof e=="string"&&e!=="4g"||Number(t)>100||Number(n)<10)return!0}return r?.userAgentData?.mobile||typeof r?.maxTouchPoints=="number"&&r?.maxTouchPoints>1},UH=!1,VH=!1,zH=r=>({setRegion(e){r.region=e},region(){return r.region}}),$H=r=>({region:r.region()}),KE=r=>sc.isInstance(r)?r.headers?.date??r.headers?.Date:void 0,fP=r=>new Date(Date.now()+r),HH=(r,e)=>Math.abs(fP(e).getTime()-r)>=3e5,ZE=(r,e)=>{const t=Date.parse(r);return HH(t,e)?t-Date.now():e},rf=(r,e)=>{if(!e)throw new Error(`Property \`${r}\` is not resolved for AWS SDK SigV4Auth`);return e},jH=async r=>{const e=rf("context",r.context),t=rf("config",r.config),n=e.endpointV2?.properties?.authSchemes?.[0],a=await rf("signer",t.signer)(n),s=r?.signingRegion,o=r?.signingRegionSet,l=r?.signingName;return{config:t,signer:a,signingRegion:s,signingRegionSet:o,signingName:l}};class GH{async sign(e,t,n){if(!na.isInstance(e))throw new Error("The request is not an instance of `HttpRequest` and cannot be signed");const i=await jH(n),{config:a,signer:s}=i;let{signingRegion:o,signingName:l}=i;const u=n.context;if(u?.authSchemes?.length??!1){const[f,d]=u.authSchemes;f?.name==="sigv4a"&&d?.name==="sigv4"&&(o=d?.signingRegion??o,l=d?.signingName??l)}return n._preRequestSystemClockOffset=a.systemClockOffset,await s.sign(e,{signingDate:fP(a.systemClockOffset),signingRegion:o,signingService:l})}errorHandler(e){return t=>{const n=t,i=n.ServerTime??KE(n.$response);if(i){const a=rf("config",e.config),s=e._preRequestSystemClockOffset,o=ZE(i,a.systemClockOffset);(o!==a.systemClockOffset||s!==void 0&&s!==o)&&n.$metadata&&(a.systemClockOffset=o,n.$metadata.clockSkewCorrected=!0)}throw t}}successHandler(e,t){const n=KE(e);if(n){const i=rf("config",t.config);i.systemClockOffset=ZE(n,i.systemClockOffset)}}}class qH{format(e){const t=[];for(const a of Object.keys(e)){const s=kl(a);t.push(Uint8Array.from([s.byteLength]),s,this.formatHeaderValue(e[a]))}const n=new Uint8Array(t.reduce((a,s)=>a+s.byteLength,0));let i=0;for(const a of t)n.set(a,i),i+=a.byteLength;return n}formatHeaderValue(e){switch(e.type){case"boolean":return Uint8Array.from([e.value?0:1]);case"byte":return Uint8Array.from([2,e.value]);case"short":const t=new DataView(new ArrayBuffer(3));return t.setUint8(0,3),t.setInt16(1,e.value,!1),new Uint8Array(t.buffer);case"integer":const n=new DataView(new ArrayBuffer(5));return n.setUint8(0,4),n.setInt32(1,e.value,!1),new Uint8Array(n.buffer);case"long":const i=new Uint8Array(9);return i[0]=5,i.set(e.value.bytes,1),i;case"binary":const a=new DataView(new ArrayBuffer(3+e.value.byteLength));a.setUint8(0,6),a.setUint16(1,e.value.byteLength,!1);const s=new Uint8Array(a.buffer);return s.set(e.value,3),s;case"string":const o=kl(e.value),l=new DataView(new ArrayBuffer(3+o.byteLength));l.setUint8(0,7),l.setUint16(1,o.byteLength,!1);const u=new Uint8Array(l.buffer);return u.set(o,3),u;case"timestamp":const c=new Uint8Array(9);return c[0]=8,c.set(W1.fromNumber(e.value.valueOf()).bytes,1),c;case"uuid":if(!WH.test(e.value))throw new Error(`Invalid UUID received: ${e.value}`);const f=new Uint8Array(17);return f[0]=9,f.set(WI(e.value.replace(/\-/g,"")),1),f}}}var e2;(function(r){r[r.boolTrue=0]="boolTrue",r[r.boolFalse=1]="boolFalse",r[r.byte=2]="byte",r[r.short=3]="short",r[r.integer=4]="integer",r[r.long=5]="long",r[r.byteArray=6]="byteArray",r[r.string=7]="string",r[r.timestamp=8]="timestamp",r[r.uuid=9]="uuid"})(e2||(e2={}));const WH=/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/;class W1{bytes;constructor(e){if(this.bytes=e,e.byteLength!==8)throw new Error("Int64 buffers must be exactly 8 bytes")}static fromNumber(e){if(e>9223372036854776e3||e<-9223372036854776e3)throw new Error(`${e} is too large (or, if negative, too small) to represent as an Int64`);const t=new Uint8Array(8);for(let n=7,i=Math.abs(Math.round(e));n>-1&&i>0;n--,i/=256)t[n]=i;return e<0&&t2(t),new W1(t)}valueOf(){const e=this.bytes.slice(0),t=e[0]&128;return t&&t2(e),parseInt(Ao(e),16)*(t?-1:1)}toString(){return String(this.valueOf())}}function t2(r){for(let e=0;e<8;e++)r[e]^=255;for(let e=7;e>-1&&(r[e]++,r[e]===0);e--);}const QH="X-Amz-Algorithm",YH="X-Amz-Credential",hP="X-Amz-Date",XH="X-Amz-SignedHeaders",JH="X-Amz-Expires",pP="X-Amz-Signature",gP="X-Amz-Security-Token",mP="authorization",vP=hP.toLowerCase(),KH="date",ZH=[mP,vP,KH],ej=pP.toLowerCase(),xA="x-amz-content-sha256",tj=gP.toLowerCase(),rj={authorization:!0,"cache-control":!0,connection:!0,expect:!0,from:!0,"keep-alive":!0,"max-forwards":!0,pragma:!0,referer:!0,te:!0,trailer:!0,"transfer-encoding":!0,upgrade:!0,"user-agent":!0,"x-amzn-trace-id":!0},nj=/^proxy-/,ij=/^sec-/,Wv="AWS4-HMAC-SHA256",aj="AWS4-HMAC-SHA256-PAYLOAD",sj="UNSIGNED-PAYLOAD",oj=50,yP="aws4_request",lj=3600*24*7,uj=({query:r={}})=>{const e=[],t={};for(const n of Object.keys(r)){if(n.toLowerCase()===ej)continue;const i=Cl(n);e.push(i);const a=r[n];typeof a=="string"?t[i]=`${i}=${Cl(a)}`:Array.isArray(a)&&(t[i]=a.slice(0).reduce((s,o)=>s.concat([`${i}=${Cl(o)}`]),[]).sort().join("&"))}return e.sort().map(n=>t[n]).filter(n=>n).join("&")},cj=r=>dj(r).toISOString().replace(/\.\d{3}Z$/,"Z"),dj=r=>typeof r=="number"?new Date(r*1e3):typeof r=="string"?Number(r)?new Date(Number(r)*1e3):new Date(r):r;class fj{service;regionProvider;credentialProvider;sha256;uriEscapePath;applyChecksum;constructor({applyChecksum:e,credentials:t,region:n,service:i,sha256:a,uriEscapePath:s=!0}){this.service=i,this.sha256=a,this.uriEscapePath=s,this.applyChecksum=typeof e=="boolean"?e:!0,this.regionProvider=Bs(n),this.credentialProvider=Bs(t)}createCanonicalRequest(e,t,n){const i=Object.keys(t).sort();return`${e.method}
3044
3044
  ${this.getCanonicalPath(e)}
3045
3045
  ${uj(e)}
@@ -3053,7 +3053,7 @@ ${t}
3053
3053
  ${Ao(s)}`}getCanonicalPath({path:e}){if(this.uriEscapePath){const t=[];for(const a of e.split("/"))a?.length!==0&&a!=="."&&(a===".."?t.pop():t.push(a));const n=`${e?.startsWith("/")?"/":""}${t.join("/")}${t.length>0&&e?.endsWith("/")?"/":""}`;return Cl(n).replace(/%2F/g,"/")}return e}validateResolvedCredentials(e){if(typeof e!="object"||typeof e.accessKeyId!="string"||typeof e.secretAccessKey!="string")throw new Error("Resolved credential object is not valid")}formatDate(e){const t=cj(e).replace(/[\-:]/g,"");return{longDate:t,shortDate:t.slice(0,8)}}getCanonicalHeaderList(e){return Object.keys(e).sort().join(";")}}const Fp={},Qv=[],Yv=(r,e,t)=>`${r}/${e}/${t}/${yP}`,hj=async(r,e,t,n,i)=>{const a=await r2(r,e.secretAccessKey,e.accessKeyId),s=`${t}:${n}:${i}:${Ao(a)}:${e.sessionToken}`;if(s in Fp)return Fp[s];for(Qv.push(s);Qv.length>oj;)delete Fp[Qv.shift()];let o=`AWS4${e.secretAccessKey}`;for(const l of[t,n,i,yP])o=await r2(r,o,l);return Fp[s]=o},r2=(r,e,t)=>{const n=new r(e);return n.update(kf(t)),n.digest()},n2=({headers:r},e,t)=>{const n={};for(const i of Object.keys(r).sort()){if(r[i]==null)continue;const a=i.toLowerCase();(a in rj||e?.has(a)||nj.test(a)||ij.test(a))&&(!t||t&&!t.has(a))||(n[a]=r[i].trim().replace(/\s+/g," "))}return n},Xv=async({headers:r,body:e},t)=>{for(const n of Object.keys(r))if(n.toLowerCase()===xA)return r[n];if(e==null)return"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";if(typeof e=="string"||ArrayBuffer.isView(e)||xz(e)){const n=new t;return n.update(kf(e)),Ao(await n.digest())}return sj},pj=(r,e)=>{r=r.toLowerCase();for(const t of Object.keys(e))if(r===t.toLowerCase())return!0;return!1},gj=(r,e={})=>{const{headers:t,query:n={}}=na.clone(r);for(const i of Object.keys(t)){const a=i.toLowerCase();(a.slice(0,6)==="x-amz-"&&!e.unhoistableHeaders?.has(a)||e.hoistableHeaders?.has(a))&&(n[i]=t[i],delete t[i])}return{...r,headers:t,query:n}},i2=r=>{r=na.clone(r);for(const e of Object.keys(r.headers))ZH.indexOf(e.toLowerCase())>-1&&delete r.headers[e];return r};class a2 extends fj{headerFormatter=new qH;constructor({applyChecksum:e,credentials:t,region:n,service:i,sha256:a,uriEscapePath:s=!0}){super({applyChecksum:e,credentials:t,region:n,service:i,sha256:a,uriEscapePath:s})}async presign(e,t={}){const{signingDate:n=new Date,expiresIn:i=3600,unsignableHeaders:a,unhoistableHeaders:s,signableHeaders:o,hoistableHeaders:l,signingRegion:u,signingService:c}=t,f=await this.credentialProvider();this.validateResolvedCredentials(f);const d=u??await this.regionProvider(),{longDate:h,shortDate:g}=this.formatDate(n);if(i>lj)return Promise.reject("Signature version 4 presigned URLs must have an expiration date less than one week in the future");const v=Yv(g,d,c??this.service),y=gj(i2(e),{unhoistableHeaders:s,hoistableHeaders:l});f.sessionToken&&(y.query[gP]=f.sessionToken),y.query[QH]=Wv,y.query[YH]=`${f.accessKeyId}/${v}`,y.query[hP]=h,y.query[JH]=i.toString(10);const A=n2(y,a,o);return y.query[XH]=this.getCanonicalHeaderList(A),y.query[pP]=await this.getSignature(h,v,this.getSigningKey(f,d,g,c),this.createCanonicalRequest(y,A,await Xv(e,this.sha256))),y}async sign(e,t){return typeof e=="string"?this.signString(e,t):e.headers&&e.payload?this.signEvent(e,t):e.message?this.signMessage(e,t):this.signRequest(e,t)}async signEvent({headers:e,payload:t},{signingDate:n=new Date,priorSignature:i,signingRegion:a,signingService:s,eventStreamCredentials:o}){const l=a??await this.regionProvider(),{shortDate:u,longDate:c}=this.formatDate(n),f=Yv(u,l,s??this.service),d=await Xv({headers:{},body:t},this.sha256),h=new this.sha256;h.update(e);const g=Ao(await h.digest()),v=[aj,c,f,i,g,d].join(`
3054
3054
  `);return this.signString(v,{signingDate:n,signingRegion:l,signingService:s,eventStreamCredentials:o})}async signMessage(e,{signingDate:t=new Date,signingRegion:n,signingService:i,eventStreamCredentials:a}){return this.signEvent({headers:this.headerFormatter.format(e.message.headers),payload:e.message.body},{signingDate:t,signingRegion:n,signingService:i,priorSignature:e.priorSignature,eventStreamCredentials:a}).then(o=>({message:e.message,signature:o}))}async signString(e,{signingDate:t=new Date,signingRegion:n,signingService:i,eventStreamCredentials:a}={}){const s=a??await this.credentialProvider();this.validateResolvedCredentials(s);const o=n??await this.regionProvider(),{shortDate:l}=this.formatDate(t),u=new this.sha256(await this.getSigningKey(s,o,l,i));return u.update(kf(e)),Ao(await u.digest())}async signRequest(e,{signingDate:t=new Date,signableHeaders:n,unsignableHeaders:i,signingRegion:a,signingService:s}={}){const o=await this.credentialProvider();this.validateResolvedCredentials(o);const l=a??await this.regionProvider(),u=i2(e),{longDate:c,shortDate:f}=this.formatDate(t),d=Yv(f,l,s??this.service);u.headers[vP]=c,o.sessionToken&&(u.headers[tj]=o.sessionToken);const h=await Xv(u,this.sha256);!pj(xA,u.headers)&&this.applyChecksum&&(u.headers[xA]=h);const g=n2(u,i,n),v=await this.getSignature(c,d,this.getSigningKey(o,l,f,s),this.createCanonicalRequest(u,g,h));return u.headers[mP]=`${Wv} Credential=${o.accessKeyId}/${d}, SignedHeaders=${this.getCanonicalHeaderList(g)}, Signature=${v}`,u}async getSignature(e,t,n,i){const a=await this.createStringToSign(e,t,i,Wv),s=new this.sha256(await n);return s.update(kf(a)),Ao(await s.digest())}getSigningKey(e,t,n,i){return hj(this.sha256,e,n,t,i||this.service)}}const mj=r=>{let e=r.credentials,t=!!r.credentials,n;Object.defineProperty(r,"credentials",{set(u){u&&u!==e&&u!==n&&(t=!0),e=u;const c=vj(r,{credentials:e,credentialDefaultProvider:r.credentialDefaultProvider}),f=yj(r,c);if(t&&!f.attributed){const d=typeof e=="object"&&e!==null;n=async h=>{const v=await f(h);return d&&(!v.$source||Object.keys(v.$source).length===0)?kV(v,"CREDENTIALS_CODE","e"):v},n.memoized=f.memoized,n.configBound=f.configBound,n.attributed=!0}else n=f},get(){return n},enumerable:!0,configurable:!0}),r.credentials=e;const{signingEscapePath:i=!0,systemClockOffset:a=r.systemClockOffset||0,sha256:s}=r;let o;return r.signer?o=tf(r.signer):r.regionInfoProvider?o=()=>tf(r.region)().then(async u=>[await r.regionInfoProvider(u,{useFipsEndpoint:await r.useFipsEndpoint(),useDualstackEndpoint:await r.useDualstackEndpoint()})||{},u]).then(([u,c])=>{const{signingRegion:f,signingService:d}=u;r.signingRegion=r.signingRegion||f||c,r.signingName=r.signingName||d||r.serviceId;const h={...r,credentials:r.credentials,region:r.signingRegion,service:r.signingName,sha256:s,uriEscapePath:i},g=r.signerConstructor||a2;return new g(h)}):o=async u=>{u=Object.assign({},{name:"sigv4",signingName:r.signingName||r.defaultSigningName,signingRegion:await tf(r.region)(),properties:{}},u);const c=u.signingRegion,f=u.signingName;r.signingRegion=r.signingRegion||c,r.signingName=r.signingName||f||r.serviceId;const d={...r,credentials:r.credentials,region:r.signingRegion,service:r.signingName,sha256:s,uriEscapePath:i},h=r.signerConstructor||a2;return new h(d)},Object.assign(r,{systemClockOffset:a,signingEscapePath:i,signer:o})};function vj(r,{credentials:e,credentialDefaultProvider:t}){let n;return e?e?.memoized?n=e:n=hH(e,fH,lP):t?n=tf(t(Object.assign({},r,{parentClientConfig:r}))):n=async()=>{throw new Error("@aws-sdk/core::resolveAwsSdkSigV4Config - `credentials` not provided and no credentialDefaultProvider was configured.")},n.memoized=!0,n}function yj(r,e){if(e.configBound)return e;const t=async n=>e({...n,callerClientConfig:r});return t.memoized=e.memoized,t.configBound=!0,t}const Aj=async(r,e,t)=>({operation:vc(e).operation,region:await Bs(r.region)()||(()=>{throw new Error("expected `region` to be configured for `aws.auth#sigv4`")})()});function wj(r){return{schemeId:"aws.auth#sigv4",signingProperties:{name:"cognito-idp",region:r.region},propertiesExtractor:(e,t)=>({signingProperties:{config:e,context:t}})}}function Ur(r){return{schemeId:"smithy.api#noAuth"}}const bj=r=>{const e=[];switch(r.operation){case"AssociateSoftwareToken":{e.push(Ur());break}case"ChangePassword":{e.push(Ur());break}case"CompleteWebAuthnRegistration":{e.push(Ur());break}case"ConfirmDevice":{e.push(Ur());break}case"ConfirmForgotPassword":{e.push(Ur());break}case"ConfirmSignUp":{e.push(Ur());break}case"DeleteUser":{e.push(Ur());break}case"DeleteUserAttributes":{e.push(Ur());break}case"DeleteWebAuthnCredential":{e.push(Ur());break}case"ForgetDevice":{e.push(Ur());break}case"ForgotPassword":{e.push(Ur());break}case"GetDevice":{e.push(Ur());break}case"GetTokensFromRefreshToken":{e.push(Ur());break}case"GetUser":{e.push(Ur());break}case"GetUserAttributeVerificationCode":{e.push(Ur());break}case"GetUserAuthFactors":{e.push(Ur());break}case"GlobalSignOut":{e.push(Ur());break}case"InitiateAuth":{e.push(Ur());break}case"ListDevices":{e.push(Ur());break}case"ListWebAuthnCredentials":{e.push(Ur());break}case"ResendConfirmationCode":{e.push(Ur());break}case"RespondToAuthChallenge":{e.push(Ur());break}case"RevokeToken":{e.push(Ur());break}case"SetUserMFAPreference":{e.push(Ur());break}case"SetUserSettings":{e.push(Ur());break}case"SignUp":{e.push(Ur());break}case"StartWebAuthnRegistration":{e.push(Ur());break}case"UpdateAuthEventFeedback":{e.push(Ur());break}case"UpdateDeviceStatus":{e.push(Ur());break}case"UpdateUserAttributes":{e.push(Ur());break}case"VerifySoftwareToken":{e.push(Ur());break}case"VerifyUserAttribute":{e.push(Ur());break}default:e.push(wj(r))}return e},Cj=r=>{const e=mj(r);return Object.assign(e,{authSchemePreference:Bs(r.authSchemePreference??[])})},xj=r=>Object.assign(r,{useDualstackEndpoint:r.useDualstackEndpoint??!1,useFipsEndpoint:r.useFipsEndpoint??!1,defaultSigningName:"cognito-idp"}),AP={UseFIPS:{type:"builtInParams",name:"useFipsEndpoint"},Endpoint:{type:"builtInParams",name:"endpoint"},Region:{type:"builtInParams",name:"region"},UseDualStack:{type:"builtInParams",name:"useDualstackEndpoint"}},Sj="3.1075.0",Ej={version:Sj},kj=r=>new TextEncoder().encode(r);var Tj=typeof Buffer<"u"&&Buffer.from?function(r){return Buffer.from(r,"utf8")}:kj;function Tf(r){return r instanceof Uint8Array?r:typeof r=="string"?Tj(r):ArrayBuffer.isView(r)?new Uint8Array(r.buffer,r.byteOffset,r.byteLength/Uint8Array.BYTES_PER_ELEMENT):new Uint8Array(r)}function SA(r){return typeof r=="string"?r.length===0:r.byteLength===0}var wP={name:"SHA-256"},s2={name:"HMAC",hash:wP},Fj=new Uint8Array([227,176,196,66,152,252,28,20,154,251,244,200,153,111,185,36,39,174,65,228,100,155,147,76,164,149,153,27,120,82,184,85]);const Ij={};function Kp(){return typeof window<"u"?window:typeof self<"u"?self:Ij}var Pj=(function(){function r(e){this.toHash=new Uint8Array(0),this.secret=e,this.reset()}return r.prototype.update=function(e){if(!SA(e)){var t=Tf(e),n=new Uint8Array(this.toHash.byteLength+t.byteLength);n.set(this.toHash,0),n.set(t,this.toHash.byteLength),this.toHash=n}},r.prototype.digest=function(){var e=this;return this.key?this.key.then(function(t){return Kp().crypto.subtle.sign(s2,t,e.toHash).then(function(n){return new Uint8Array(n)})}):SA(this.toHash)?Promise.resolve(Fj):Promise.resolve().then(function(){return Kp().crypto.subtle.digest(wP,e.toHash)}).then(function(t){return Promise.resolve(new Uint8Array(t))})},r.prototype.reset=function(){var e=this;this.toHash=new Uint8Array(0),this.secret&&this.secret!==void 0&&(this.key=new Promise(function(t,n){Kp().crypto.subtle.importKey("raw",Tf(e.secret),s2,!1,["sign"]).then(t,n)}),this.key.catch(function(){}))},r})(),ha=64,Dj=32,Rj=new Uint32Array([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Oj=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],Bj=Math.pow(2,53)-1,Zp=(function(){function r(){this.state=Int32Array.from(Oj),this.temp=new Int32Array(64),this.buffer=new Uint8Array(64),this.bufferLength=0,this.bytesHashed=0,this.finished=!1}return r.prototype.update=function(e){if(this.finished)throw new Error("Attempted to update an already finished hash.");var t=0,n=e.byteLength;if(this.bytesHashed+=n,this.bytesHashed*8>Bj)throw new Error("Cannot hash more than 2^53 - 1 bits");for(;n>0;)this.buffer[this.bufferLength++]=e[t++],n--,this.bufferLength===ha&&(this.hashBuffer(),this.bufferLength=0)},r.prototype.digest=function(){if(!this.finished){var e=this.bytesHashed*8,t=new DataView(this.buffer.buffer,this.buffer.byteOffset,this.buffer.byteLength),n=this.bufferLength;if(t.setUint8(this.bufferLength++,128),n%ha>=ha-8){for(var i=this.bufferLength;i<ha;i++)t.setUint8(i,0);this.hashBuffer(),this.bufferLength=0}for(var i=this.bufferLength;i<ha-8;i++)t.setUint8(i,0);t.setUint32(ha-8,Math.floor(e/4294967296),!0),t.setUint32(ha-4,e),this.hashBuffer(),this.finished=!0}for(var a=new Uint8Array(Dj),i=0;i<8;i++)a[i*4]=this.state[i]>>>24&255,a[i*4+1]=this.state[i]>>>16&255,a[i*4+2]=this.state[i]>>>8&255,a[i*4+3]=this.state[i]>>>0&255;return a},r.prototype.hashBuffer=function(){for(var e=this,t=e.buffer,n=e.state,i=n[0],a=n[1],s=n[2],o=n[3],l=n[4],u=n[5],c=n[6],f=n[7],d=0;d<ha;d++){if(d<16)this.temp[d]=(t[d*4]&255)<<24|(t[d*4+1]&255)<<16|(t[d*4+2]&255)<<8|t[d*4+3]&255;else{var h=this.temp[d-2],g=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10;h=this.temp[d-15];var v=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3;this.temp[d]=(g+this.temp[d-7]|0)+(v+this.temp[d-16]|0)}var y=(((l>>>6|l<<26)^(l>>>11|l<<21)^(l>>>25|l<<7))+(l&u^~l&c)|0)+(f+(Rj[d]+this.temp[d]|0)|0)|0,A=((i>>>2|i<<30)^(i>>>13|i<<19)^(i>>>22|i<<10))+(i&a^i&s^a&s)|0;f=c,c=u,u=l,l=o+y|0,o=s,s=a,a=i,i=y+A|0}n[0]+=i,n[1]+=a,n[2]+=s,n[3]+=o,n[4]+=l,n[5]+=u,n[6]+=c,n[7]+=f},r})(),Mj=(function(){function r(e){this.secret=e,this.hash=new Zp,this.reset()}return r.prototype.update=function(e){if(!(SA(e)||this.error))try{this.hash.update(Tf(e))}catch(t){this.error=t}},r.prototype.digestSync=function(){if(this.error)throw this.error;return this.outer?(this.outer.finished||this.outer.update(this.hash.digest()),this.outer.digest()):this.hash.digest()},r.prototype.digest=function(){return es(this,void 0,void 0,function(){return ts(this,function(e){return[2,this.digestSync()]})})},r.prototype.reset=function(){if(this.hash=new Zp,this.secret){this.outer=new Zp;var e=_j(this.secret),t=new Uint8Array(ha);t.set(e);for(var n=0;n<ha;n++)e[n]^=54,t[n]^=92;this.hash.update(e),this.outer.update(t);for(var n=0;n<e.byteLength;n++)e[n]=0}},r})();function _j(r){var e=Tf(r);if(e.byteLength>ha){var t=new Zp;t.update(e),e=t.digest()}var n=new Uint8Array(ha);return n.set(e),n}var Nj=["decrypt","digest","encrypt","exportKey","generateKey","importKey","sign","verify"];function Lj(r){if(Uj(r)&&typeof r.crypto.subtle=="object"){var e=r.crypto.subtle;return Vj(e)}return!1}function Uj(r){if(typeof r=="object"&&typeof r.crypto=="object"){var e=r.crypto.getRandomValues;return typeof e=="function"}return!1}function Vj(r){return r&&Nj.every(function(e){return typeof r[e]=="function"})}var zj=(function(){function r(e){Lj(Kp())?this.hash=new Pj(e):this.hash=new Mj(e)}return r.prototype.update=function(e,t){this.hash.update(Tf(e))},r.prototype.digest=function(){return this.hash.digest()},r.prototype.reset=function(){this.hash.reset()},r})();function o2(r,e){return new Request(r,e)}function $j(r=0){return new Promise((e,t)=>{r&&setTimeout(()=>{const n=new Error(`Request did not complete within ${r} ms`);n.name="TimeoutError",t(n)},r)})}const Jv={supported:void 0};class Q1{config;configProvider;static create(e){return typeof e?.handle=="function"?e:new Q1(e)}constructor(e){typeof e=="function"?this.configProvider=e().then(t=>t||{}):(this.config=e??{},this.configProvider=Promise.resolve(this.config)),Jv.supported===void 0&&(Jv.supported=typeof Request<"u"&&"keepalive"in o2("https://[::1]"))}destroy(){}async handle(e,{abortSignal:t,requestTimeout:n}={}){this.config||(this.config=await this.configProvider);const i=n??this.config.requestTimeout,a=this.config.keepAlive===!0,s=this.config.credentials;if(t?.aborted){const C=l2(t);return Promise.reject(C)}let o=e.path;const l=v$(e.query||{});l&&(o+=`?${l}`),e.fragment&&(o+=`#${e.fragment}`);let u="";if(e.username!=null||e.password!=null){const C=e.username??"",S=e.password??"";u=`${C}:${S}@`}const{port:c,method:f}=e,d=`${e.protocol}//${u}${e.hostname}${c?`:${c}`:""}${o}`,h=f==="GET"||f==="HEAD"?void 0:e.body,g={body:h,headers:new Headers(e.headers),method:f,credentials:s};this.config?.cache&&(g.cache=this.config.cache),h&&(g.duplex="half"),typeof AbortController<"u"&&(g.signal=t),Jv.supported&&(g.keepalive=a),typeof this.config.requestInit=="function"&&Object.assign(g,this.config.requestInit(e));let v=()=>{};const y=o2(d,g),A=[fetch(y).then(C=>{const S=C.headers,F={};for(const R of S.entries())F[R[0]]=R[1];return C.body!=null?{response:new sc({headers:F,reason:C.statusText,statusCode:C.status,body:C.body})}:C.blob().then(R=>({response:new sc({headers:F,reason:C.statusText,statusCode:C.status,body:R})}))}),$j(i)];return t&&A.push(new Promise((C,S)=>{const F=()=>{const E=l2(t);S(E)};if(typeof t.addEventListener=="function"){const E=t;E.addEventListener("abort",F,{once:!0}),v=()=>E.removeEventListener("abort",F)}else t.onabort=F})),Promise.race(A).finally(v)}updateHttpClientConfig(e,t){this.config=void 0,this.configProvider=this.configProvider.then(n=>(n[e]=t,n))}httpHandlerConfigs(){return this.config??{}}}function l2(r){const e=r&&typeof r=="object"&&"reason"in r?r.reason:void 0;if(e){if(e instanceof Error){const i=new Error("Request aborted");return i.name="AbortError",i.cause=e,i}const n=new Error(String(e));return n.name="AbortError",n}const t=new Error("Request aborted");return t.name="AbortError",t}const Hj=async r=>typeof Blob=="function"&&r instanceof Blob||r.constructor?.name==="Blob"?Blob.prototype.arrayBuffer!==void 0?new Uint8Array(await r.arrayBuffer()):jj(r):Gj(r);async function jj(r){const e=await qj(r),t=Zg(e);return new Uint8Array(t)}async function Gj(r){const e=[],t=r.getReader();let n=!1,i=0;for(;!n;){const{done:o,value:l}=await t.read();l&&(e.push(l),i+=l.length),n=o}const a=new Uint8Array(i);let s=0;for(const o of e)a.set(o,s),s+=o.length;return a}function qj(r){return new Promise((e,t)=>{const n=new FileReader;n.onloadend=()=>{if(n.readyState!==2)return t(new Error("Reader aborted too early"));const i=n.result??"",a=i.indexOf(","),s=a>-1?a+1:i.length;e(i.substring(s))},n.onabort=()=>t(new Error("Read aborted")),n.onerror=()=>t(n.error),n.readAsDataURL(r)})}class Wj{queryCompat;errorRegistry;constructor(e=!1){this.queryCompat=e}resolveRestContentType(e,t){const n=t.getMemberSchemas(),i=Object.values(n).find(a=>!!a.getMergedTraits().httpPayload);if(i){const a=i.getMergedTraits().mediaType;return a||(i.isStringSchema()?"text/plain":i.isBlobSchema()?"application/octet-stream":e)}else if(!t.isUnitSchema()&&Object.values(n).find(s=>{const{httpQuery:o,httpQueryParams:l,httpHeader:u,httpLabel:c,httpPrefixHeaders:f}=s.getMergedTraits();return!o&&!l&&!u&&!c&&f===void 0}))return e}async getErrorSchemaOrThrowBaseException(e,t,n,i,a,s){let o=e;e.includes("#")&&([,o]=e.split("#"));const l={$metadata:a,$fault:n.statusCode<500?"client":"server"};if(!this.errorRegistry)throw new Error("@aws-sdk/core/protocols - error handler not initialized.");try{return{errorSchema:s?.(this.errorRegistry,o)??this.errorRegistry.getSchema(e),errorMetadata:l}}catch{i.message=i.message??i.Message??"UnknownError";const c=this.errorRegistry,f=c.getBaseException();if(f){const g=c.getErrorCtor(f)??Error;throw this.decorateServiceException(Object.assign(new g({name:o}),l),i)}const d=i,h=d?.message??d?.Message??d?.Error?.Message??d?.Error?.message;throw this.decorateServiceException(Object.assign(new Error(h),{name:o},l),i)}}compose(e,t,n){let i=n;t.includes("#")&&([i]=t.split("#"));const a=Zi.for(i),s=Zi.for("smithy.ts.sdk.synthetic."+n);e.copyFrom(a),e.copyFrom(s),this.errorRegistry=e}decorateServiceException(e,t={}){if(this.queryCompat){const n=e.Message??t.Message,i=_E(e,t);n&&(i.message=n);const a=i.Error??{};a.Type=i.Error?.Type,a.Code=i.Error?.Code,a.Message=i.Error?.message??i.Error?.Message??n,i.Error=a;const s=i.$metadata.requestId;return s&&(i.RequestId=s),i}return _E(e,t)}setQueryCompatError(e,t){const n=t.headers?.["x-amzn-query-error"];if(e!==void 0&&n!=null){const[i,a]=n.split(";"),s=Object.keys(e),o={Code:i,Type:a};e.Code=i,e.Type=a;for(let l=0;l<s.length;l++){const u=s[l];o[u==="message"?"Message":u]=e[u]}delete o.__type,e.Error=o}}queryCompatOutput(e,t){e.Error&&(t.Error=e.Error),e.Type&&(t.Type=e.Type),e.Code&&(t.Code=e.Code)}findQueryCompatibleError(e,t){try{return e.getSchema(t)}catch{return e.find(i=>vi.of(i).getMergedTraits().awsQueryError?.[0]===t)}}}class Y1{serdeContext;setSerdeContext(e){this.serdeContext=e}}class Qj{from;to;keys;constructor(e,t){this.from=e,this.to=t;const n=Object.keys(this.from),i=new Set(n);i.delete("__type"),this.keys=i}mark(e){this.keys.delete(e)}hasUnknown(){return this.keys.size===1&&Object.keys(this.to).length===0}writeUnknown(){if(this.hasUnknown()){const e=this.keys.values().next().value,t=this.from[e];this.to.$unknown=[e,t]}}}function Yj(r,e,t){if(t?.source){const n=t.source;if(typeof e=="number"&&(e>Number.MAX_SAFE_INTEGER||e<Number.MIN_SAFE_INTEGER||n!==String(e)))return n.includes(".")?new ns(n,"bigDecimal"):BigInt(n)}return e}const Xj=(r,e)=>bA(r,e).then(t=>(e?.utf8Encoder??em)(t)),Jj=(r,e)=>Xj(r,e).then(t=>{if(t.length)try{return JSON.parse(t)}catch(n){throw n?.name==="SyntaxError"&&Object.defineProperty(n,"$responseBodyText",{value:t}),n}return{}}),u2=(r,e)=>Object.keys(r).find(t=>t.toLowerCase()===e.toLowerCase()),Kv=r=>{let e=r;return typeof e=="number"&&(e=e.toString()),e.indexOf(",")>=0&&(e=e.split(",")[0]),e.indexOf(":")>=0&&(e=e.split(":")[0]),e.indexOf("#")>=0&&(e=e.split("#")[1]),e},Kj=(r,e,t=!1)=>Zj(r,e,t?["code","header","type"]:["type","code","header"]),Zj=({headers:r},e,t)=>{for(;t.length>0;)switch(t.shift()){case"header":const i=u2(r??{},"x-amzn-errortype");if(i!==void 0)return Kv(r[i]);break;case"code":const a=u2(e??{},"code");if(a&&e[a]!==void 0)return Kv(e[a]);break;case"type":if(e?.__type!==void 0)return Kv(e.__type);break}};class eG extends Y1{settings;constructor(e){super(),this.settings=e}async read(e,t){return this._read(e,typeof t=="string"?JSON.parse(t,Yj):await Jj(t,this.serdeContext))}readObject(e,t){return this._read(e,t)}_read(e,t){const n=t!==null&&typeof t=="object",i=vi.of(e);if(n){if(i.isStructSchema()){const s=t,o=i.isUnionSchema(),l={};let u;const{jsonName:c}=this.settings;c&&(u={});let f;o&&(f=new Qj(s,l));for(const[d,h]of i.structIterator()){let g=d;c&&(g=h.getMergedTraits().jsonName??g,u[g]=d),o&&f.mark(g),s[g]!=null&&(l[d]=this._read(h,s[g]))}if(o)f.writeUnknown();else if(typeof s.__type=="string")for(const d in s){const h=s[d],g=c?u[d]??d:d;g in l||(l[g]=h)}return l}if(Array.isArray(t)&&i.isListSchema()){const s=i.getValueSchema(),o=[];for(const l of t)o.push(this._read(s,l));return o}if(i.isMapSchema()){const s=i.getValueSchema(),o={};for(const l in t)o[l]=this._read(s,t[l]);return o}}if(i.isBlobSchema()&&typeof t=="string")return Zg(t);const a=i.getMergedTraits().mediaType;if(i.isStringSchema()&&typeof t=="string"&&a)return a==="application/json"||a.endsWith("+json")?po.from(t):t;if(i.isTimestampSchema()&&t!=null)switch(aP(i,this.settings)){case 5:return uz(t);case 6:return GI(t);case 7:return hz(t);default:return console.warn("Missing timestamp format, parsing value with Date constructor:",t),new Date(t)}if(i.isBigIntegerSchema()&&(typeof t=="number"||typeof t=="string"))return BigInt(t);if(i.isBigDecimalSchema()&&t!=null){if(t instanceof ns)return t;const s=t;return s.type==="bigDecimal"&&"string"in s?new ns(s.string,s.type):new ns(String(t),"bigDecimal")}if(i.isNumericSchema()&&typeof t=="string"){switch(t){case"Infinity":return 1/0;case"-Infinity":return-1/0;case"NaN":return NaN}return t}if(i.isDocumentSchema())if(n){const s=Array.isArray(t)?[]:{};for(const o in t){const l=t[o];l instanceof ns?s[o]=l:s[o]=this._read(i,l)}return s}else return structuredClone(t);return t}}const c2="Ν";class tG{values=new Map;counter=0;stage=0;createReplacer(){if(this.stage===1)throw new Error("@aws-sdk/core/protocols - JsonReplacer already created.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");return this.stage=1,(e,t)=>{if(t instanceof ns){const n=`${c2+"nv"+this.counter++}_`+t.string;return this.values.set(`"${n}"`,t.string),n}if(typeof t=="bigint"){const n=t.toString(),i=`${c2+"b"+this.counter++}_`+n;return this.values.set(`"${i}"`,n),i}return t}}replaceInJson(e){if(this.stage===0)throw new Error("@aws-sdk/core/protocols - JsonReplacer not created yet.");if(this.stage===2)throw new Error("@aws-sdk/core/protocols - JsonReplacer exhausted.");if(this.stage=2,this.counter===0)return e;for(const[t,n]of this.values)e=e.replace(t,n);return e}}class rG extends Y1{settings;buffer;useReplacer=!1;rootSchema;constructor(e){super(),this.settings=e}write(e,t){this.rootSchema=vi.of(e),this.buffer=this._write(this.rootSchema,t)}flush(){const{rootSchema:e,useReplacer:t}=this;if(this.rootSchema=void 0,this.useReplacer=!1,e?.isStructSchema()||e?.isDocumentSchema()){if(!t)return JSON.stringify(this.buffer);const n=new tG;return n.replaceInJson(JSON.stringify(this.buffer,n.createReplacer(),0))}return this.buffer}writeDiscriminatedDocument(e,t){this.write(e,t),typeof this.buffer=="object"&&(this.buffer.__type=vi.of(e).getName(!0))}_write(e,t,n){const i=t!==null&&typeof t=="object",a=vi.of(e);if(i){if(a.isStructSchema()){const s=t,o={},{jsonName:l}=this.settings;let u;l&&(u={});let c=0;for(const[f,d]of a.structIterator()){const h=this._write(d,s[f],a);if(h!==void 0){let g=f;l&&(g=d.getMergedTraits().jsonName??f,u[f]=g),o[g]=h,c++}}if(a.isUnionSchema()&&c===0){const{$unknown:f}=s;if(Array.isArray(f)){const[d,h]=f;o[d]=this._write(15,h)}}else if(typeof s.__type=="string")for(const f in s){const d=s[f],h=l?u[f]??f:f;h in o||(o[h]=this._write(15,d))}return o}if(Array.isArray(t)&&a.isListSchema()){const s=a.getValueSchema(),o=[],l=!!a.getMergedTraits().sparse;for(const u of t)(l||u!=null)&&o.push(this._write(s,u));return o}if(a.isMapSchema()){const s=a.getValueSchema(),o={},l=!!a.getMergedTraits().sparse;for(const u in t){const c=t[u];(l||c!=null)&&(o[u]=this._write(s,c))}return o}if(t instanceof Uint8Array&&(a.isBlobSchema()||a.isDocumentSchema()))return a===this.rootSchema?t:(this.serdeContext?.base64Encoder??Cg)(t);if(t instanceof Date&&(a.isTimestampSchema()||a.isDocumentSchema()))switch(aP(a,this.settings)){case 5:return t.toISOString().replace(".000Z","Z");case 6:return oz(t);case 7:return t.getTime()/1e3;default:return console.warn("Missing timestamp format, using epoch seconds",t),t.getTime()/1e3}t instanceof ns&&(this.useReplacer=!0)}if(!(t===null&&n?.isStructSchema())){if(a.isStringSchema()){if(typeof t>"u"&&a.isIdempotencyToken())return o$();const s=a.getMergedTraits().mediaType;return t!=null&&s&&(s==="application/json"||s.endsWith("+json"))?po.from(t):t}if(typeof t=="number"&&a.isNumericSchema())return Math.abs(t)===1/0||isNaN(t)?String(t):t;if(typeof t=="string"&&a.isBlobSchema())return a===this.rootSchema?t:(this.serdeContext?.base64Encoder??Cg)(t);if(typeof t=="bigint"&&(this.useReplacer=!0),a.isDocumentSchema())if(i){const s=Array.isArray(t)?[]:{};for(const o in t){const l=t[o];l instanceof ns?(this.useReplacer=!0,s[o]=l):s[o]=this._write(a,l)}return s}else return structuredClone(t);return t}}}class nG extends Y1{settings;constructor(e){super(),this.settings=e}createSerializer(){const e=new rG(this.settings);return e.setSerdeContext(this.serdeContext),e}createDeserializer(){const e=new eG(this.settings);return e.setSerdeContext(this.serdeContext),e}}class iG extends c${serializer;deserializer;serviceTarget;codec;mixin;awsQueryCompatible;constructor({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:n,awsQueryCompatible:i,jsonCodec:a}){super({defaultNamespace:e,errorTypeRegistries:t}),this.serviceTarget=n,this.codec=a??new nG({timestampFormat:{useTrait:!0,default:7},jsonName:!1}),this.serializer=this.codec.createSerializer(),this.deserializer=this.codec.createDeserializer(),this.awsQueryCompatible=!!i,this.mixin=new Wj(this.awsQueryCompatible)}async serializeRequest(e,t,n){const i=await super.serializeRequest(e,t,n);return i.path.endsWith("/")||(i.path+="/"),i.headers["content-type"]=`application/x-amz-json-${this.getJsonRpcVersion()}`,i.headers["x-amz-target"]=`${this.serviceTarget}.${e.name}`,this.awsQueryCompatible&&(i.headers["x-amzn-query-mode"]="true"),(Yp(e.input)==="unit"||!i.body)&&(i.body="{}"),i}getPayloadCodec(){return this.codec}async handleError(e,t,n,i,a){const{awsQueryCompatible:s}=this;s&&this.mixin.setQueryCompatError(i,n);const o=Kj(n,i,s)??"Unknown";this.mixin.compose(this.compositeErrorRegistry,o,this.options.defaultNamespace);const{errorSchema:l,errorMetadata:u}=await this.mixin.getErrorSchemaOrThrowBaseException(o,this.options.defaultNamespace,n,i,a,s?this.mixin.findQueryCompatibleError:void 0),c=vi.of(l),f=i.message??i.Message??"UnknownError",d=this.compositeErrorRegistry.getErrorCtor(l)??Error,h=new d({}),g={},v=this.codec.createDeserializer();for(const[y,A]of c.structIterator())i[y]!=null&&(g[y]=v.readObject(A,i[y]));throw s&&this.mixin.queryCompatOutput(i,g),this.mixin.decorateServiceException(Object.assign(h,u,{$fault:c.getMergedTraits().error,message:f},g),i)}}class aG extends iG{constructor({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:n,awsQueryCompatible:i,jsonCodec:a}){super({defaultNamespace:e,errorTypeRegistries:t,serviceTarget:n,awsQueryCompatible:i,jsonCodec:a})}getShapeId(){return"aws.protocols#awsJson1_1"}getJsonRpcVersion(){return"1.1"}getDefaultContentType(){return"application/x-amz-json-1.1"}}const Ff="ref",hl=-1,Ip=!0,d2="isSet",bP="PartitionResult",Pp="booleanEquals",Zv="getAttr",Fd="stringEquals",f2={[Ff]:"Endpoint"},ey={[Ff]:bP},$d={[Ff]:"Region"},Ya={},h2=[$d],p2={conditions:[[d2,[f2]],[d2,h2],["aws.partition",h2,bP],[Pp,[{[Ff]:"UseFIPS"},Ip]],[Pp,[{fn:Zv,argv:[ey,"supportsFIPS"]},Ip]],[Pp,[{[Ff]:"UseDualStack"},Ip]],[Pp,[{fn:Zv,argv:[ey,"supportsDualStack"]},Ip]],[Fd,[{fn:Zv,argv:[ey,"name"]},"aws"]],[Fd,[$d,"us-east-1"]],[Fd,[$d,"us-east-2"]],[Fd,[$d,"us-west-1"]],[Fd,[$d,"us-west-2"]]],results:[[hl],[hl,"Invalid Configuration: FIPS and custom endpoint are not supported"],[hl,"Invalid Configuration: Dualstack and custom endpoint are not supported"],[f2,Ya],["https://cognito-idp-fips.us-east-1.amazonaws.com",Ya],["https://cognito-idp-fips.us-east-2.amazonaws.com",Ya],["https://cognito-idp-fips.us-west-1.amazonaws.com",Ya],["https://cognito-idp-fips.us-west-2.amazonaws.com",Ya],["https://cognito-idp-fips.{Region}.{PartitionResult#dualStackDnsSuffix}",Ya],[hl,"FIPS and DualStack are enabled, but this partition does not support one or both"],["https://cognito-idp-fips.{Region}.{PartitionResult#dnsSuffix}",Ya],[hl,"FIPS is enabled but this partition does not support FIPS"],["https://cognito-idp.{Region}.amazonaws.com",Ya],["https://cognito-idp.{Region}.{PartitionResult#dualStackDnsSuffix}",Ya],[hl,"DualStack is enabled but this partition does not support DualStack"],["https://cognito-idp.{Region}.{PartitionResult#dnsSuffix}",Ya],[hl,"Invalid Configuration: Missing Region"]]},sG=2,pi=1e8,oG=new Int32Array([-1,1,-1,0,17,3,1,4,pi+16,2,5,pi+16,3,9,6,5,7,pi+15,6,8,pi+14,7,pi+12,pi+13,4,11,10,5,pi+9,pi+11,5,12,pi+10,6,13,pi+9,8,pi+4,14,9,pi+5,15,10,pi+6,16,11,pi+7,pi+8,3,pi+1,18,5,pi+2,pi+3]),lG=H1.from(oG,sG,p2.conditions,p2.results),uG=new Uz({size:50,params:["Endpoint","Region","UseDualStack","UseFIPS"]}),cG=(r,e={})=>uG.get(r,()=>i$(lG,{endpointParams:r,logger:e.logger}));j1.aws=cP;class Ct extends Lu{constructor(e){super(e),Object.setPrototypeOf(this,Ct.prototype)}}class X1 extends Ct{name="AccessDeniedException";$fault="client";constructor(e){super({name:"AccessDeniedException",$fault:"client",...e}),Object.setPrototypeOf(this,X1.prototype)}}class J1 extends Ct{name="InternalErrorException";$fault="server";constructor(e){super({name:"InternalErrorException",$fault:"server",...e}),Object.setPrototypeOf(this,J1.prototype)}}class K1 extends Ct{name="InvalidParameterException";$fault="client";reasonCode;constructor(e){super({name:"InvalidParameterException",$fault:"client",...e}),Object.setPrototypeOf(this,K1.prototype),this.reasonCode=e.reasonCode}}class Z1 extends Ct{name="NotAuthorizedException";$fault="client";constructor(e){super({name:"NotAuthorizedException",$fault:"client",...e}),Object.setPrototypeOf(this,Z1.prototype)}}class ew extends Ct{name="OperationNotEnabledException";$fault="client";constructor(e){super({name:"OperationNotEnabledException",$fault:"client",...e}),Object.setPrototypeOf(this,ew.prototype)}}class tw extends Ct{name="ResourceNotFoundException";$fault="client";constructor(e){super({name:"ResourceNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,tw.prototype)}}class rw extends Ct{name="TooManyRequestsException";$fault="client";constructor(e){super({name:"TooManyRequestsException",$fault:"client",...e}),Object.setPrototypeOf(this,rw.prototype)}}class nw extends Ct{name="UserImportInProgressException";$fault="client";constructor(e){super({name:"UserImportInProgressException",$fault:"client",...e}),Object.setPrototypeOf(this,nw.prototype)}}class iw extends Ct{name="InternalServerException";$fault="server";constructor(e){super({name:"InternalServerException",$fault:"server",...e}),Object.setPrototypeOf(this,iw.prototype)}}class aw extends Ct{name="LimitExceededException";$fault="client";constructor(e){super({name:"LimitExceededException",$fault:"client",...e}),Object.setPrototypeOf(this,aw.prototype)}}class sw extends Ct{name="UserNotFoundException";$fault="client";constructor(e){super({name:"UserNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,sw.prototype)}}class ow extends Ct{name="InvalidLambdaResponseException";$fault="client";constructor(e){super({name:"InvalidLambdaResponseException",$fault:"client",...e}),Object.setPrototypeOf(this,ow.prototype)}}class lw extends Ct{name="TooManyFailedAttemptsException";$fault="client";constructor(e){super({name:"TooManyFailedAttemptsException",$fault:"client",...e}),Object.setPrototypeOf(this,lw.prototype)}}class uw extends Ct{name="UnexpectedLambdaException";$fault="client";constructor(e){super({name:"UnexpectedLambdaException",$fault:"client",...e}),Object.setPrototypeOf(this,uw.prototype)}}class cw extends Ct{name="UserLambdaValidationException";$fault="client";constructor(e){super({name:"UserLambdaValidationException",$fault:"client",...e}),Object.setPrototypeOf(this,cw.prototype)}}class dw extends Ct{name="CodeDeliveryFailureException";$fault="client";constructor(e){super({name:"CodeDeliveryFailureException",$fault:"client",...e}),Object.setPrototypeOf(this,dw.prototype)}}class fw extends Ct{name="InvalidPasswordException";$fault="client";constructor(e){super({name:"InvalidPasswordException",$fault:"client",...e}),Object.setPrototypeOf(this,fw.prototype)}}class hw extends Ct{name="InvalidSmsRoleAccessPolicyException";$fault="client";constructor(e){super({name:"InvalidSmsRoleAccessPolicyException",$fault:"client",...e}),Object.setPrototypeOf(this,hw.prototype)}}class pw extends Ct{name="InvalidSmsRoleTrustRelationshipException";$fault="client";constructor(e){super({name:"InvalidSmsRoleTrustRelationshipException",$fault:"client",...e}),Object.setPrototypeOf(this,pw.prototype)}}class gw extends Ct{name="PreconditionNotMetException";$fault="client";constructor(e){super({name:"PreconditionNotMetException",$fault:"client",...e}),Object.setPrototypeOf(this,gw.prototype)}}class mw extends Ct{name="UnsupportedUserStateException";$fault="client";constructor(e){super({name:"UnsupportedUserStateException",$fault:"client",...e}),Object.setPrototypeOf(this,mw.prototype)}}class vw extends Ct{name="UsernameExistsException";$fault="client";constructor(e){super({name:"UsernameExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,vw.prototype)}}class yw extends Ct{name="AliasExistsException";$fault="client";constructor(e){super({name:"AliasExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,yw.prototype)}}class Aw extends Ct{name="InvalidUserPoolConfigurationException";$fault="client";constructor(e){super({name:"InvalidUserPoolConfigurationException",$fault:"client",...e}),Object.setPrototypeOf(this,Aw.prototype)}}class ww extends Ct{name="InvalidEmailRoleAccessPolicyException";$fault="client";constructor(e){super({name:"InvalidEmailRoleAccessPolicyException",$fault:"client",...e}),Object.setPrototypeOf(this,ww.prototype)}}class bw extends Ct{name="MFAMethodNotFoundException";$fault="client";constructor(e){super({name:"MFAMethodNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,bw.prototype)}}class Cw extends Ct{name="PasswordResetRequiredException";$fault="client";constructor(e){super({name:"PasswordResetRequiredException",$fault:"client",...e}),Object.setPrototypeOf(this,Cw.prototype)}}class xw extends Ct{name="UnsupportedOperationException";$fault="client";constructor(e){super({name:"UnsupportedOperationException",$fault:"client",...e}),Object.setPrototypeOf(this,xw.prototype)}}class Sw extends Ct{name="UserNotConfirmedException";$fault="client";constructor(e){super({name:"UserNotConfirmedException",$fault:"client",...e}),Object.setPrototypeOf(this,Sw.prototype)}}class Ew extends Ct{name="UserPoolAddOnNotEnabledException";$fault="client";constructor(e){super({name:"UserPoolAddOnNotEnabledException",$fault:"client",...e}),Object.setPrototypeOf(this,Ew.prototype)}}class kw extends Ct{name="CodeMismatchException";$fault="client";constructor(e){super({name:"CodeMismatchException",$fault:"client",...e}),Object.setPrototypeOf(this,kw.prototype)}}class Tw extends Ct{name="ExpiredCodeException";$fault="client";constructor(e){super({name:"ExpiredCodeException",$fault:"client",...e}),Object.setPrototypeOf(this,Tw.prototype)}}class Fw extends Ct{name="PasswordHistoryPolicyViolationException";$fault="client";constructor(e){super({name:"PasswordHistoryPolicyViolationException",$fault:"client",...e}),Object.setPrototypeOf(this,Fw.prototype)}}class Iw extends Ct{name="SoftwareTokenMFANotFoundException";$fault="client";constructor(e){super({name:"SoftwareTokenMFANotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,Iw.prototype)}}class Pw extends Ct{name="ConcurrentModificationException";$fault="client";constructor(e){super({name:"ConcurrentModificationException",$fault:"client",...e}),Object.setPrototypeOf(this,Pw.prototype)}}class Dw extends Ct{name="ForbiddenException";$fault="client";constructor(e){super({name:"ForbiddenException",$fault:"client",...e}),Object.setPrototypeOf(this,Dw.prototype)}}class Rw extends Ct{name="WebAuthnChallengeNotFoundException";$fault="client";constructor(e){super({name:"WebAuthnChallengeNotFoundException",$fault:"client",...e}),Object.setPrototypeOf(this,Rw.prototype)}}class Ow extends Ct{name="WebAuthnClientMismatchException";$fault="client";constructor(e){super({name:"WebAuthnClientMismatchException",$fault:"client",...e}),Object.setPrototypeOf(this,Ow.prototype)}}class Bw extends Ct{name="WebAuthnCredentialNotSupportedException";$fault="client";constructor(e){super({name:"WebAuthnCredentialNotSupportedException",$fault:"client",...e}),Object.setPrototypeOf(this,Bw.prototype)}}class Mw extends Ct{name="WebAuthnNotEnabledException";$fault="client";constructor(e){super({name:"WebAuthnNotEnabledException",$fault:"client",...e}),Object.setPrototypeOf(this,Mw.prototype)}}class _w extends Ct{name="WebAuthnOriginNotAllowedException";$fault="client";constructor(e){super({name:"WebAuthnOriginNotAllowedException",$fault:"client",...e}),Object.setPrototypeOf(this,_w.prototype)}}class Nw extends Ct{name="WebAuthnRelyingPartyMismatchException";$fault="client";constructor(e){super({name:"WebAuthnRelyingPartyMismatchException",$fault:"client",...e}),Object.setPrototypeOf(this,Nw.prototype)}}class Lw extends Ct{name="DeviceKeyExistsException";$fault="client";constructor(e){super({name:"DeviceKeyExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,Lw.prototype)}}class Uw extends Ct{name="GroupExistsException";$fault="client";constructor(e){super({name:"GroupExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,Uw.prototype)}}class Vw extends Ct{name="DuplicateProviderException";$fault="client";constructor(e){super({name:"DuplicateProviderException",$fault:"client",...e}),Object.setPrototypeOf(this,Vw.prototype)}}class zw extends Ct{name="ManagedLoginBrandingExistsException";$fault="client";constructor(e){super({name:"ManagedLoginBrandingExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,zw.prototype)}}class $w extends Ct{name="TermsExistsException";$fault="client";constructor(e){super({name:"TermsExistsException",$fault:"client",...e}),Object.setPrototypeOf(this,$w.prototype)}}class Hw extends Ct{name="FeatureUnavailableInTierException";$fault="client";constructor(e){super({name:"FeatureUnavailableInTierException",$fault:"client",...e}),Object.setPrototypeOf(this,Hw.prototype)}}class jw extends Ct{name="TierChangeNotAllowedException";$fault="client";constructor(e){super({name:"TierChangeNotAllowedException",$fault:"client",...e}),Object.setPrototypeOf(this,jw.prototype)}}class Gw extends Ct{name="UserPoolTaggingException";$fault="client";constructor(e){super({name:"UserPoolTaggingException",$fault:"client",...e}),Object.setPrototypeOf(this,Gw.prototype)}}class qw extends Ct{name="InvalidOAuthFlowException";$fault="client";constructor(e){super({name:"InvalidOAuthFlowException",$fault:"client",...e}),Object.setPrototypeOf(this,qw.prototype)}}class Ww extends Ct{name="ScopeDoesNotExistException";$fault="client";constructor(e){super({name:"ScopeDoesNotExistException",$fault:"client",...e}),Object.setPrototypeOf(this,Ww.prototype)}}class Qw extends Ct{name="UnsupportedIdentityProviderException";$fault="client";constructor(e){super({name:"UnsupportedIdentityProviderException",$fault:"client",...e}),Object.setPrototypeOf(this,Qw.prototype)}}class Yw extends Ct{name="RefreshTokenReuseException";$fault="client";constructor(e){super({name:"RefreshTokenReuseException",$fault:"client",...e}),Object.setPrototypeOf(this,Yw.prototype)}}class Xw extends Ct{name="UnauthorizedException";$fault="client";constructor(e){super({name:"UnauthorizedException",$fault:"client",...e}),Object.setPrototypeOf(this,Xw.prototype)}}class Jw extends Ct{name="UnsupportedTokenTypeException";$fault="client";constructor(e){super({name:"UnsupportedTokenTypeException",$fault:"client",...e}),Object.setPrototypeOf(this,Jw.prototype)}}class Kw extends Ct{name="WebAuthnConfigurationMissingException";$fault="client";constructor(e){super({name:"WebAuthnConfigurationMissingException",$fault:"client",...e}),Object.setPrototypeOf(this,Kw.prototype)}}class Zw extends Ct{name="EnableSoftwareTokenMFAException";$fault="client";constructor(e){super({name:"EnableSoftwareTokenMFAException",$fault:"client",...e}),Object.setPrototypeOf(this,Zw.prototype)}}const dG="AvailableChallenges",fG="AccessDeniedException",hG="AliasExistsException",pG="AnalyticsEndpointId",gG="AuthFlow",CP="AnalyticsMetadata",mG="AnalyticsMetadataType",vG="AuthParameters",yG="AuthParametersType",xP="AuthenticationResult",AG="AuthenticationResultType",wG="AccessToken",bG="CodeDeliveryFailureException",SP="ClientId",CG="ClientIdType",EP="ClientMetadata",xG="CodeMismatchException",SG="ConcurrentModificationException",eb="ChallengeName",kP="ChallengeParameters",EG="ChallengeResponses",kG="ChallengeResponsesType",TG="DeviceGroupKey",FG="DeviceKey",IG="DeviceKeyExistsException",PG="DuplicateProviderException",DG="ExpiredCodeException",RG="EncodedData",OG="ExpiresIn",BG="EnableSoftwareTokenMFAException",MG="ForbiddenException",_G="FeatureUnavailableInTierException",NG="GroupExistsException",LG="IpAddress",UG="InitiateAuthRequest",VG="InitiateAuthResponse",zG="InitiateAuth",$G="InternalErrorException",HG="InvalidEmailRoleAccessPolicyException",jG="InvalidLambdaResponseException",GG="InvalidOAuthFlowException",qG="InvalidParameterException",WG="InvalidPasswordException",QG="InternalServerException",YG="InvalidSmsRoleAccessPolicyException",XG="InvalidSmsRoleTrustRelationshipException",JG="IdToken",KG="InvalidUserPoolConfigurationException",ZG="LimitExceededException",eq="MFAMethodNotFoundException",tq="ManagedLoginBrandingExistsException",rq="NotAuthorizedException",nq="NewDeviceMetadata",iq="NewDeviceMetadataType",aq="OperationNotEnabledException",sq="PasswordHistoryPolicyViolationException",oq="PreconditionNotMetException",lq="PasswordResetRequiredException",uq="ResourceNotFoundException",cq="RefreshToken",dq="RespondToAuthChallenge",fq="RespondToAuthChallengeRequest",hq="RespondToAuthChallengeResponse",pq="RefreshTokenReuseException",nm="Session",gq="ScopeDoesNotExistException",mq="SessionType",vq="SoftwareTokenMFANotFoundException",yq="TierChangeNotAllowedException",Aq="TermsExistsException",wq="TooManyFailedAttemptsException",bq="TooManyRequestsException",Cq="TokenModelType",xq="TokenType",Sq="UserContextDataType",TP="UserContextData",Eq="UnauthorizedException",kq="UsernameExistsException",Tq="UserImportInProgressException",Fq="UnsupportedIdentityProviderException",Iq="UnexpectedLambdaException",Pq="UserLambdaValidationException",Dq="UserNotConfirmedException",Rq="UserNotFoundException",Oq="UnsupportedOperationException",Bq="UserPoolAddOnNotEnabledException",Mq="UserPoolTaggingException",_q="UnsupportedTokenTypeException",Nq="UnsupportedUserStateException",Lq="WebAuthnClientMismatchException",Uq="WebAuthnConfigurationMissingException",Vq="WebAuthnChallengeNotFoundException",zq="WebAuthnCredentialNotSupportedException",$q="WebAuthnNotEnabledException",Hq="WebAuthnOriginNotAllowedException",jq="WebAuthnRelyingPartyMismatchException",It="client",Tt="error",Pt="httpError",Ft="message",Gq="reasonCode",FP="smithy.ts.sdk.synthetic.com.amazonaws.cognitoidentityprovider",IP="server",at="com.amazonaws.cognitoidentityprovider",PP=Zi.for(FP);var qq=[-3,FP,"CognitoIdentityProviderServiceException",0,[],[]];PP.registerError(qq,Ct);const kt=Zi.for(at);var Wq=[-3,at,fG,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(Wq,X1);var Qq=[-3,at,hG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Qq,yw);var Yq=[-3,at,bG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Yq,dw);var Xq=[-3,at,xG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Xq,kw);var Jq=[-3,at,SG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Jq,Pw);var Kq=[-3,at,IG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Kq,Lw);var Zq=[-3,at,PG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(Zq,Vw);var eW=[-3,at,BG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(eW,Zw);var tW=[-3,at,DG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(tW,Tw);var rW=[-3,at,_G,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(rW,Hw);var nW=[-3,at,MG,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(nW,Dw);var iW=[-3,at,NG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(iW,Uw);var aW=[-3,at,$G,{[Tt]:IP},[Ft],[0]];kt.registerError(aW,J1);var sW=[-3,at,QG,{[Tt]:IP},[Ft],[0]];kt.registerError(sW,iw);var oW=[-3,at,HG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(oW,ww);var lW=[-3,at,jG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(lW,ow);var uW=[-3,at,GG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(uW,qw);var cW=[-3,at,qG,{[Tt]:It,[Pt]:400},[Ft,Gq],[0,0]];kt.registerError(cW,K1);var dW=[-3,at,WG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(dW,fw);var fW=[-3,at,YG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(fW,hw);var hW=[-3,at,XG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(hW,pw);var pW=[-3,at,KG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(pW,Aw);var gW=[-3,at,ZG,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(gW,aw);var mW=[-3,at,tq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(mW,zw);var vW=[-3,at,eq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(vW,bw);var yW=[-3,at,rq,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(yW,Z1);var AW=[-3,at,aq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(AW,ew);var wW=[-3,at,sq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(wW,Fw);var bW=[-3,at,lq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(bW,Cw);var CW=[-3,at,oq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(CW,gw);var xW=[-3,at,pq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(xW,Yw);var SW=[-3,at,uq,{[Tt]:It,[Pt]:404},[Ft],[0]];kt.registerError(SW,tw);var EW=[-3,at,gq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(EW,Ww);var kW=[-3,at,vq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(kW,Iw);var TW=[-3,at,Aq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(TW,$w);var FW=[-3,at,yq,{[Tt]:It,[Pt]:403},[Ft],[0]];kt.registerError(FW,jw);var IW=[-3,at,wq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(IW,lw);var PW=[-3,at,bq,{[Tt]:It,[Pt]:429},[Ft],[0]];kt.registerError(PW,rw);var DW=[-3,at,Eq,{[Tt]:It,[Pt]:401},[Ft],[0]];kt.registerError(DW,Xw);var RW=[-3,at,Iq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(RW,uw);var OW=[-3,at,Fq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(OW,Qw);var BW=[-3,at,Oq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(BW,xw);var MW=[-3,at,_q,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(MW,Jw);var _W=[-3,at,Nq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(_W,mw);var NW=[-3,at,Tq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(NW,nw);var LW=[-3,at,Pq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(LW,cw);var UW=[-3,at,kq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(UW,vw);var VW=[-3,at,Dq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(VW,Sw);var zW=[-3,at,Rq,{[Tt]:It,[Pt]:404},[Ft],[0]];kt.registerError(zW,sw);var $W=[-3,at,Bq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError($W,Ew);var HW=[-3,at,Mq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(HW,Gw);var jW=[-3,at,Vq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(jW,Rw);var GW=[-3,at,Lq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(GW,Ow);var qW=[-3,at,Uq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(qW,Kw);var WW=[-3,at,zq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(WW,Bw);var QW=[-3,at,$q,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(QW,Mw);var YW=[-3,at,Hq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(YW,_w);var XW=[-3,at,jq,{[Tt]:It,[Pt]:400},[Ft],[0]];kt.registerError(XW,Nw);const JW=[PP,kt];var DP=[0,at,CG,8,0],im=[0,at,mq,8,0],ty=[0,at,Cq,8,0],RP=[3,at,mG,0,[pG],[0]],OP=[3,at,AG,0,[wG,OG,xq,cq,JG,nq],[[()=>ty,0],1,0,[()=>ty,0],[()=>ty,0],()=>eQ]],KW=[3,at,UG,0,[gG,SP,vG,EP,CP,TP,nm],[0,[()=>DP,0],[()=>nQ,0],128,()=>RP,[()=>BP,0],[()=>im,0]],2],ZW=[3,at,VG,0,[eb,nm,kP,xP,dG],[0,[()=>im,0],128,[()=>OP,0],64]],eQ=[3,at,iq,0,[FG,TG],[0,0]],tQ=[3,at,fq,0,[SP,eb,nm,EG,CP,TP,EP],[[()=>DP,0],0,[()=>im,0],[()=>iQ,0],()=>RP,[()=>BP,0],128],2],rQ=[3,at,hq,0,[eb,nm,kP,xP],[0,[()=>im,0],128,[()=>OP,0]]],BP=[3,at,Sq,8,[LG,RG],[0,0]],nQ=[2,at,yG,8,0,0],iQ=[2,at,kG,8,0,0],aQ=[9,at,zG,0,()=>KW,()=>ZW],sQ=[9,at,dq,0,()=>tQ,()=>rQ];const oQ=r=>({apiVersion:"2016-04-18",base64Decoder:r?.base64Decoder??Zg,base64Encoder:r?.base64Encoder??Cg,disableHostPrefix:r?.disableHostPrefix??!1,endpointProvider:r?.endpointProvider??cG,extensions:r?.extensions??[],httpAuthSchemeProvider:r?.httpAuthSchemeProvider??bj,httpAuthSchemes:r?.httpAuthSchemes??[{schemeId:"aws.auth#sigv4",identityProvider:e=>e.getIdentityProvider("aws.auth#sigv4"),signer:new GH},{schemeId:"smithy.api#noAuth",identityProvider:e=>e.getIdentityProvider("smithy.api#noAuth")||(async()=>({})),signer:new uH}],logger:r?.logger??new $I,protocol:r?.protocol??aG,protocolSettings:r?.protocolSettings??{defaultNamespace:"com.amazonaws.cognitoidentityprovider",errorTypeRegistries:JW,xmlNamespace:"http://cognito-idp.amazonaws.com/doc/2016-04-18/",version:"2016-04-18",serviceTarget:"AWSCognitoIdentityProviderService"},serviceId:r?.serviceId??"Cognito Identity Provider",urlParser:r?.urlParser??bg,utf8Decoder:r?.utf8Decoder??kl,utf8Encoder:r?.utf8Encoder??em}),lQ=r=>{const e=NH(r),t=()=>e().then(VV),n=oQ(r);return{...n,...r,runtime:"browser",defaultsMode:e,bodyLengthChecker:r?.bodyLengthChecker??Cz,credentialDefaultProvider:r?.credentialDefaultProvider??(i=>()=>Promise.reject(new Error("Credential is missing"))),defaultUserAgentProvider:r?.defaultUserAgentProvider??IH({serviceId:n.serviceId,clientVersion:Ej.version}),maxAttempts:r?.maxAttempts??ef,region:r?.region??DV("Region is missing"),requestHandler:Q1.create(r?.requestHandler??t),retryMode:r?.retryMode??(async()=>(await t()).retryMode||z$),sha256:r?.sha256??zj,streamCollector:r?.streamCollector??Hj,useDualstackEndpoint:r?.useDualstackEndpoint??(()=>Promise.resolve(UH)),useFipsEndpoint:r?.useFipsEndpoint??(()=>Promise.resolve(VH))}},uQ=r=>{const e=r.httpAuthSchemes;let t=r.httpAuthSchemeProvider,n=r.credentials;return{setHttpAuthScheme(i){const a=e.findIndex(s=>s.schemeId===i.schemeId);a===-1?e.push(i):e.splice(a,1,i)},httpAuthSchemes(){return e},setHttpAuthSchemeProvider(i){t=i},httpAuthSchemeProvider(){return t},setCredentials(i){n=i},credentials(){return n}}},cQ=r=>({httpAuthSchemes:r.httpAuthSchemes(),httpAuthSchemeProvider:r.httpAuthSchemeProvider(),credentials:r.credentials()}),dQ=(r,e)=>{const t=Object.assign(zH(r),GV(r),d$(r),uQ(r));return e.forEach(n=>n.configure(t)),Object.assign(r,$H(t),qV(t),f$(t),cQ(t))};class fQ extends RV{config;constructor(...[e]){const t=lQ(e||{});super(t),this.initConfig=t;const n=xj(t),i=mH(n),a=H$(i),s=MH(a),o=s,l=a$(o),u=Cj(l),c=dQ(u,e?.extensions||[]);this.config=c,this.middlewareStack.use(NV(this.config)),this.middlewareStack.use(FH(this.config)),this.middlewareStack.use(j$(this.config)),this.middlewareStack.use(g$(this.config)),this.middlewareStack.use(W$(this.config)),this.middlewareStack.use(X$(this.config)),this.middlewareStack.use(J$(this.config)),this.middlewareStack.use(rH(this.config,{httpAuthSchemeParametersProvider:Aj,identityProviderConfigProvider:async f=>new lH({"aws.auth#sigv4":f.credentials})})),this.middlewareStack.use(oH(this.config))}destroy(){super.destroy()}}class g2 extends z1.classBuilder().ep(AP).m(function(e,t,n,i){return[nP(n,e.getEndpointParameterInstructions())]}).s("AWSCognitoIdentityProviderService","InitiateAuth",{}).n("CognitoIdentityProviderClient","InitiateAuthCommand").sc(aQ).build(){}class hQ extends z1.classBuilder().ep(AP).m(function(e,t,n,i){return[nP(n,e.getEndpointParameterInstructions())]}).s("AWSCognitoIdentityProviderService","RespondToAuthChallenge",{}).n("CognitoIdentityProviderClient","RespondToAuthChallengeCommand").sc(sQ).build(){}class pQ{init(e,t,n){this.cognitoClient=new fQ({region:t}),this.spiffRegion=e,this.userPoolClientId=n}async generateCode(e){const t=await this.cognitoClient?.send(new g2({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:e}}));t?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=t.Session)}async verifyCode(e,t,n){const i=await this.cognitoClient?.send(new hQ({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:e,ANSWER:t},ClientMetadata:{partnerId:n,environment:(this.spiffRegion||"").toLowerCase()}}));return i?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=i.Session),i}async refreshTokens(){const e=localStorage.getItem("cognito-tokens");if(!e)throw new Error("Failed to find existing tokens.");const t=JSON.parse(e);return await this.cognitoClient?.send(new g2({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:t.RefreshToken||""}}))}}const Id=new pQ;var gQ={defaultAmount:0,defaultCurrency:"USD",defaultPrecision:2},mQ={globalLocale:"en-US",globalFormat:"$0,0.00",globalRoundingMode:"HALF_EVEN",globalFormatRoundingMode:"HALF_AWAY_FROM_ZERO",globalExchangeRatesApi:{endpoint:void 0,headers:void 0,propertyPath:void 0}};function nf(r){"@babel/helpers - typeof";return typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?nf=function(e){return typeof e}:nf=function(e){return e&&typeof Symbol=="function"&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},nf(r)}function m2(r){return vQ(r)||yQ(r)||AQ(r)||wQ()}function vQ(r){if(Array.isArray(r))return r}function yQ(r){if(typeof Symbol<"u"&&Symbol.iterator in Object(r))return Array.from(r)}function AQ(r,e){if(r){if(typeof r=="string")return v2(r,e);var t=Object.prototype.toString.call(r).slice(8,-1);if(t==="Object"&&r.constructor&&(t=r.constructor.name),t==="Map"||t==="Set")return Array.from(r);if(t==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t))return v2(r,e)}}function v2(r,e){(e==null||e>r.length)&&(e=r.length);for(var t=0,n=new Array(e);t<e;t++)n[t]=r[t];return n}function wQ(){throw new TypeError(`Invalid attempt to destructure non-iterable instance.
3055
3055
  In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}var bQ={normalizePrecision:function(e){var t=e.reduce(function(n,i){return Math.max(n.getPrecision(),i.getPrecision())});return e.map(function(n){return n.getPrecision()!==t?n.convertPrecision(t):n})},minimum:function(e){var t=m2(e),n=t[0],i=t.slice(1),a=n;return i.forEach(function(s){a=a.lessThan(s)?a:s}),a},maximum:function(e){var t=m2(e),n=t[0],i=t.slice(1),a=n;return i.forEach(function(s){a=a.greaterThan(s)?a:s}),a}};function MP(r){return!isNaN(parseInt(r))&&isFinite(r)}function CQ(r){return MP(r)&&r<=100&&r>=0}function xQ(r){return r.length>0&&r.every(function(e){return e>=0})&&r.some(function(e){return e>0})}function y2(r){return r%2===0}function A2(r){return MP(r)&&!Number.isInteger(r)}function SQ(){var r=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0,e=r.toString();if(e.indexOf("e-")>0)return parseInt(e.split("e-")[1]);var t=e.split(".")[1];return t?t.length:0}function Pd(r){return Math.abs(r)%1===.5}function EQ(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return new Promise(function(t,n){var i=Object.assign(new XMLHttpRequest,{onreadystatechange:function(){i.readyState===4&&(i.status>=200&&i.status<400?t(JSON.parse(i.responseText)):n(new Error(i.statusText)))},onerror:function(){n(new Error("Network error"))}});i.open("GET",r,!0),kQ(i,e.headers),i.send()})}function kQ(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};for(var t in e)r.setRequestHeader(t,e[t]);return r}function Hd(r){return typeof r>"u"}function _P(r){var e=arguments.length>1&&arguments[1]!==void 0?arguments[1]:".",t={};return Object.entries(r).forEach(function(n){if(nf(n[1])==="object"){var i=_P(n[1]);Object.entries(i).forEach(function(a){t[n[0]+e+a[0]]=a[1]})}else t[n[0]]=n[1]}),t}function TQ(r){return!!r&&(nf(r)==="object"||typeof r=="function")&&typeof r.then=="function"}function NP(){var r=function(n,i){var a=function(l){return Math.pow(10,SQ(l))},s=Math.max(a(n),a(i));return Math.round(n*s)*Math.round(i*s)/(s*s)},e={HALF_ODD:function(n){var i=Math.round(n);return Pd(n)&&y2(i)?i-1:i},HALF_EVEN:function(n){var i=Math.round(n);return Pd(n)?y2(i)?i:i-1:i},HALF_UP:function(n){return Math.round(n)},HALF_DOWN:function(n){return Pd(n)?Math.floor(n):Math.round(n)},HALF_TOWARDS_ZERO:function(n){return Pd(n)?Math.sign(n)*Math.floor(Math.abs(n)):Math.round(n)},HALF_AWAY_FROM_ZERO:function(n){return Pd(n)?Math.sign(n)*Math.ceil(Math.abs(n)):Math.round(n)},DOWN:function(n){return Math.floor(n)}};return{add:function(n,i){return n+i},subtract:function(n,i){return n-i},multiply:function(n,i){return A2(n)||A2(i)?r(n,i):n*i},divide:function(n,i){return n/i},modulo:function(n,i){return n%i},round:function(n){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:"HALF_EVEN";return e[i](n)}}}var FQ=NP();function IQ(r){var e=/^(?:(\$|USD)?0(?:(,)0)?(\.)?(0+)?|0(?:(,)0)?(\.)?(0+)?\s?(dollar)?)$/gm.exec(r);return{getMatches:function(){return e!==null?e.slice(1).filter(function(n){return!Hd(n)}):[]},getMinimumFractionDigits:function(){var n=function(a){return a==="."};return Hd(this.getMatches().find(n))?0:this.getMatches()[FQ.add(this.getMatches().findIndex(n),1)].split("").length},getCurrencyDisplay:function(){var n={USD:"code",dollar:"name",$:"symbol"};return n[this.getMatches().find(function(i){return i==="USD"||i==="dollar"||i==="$"})]},getStyle:function(){return Hd(this.getCurrencyDisplay(this.getMatches()))?"decimal":"currency"},getUseGrouping:function(){return!Hd(this.getMatches().find(function(n){return n===","}))}}}function PQ(r){var e=function(){var i=arguments.length>0&&arguments[0]!==void 0?arguments[0]:"",a=arguments.length>1?arguments[1]:void 0;for(var s in a)i=i.replace("{{".concat(s,"}}"),a[s]);return i},t=function(i,a){return EQ(e(r.endpoint,{from:i,to:a}),{headers:r.headers})};return{getExchangeRate:function(i,a){return(TQ(r.endpoint)?r.endpoint:t(i,a)).then(function(s){return _P(s)[e(r.propertyPath,{from:i,to:a})]})}}}function If(r,e){var t=arguments.length>2&&arguments[2]!==void 0?arguments[2]:Error;if(!r)throw new t(e)}function DQ(r){If(CQ(r),"You must provide a numeric value between 0 and 100.",RangeError)}function RQ(r){If(xQ(r),"You must provide a non-empty array of numeric values greater than 0.",TypeError)}function ry(r){If(Number.isInteger(r),"You must provide an integer.",TypeError)}var Tn=NP(),OQ=function r(e){var t=Object.assign({},{amount:r.defaultAmount,currency:r.defaultCurrency,precision:r.defaultPrecision},e),n=t.amount,i=t.currency,a=t.precision;ry(n),ry(a);var s=r.globalLocale,o=r.globalFormat,l=r.globalRoundingMode,u=r.globalFormatRoundingMode,c=Object.assign({},r.globalExchangeRatesApi),f=function(g){var v=Object.assign({},Object.assign({},{amount:n,currency:i,precision:a},g),Object.assign({},{locale:this.locale},g));return Object.assign(r({amount:v.amount,currency:v.currency,precision:v.precision}),{locale:v.locale})},d=function(g){If(this.hasSameCurrency(g),"You must provide a Dinero instance with the same currency.",TypeError)};return{getAmount:function(){return n},getCurrency:function(){return i},getLocale:function(){return this.locale||s},setLocale:function(g){return f.call(this,{locale:g})},getPrecision:function(){return a},convertPrecision:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u;ry(g);var y=this.getPrecision(),A=g>y,C=A?Tn.multiply:Tn.divide,S=A?[g,y]:[y,g],F=Math.pow(10,Tn.subtract.apply(Tn,S));return f.call(this,{amount:Tn.round(C(this.getAmount(),F),v),precision:g})},add:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return f.call(this,{amount:Tn.add(v[0].getAmount(),v[1].getAmount()),precision:v[0].getPrecision()})},subtract:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return f.call(this,{amount:Tn.subtract(v[0].getAmount(),v[1].getAmount()),precision:v[0].getPrecision()})},multiply:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return f.call(this,{amount:Tn.round(Tn.multiply(this.getAmount(),g),v)})},divide:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return f.call(this,{amount:Tn.round(Tn.divide(this.getAmount(),g),v)})},percentage:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:l;return DQ(g),this.multiply(Tn.divide(g,100),v)},allocate:function(g){var v=this;RQ(g);for(var y=g.reduce(function(F,E){return Tn.add(F,E)}),A=this.getAmount(),C=g.map(function(F){var E=Math.floor(Tn.divide(Tn.multiply(v.getAmount(),F),y));return A=Tn.subtract(A,E),f.call(v,{amount:E})}),S=0;A>0;)g[S]>0&&(C[S]=C[S].add(f.call(this,{amount:1})),A=Tn.subtract(A,1)),S+=1;return C},convert:function(g){var v=this,y=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},A=y.endpoint,C=A===void 0?c.endpoint:A,S=y.propertyPath,F=S===void 0?c.propertyPath||"rates.{{to}}":S,E=y.headers,R=E===void 0?c.headers:E,B=y.roundingMode,j=B===void 0?l:B,G=Object.assign({},{endpoint:C,propertyPath:F,headers:R,roundingMode:j});return PQ(G).getExchangeRate(this.getCurrency(),g).then(function(ie){return If(!Hd(ie),'No rate was found for the destination currency "'.concat(g,'".'),TypeError),f.call(v,{amount:Tn.round(Tn.multiply(v.getAmount(),parseFloat(ie)),G.roundingMode),currency:g})})},equalsTo:function(g){return this.hasSameAmount(g)&&this.hasSameCurrency(g)},lessThan:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()<v[1].getAmount()},lessThanOrEqual:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()<=v[1].getAmount()},greaterThan:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()>v[1].getAmount()},greaterThanOrEqual:function(g){d.call(this,g);var v=r.normalizePrecision([this,g]);return v[0].getAmount()>=v[1].getAmount()},isZero:function(){return this.getAmount()===0},isPositive:function(){return this.getAmount()>=0},isNegative:function(){return this.getAmount()<0},hasSubUnits:function(){return Tn.modulo(this.getAmount(),Math.pow(10,a))!==0},hasCents:function(){return Tn.modulo(this.getAmount(),Math.pow(10,a))!==0},hasSameCurrency:function(g){return this.getCurrency()===g.getCurrency()},hasSameAmount:function(g){var v=r.normalizePrecision([this,g]);return v[0].getAmount()===v[1].getAmount()},toFormat:function(){var g=arguments.length>0&&arguments[0]!==void 0?arguments[0]:o,v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u,y=IQ(g);return this.toRoundedUnit(y.getMinimumFractionDigits(),v).toLocaleString(this.getLocale(),{currencyDisplay:y.getCurrencyDisplay(),useGrouping:y.getUseGrouping(),minimumFractionDigits:y.getMinimumFractionDigits(),style:y.getStyle(),currency:this.getCurrency()})},toUnit:function(){return Tn.divide(this.getAmount(),Math.pow(10,a))},toRoundedUnit:function(g){var v=arguments.length>1&&arguments[1]!==void 0?arguments[1]:u,y=Math.pow(10,g);return Tn.divide(Tn.round(Tn.multiply(this.toUnit(),y),v),y)},toObject:function(){return{amount:n,currency:i,precision:a}},toJSON:function(){return this.toObject()}}},BQ=Object.assign(OQ,gQ,mQ,bQ),Xa={},ny,w2;function MQ(){if(w2)return ny;w2=1;function r(t){return t}function e(t,a,s){for(var a=a||r,s=s||t,o=0,l=t.length;o<l;o+=1)if(a.call(s,t[o],o))return t[o]}return ny=e,ny}var iy={exports:{}},b2;function _Q(){if(b2)return iy.exports;b2=1;var r=iy.exports=function(e,t){if(typeof e=="function"||t)return r.by(e,t);for(var n={object:[],function:[],string:{},number:{},boolean:{},undefined:{}},i=[],a=0;a<e.length;a++){var s=e[a],o=s==="__proto__"?n.objects:n[typeof s]||n.objects;Array.isArray(o)?o.indexOf(s)<0&&(o.push(s),i.push(s)):Object.hasOwnProperty.call(o,s)||(o[s]=!0,i.push(s))}return i};return r.by=function(e,t){if(typeof e=="function"){var n=t;t=e,e=n}for(var i=[],a=0;a<e.length;a++){for(var s=e[a],o=!1,l=0;l<i.length;l++){var u=i[l];if(t.call(i,s,u)){o=!0;break}}o||i.push(s)}return i},iy.exports}var ay,C2;function NQ(){return C2||(C2=1,ay=[{code:"AED",number:"784",digits:2,currency:"UAE Dirham",countries:["United Arab Emirates (The)"]},{code:"AFN",number:"971",digits:2,currency:"Afghani",countries:["Afghanistan"]},{code:"ALL",number:"008",digits:2,currency:"Lek",countries:["Albania"]},{code:"AMD",number:"051",digits:2,currency:"Armenian Dram",countries:["Armenia"]},{code:"ANG",number:"532",digits:2,currency:"Netherlands Antillean Guilder",countries:["Curaçao","Sint Maarten (Dutch Part)"]},{code:"AOA",number:"973",digits:2,currency:"Kwanza",countries:["Angola"]},{code:"ARS",number:"032",digits:2,currency:"Argentine Peso",countries:["Argentina"]},{code:"AUD",number:"036",digits:2,currency:"Australian Dollar",countries:["Australia","Christmas Island","Cocos (Keeling) Islands (The)","Heard Island and Mcdonald Islands","Kiribati","Nauru","Norfolk Island","Tuvalu"]},{code:"AWG",number:"533",digits:2,currency:"Aruban Florin",countries:["Aruba"]},{code:"AZN",number:"944",digits:2,currency:"Azerbaijan Manat",countries:["Azerbaijan"]},{code:"BAM",number:"977",digits:2,currency:"Convertible Mark",countries:["Bosnia and Herzegovina"]},{code:"BBD",number:"052",digits:2,currency:"Barbados Dollar",countries:["Barbados"]},{code:"BDT",number:"050",digits:2,currency:"Taka",countries:["Bangladesh"]},{code:"BGN",number:"975",digits:2,currency:"Bulgarian Lev",countries:["Bulgaria"]},{code:"BHD",number:"048",digits:3,currency:"Bahraini Dinar",countries:["Bahrain"]},{code:"BIF",number:"108",digits:0,currency:"Burundi Franc",countries:["Burundi"]},{code:"BMD",number:"060",digits:2,currency:"Bermudian Dollar",countries:["Bermuda"]},{code:"BND",number:"096",digits:2,currency:"Brunei Dollar",countries:["Brunei Darussalam"]},{code:"BOB",number:"068",digits:2,currency:"Boliviano",countries:["Bolivia (Plurinational State Of)"]},{code:"BOV",number:"984",digits:2,currency:"Mvdol",countries:["Bolivia (Plurinational State Of)"]},{code:"BRL",number:"986",digits:2,currency:"Brazilian Real",countries:["Brazil"]},{code:"BSD",number:"044",digits:2,currency:"Bahamian Dollar",countries:["Bahamas (The)"]},{code:"BTN",number:"064",digits:2,currency:"Ngultrum",countries:["Bhutan"]},{code:"BWP",number:"072",digits:2,currency:"Pula",countries:["Botswana"]},{code:"BYN",number:"933",digits:2,currency:"Belarusian Ruble",countries:["Belarus"]},{code:"BZD",number:"084",digits:2,currency:"Belize Dollar",countries:["Belize"]},{code:"CAD",number:"124",digits:2,currency:"Canadian Dollar",countries:["Canada"]},{code:"CDF",number:"976",digits:2,currency:"Congolese Franc",countries:["Congo (The Democratic Republic of The)"]},{code:"CHE",number:"947",digits:2,currency:"WIR Euro",countries:["Switzerland"]},{code:"CHF",number:"756",digits:2,currency:"Swiss Franc",countries:["Liechtenstein","Switzerland"]},{code:"CHW",number:"948",digits:2,currency:"WIR Franc",countries:["Switzerland"]},{code:"CLF",number:"990",digits:4,currency:"Unidad de Fomento",countries:["Chile"]},{code:"CLP",number:"152",digits:0,currency:"Chilean Peso",countries:["Chile"]},{code:"CNY",number:"156",digits:2,currency:"Yuan Renminbi",countries:["China"]},{code:"COP",number:"170",digits:2,currency:"Colombian Peso",countries:["Colombia"]},{code:"COU",number:"970",digits:2,currency:"Unidad de Valor Real",countries:["Colombia"]},{code:"CRC",number:"188",digits:2,currency:"Costa Rican Colon",countries:["Costa Rica"]},{code:"CUC",number:"931",digits:2,currency:"Peso Convertible",countries:["Cuba"]},{code:"CUP",number:"192",digits:2,currency:"Cuban Peso",countries:["Cuba"]},{code:"CVE",number:"132",digits:2,currency:"Cabo Verde Escudo",countries:["Cabo Verde"]},{code:"CZK",number:"203",digits:2,currency:"Czech Koruna",countries:["Czechia"]},{code:"DJF",number:"262",digits:0,currency:"Djibouti Franc",countries:["Djibouti"]},{code:"DKK",number:"208",digits:2,currency:"Danish Krone",countries:["Denmark","Faroe Islands (The)","Greenland"]},{code:"DOP",number:"214",digits:2,currency:"Dominican Peso",countries:["Dominican Republic (The)"]},{code:"DZD",number:"012",digits:2,currency:"Algerian Dinar",countries:["Algeria"]},{code:"EGP",number:"818",digits:2,currency:"Egyptian Pound",countries:["Egypt"]},{code:"ERN",number:"232",digits:2,currency:"Nakfa",countries:["Eritrea"]},{code:"ETB",number:"230",digits:2,currency:"Ethiopian Birr",countries:["Ethiopia"]},{code:"EUR",number:"978",digits:2,currency:"Euro",countries:["Åland Islands","Andorra","Austria","Belgium","Croatia","Cyprus","Estonia","European Union","Finland","France","French Guiana","French Southern Territories (The)","Germany","Greece","Guadeloupe","Holy See (The)","Ireland","Italy","Latvia","Lithuania","Luxembourg","Malta","Martinique","Mayotte","Monaco","Montenegro","Netherlands (The)","Portugal","Réunion","Saint Barthélemy","Saint Martin (French Part)","Saint Pierre and Miquelon","San Marino","Slovakia","Slovenia","Spain"]},{code:"FJD",number:"242",digits:2,currency:"Fiji Dollar",countries:["Fiji"]},{code:"FKP",number:"238",digits:2,currency:"Falkland Islands Pound",countries:["Falkland Islands (The) [Malvinas]"]},{code:"GBP",number:"826",digits:2,currency:"Pound Sterling",countries:["Guernsey","Isle of Man","Jersey","United Kingdom of Great Britain and Northern Ireland (The)"]},{code:"GEL",number:"981",digits:2,currency:"Lari",countries:["Georgia"]},{code:"GHS",number:"936",digits:2,currency:"Ghana Cedi",countries:["Ghana"]},{code:"GIP",number:"292",digits:2,currency:"Gibraltar Pound",countries:["Gibraltar"]},{code:"GMD",number:"270",digits:2,currency:"Dalasi",countries:["Gambia (The)"]},{code:"GNF",number:"324",digits:0,currency:"Guinean Franc",countries:["Guinea"]},{code:"GTQ",number:"320",digits:2,currency:"Quetzal",countries:["Guatemala"]},{code:"GYD",number:"328",digits:2,currency:"Guyana Dollar",countries:["Guyana"]},{code:"HKD",number:"344",digits:2,currency:"Hong Kong Dollar",countries:["Hong Kong"]},{code:"HNL",number:"340",digits:2,currency:"Lempira",countries:["Honduras"]},{code:"HTG",number:"332",digits:2,currency:"Gourde",countries:["Haiti"]},{code:"HUF",number:"348",digits:2,currency:"Forint",countries:["Hungary"]},{code:"IDR",number:"360",digits:2,currency:"Rupiah",countries:["Indonesia"]},{code:"ILS",number:"376",digits:2,currency:"New Israeli Sheqel",countries:["Israel"]},{code:"INR",number:"356",digits:2,currency:"Indian Rupee",countries:["Bhutan","India"]},{code:"IQD",number:"368",digits:3,currency:"Iraqi Dinar",countries:["Iraq"]},{code:"IRR",number:"364",digits:2,currency:"Iranian Rial",countries:["Iran (Islamic Republic Of)"]},{code:"ISK",number:"352",digits:0,currency:"Iceland Krona",countries:["Iceland"]},{code:"JMD",number:"388",digits:2,currency:"Jamaican Dollar",countries:["Jamaica"]},{code:"JOD",number:"400",digits:3,currency:"Jordanian Dinar",countries:["Jordan"]},{code:"JPY",number:"392",digits:0,currency:"Yen",countries:["Japan"]},{code:"KES",number:"404",digits:2,currency:"Kenyan Shilling",countries:["Kenya"]},{code:"KGS",number:"417",digits:2,currency:"Som",countries:["Kyrgyzstan"]},{code:"KHR",number:"116",digits:2,currency:"Riel",countries:["Cambodia"]},{code:"KMF",number:"174",digits:0,currency:"Comorian Franc ",countries:["Comoros (The)"]},{code:"KPW",number:"408",digits:2,currency:"North Korean Won",countries:["Korea (The Democratic People’s Republic Of)"]},{code:"KRW",number:"410",digits:0,currency:"Won",countries:["Korea (The Republic Of)"]},{code:"KWD",number:"414",digits:3,currency:"Kuwaiti Dinar",countries:["Kuwait"]},{code:"KYD",number:"136",digits:2,currency:"Cayman Islands Dollar",countries:["Cayman Islands (The)"]},{code:"KZT",number:"398",digits:2,currency:"Tenge",countries:["Kazakhstan"]},{code:"LAK",number:"418",digits:2,currency:"Lao Kip",countries:["Lao People’s Democratic Republic (The)"]},{code:"LBP",number:"422",digits:2,currency:"Lebanese Pound",countries:["Lebanon"]},{code:"LKR",number:"144",digits:2,currency:"Sri Lanka Rupee",countries:["Sri Lanka"]},{code:"LRD",number:"430",digits:2,currency:"Liberian Dollar",countries:["Liberia"]},{code:"LSL",number:"426",digits:2,currency:"Loti",countries:["Lesotho"]},{code:"LYD",number:"434",digits:3,currency:"Libyan Dinar",countries:["Libya"]},{code:"MAD",number:"504",digits:2,currency:"Moroccan Dirham",countries:["Morocco","Western Sahara"]},{code:"MDL",number:"498",digits:2,currency:"Moldovan Leu",countries:["Moldova (The Republic Of)"]},{code:"MGA",number:"969",digits:2,currency:"Malagasy Ariary",countries:["Madagascar"]},{code:"MKD",number:"807",digits:2,currency:"Denar",countries:["North Macedonia"]},{code:"MMK",number:"104",digits:2,currency:"Kyat",countries:["Myanmar"]},{code:"MNT",number:"496",digits:2,currency:"Tugrik",countries:["Mongolia"]},{code:"MOP",number:"446",digits:2,currency:"Pataca",countries:["Macao"]},{code:"MRU",number:"929",digits:2,currency:"Ouguiya",countries:["Mauritania"]},{code:"MUR",number:"480",digits:2,currency:"Mauritius Rupee",countries:["Mauritius"]},{code:"MVR",number:"462",digits:2,currency:"Rufiyaa",countries:["Maldives"]},{code:"MWK",number:"454",digits:2,currency:"Malawi Kwacha",countries:["Malawi"]},{code:"MXN",number:"484",digits:2,currency:"Mexican Peso",countries:["Mexico"]},{code:"MXV",number:"979",digits:2,currency:"Mexican Unidad de Inversion (UDI)",countries:["Mexico"]},{code:"MYR",number:"458",digits:2,currency:"Malaysian Ringgit",countries:["Malaysia"]},{code:"MZN",number:"943",digits:2,currency:"Mozambique Metical",countries:["Mozambique"]},{code:"NAD",number:"516",digits:2,currency:"Namibia Dollar",countries:["Namibia"]},{code:"NGN",number:"566",digits:2,currency:"Naira",countries:["Nigeria"]},{code:"NIO",number:"558",digits:2,currency:"Cordoba Oro",countries:["Nicaragua"]},{code:"NOK",number:"578",digits:2,currency:"Norwegian Krone",countries:["Bouvet Island","Norway","Svalbard and Jan Mayen"]},{code:"NPR",number:"524",digits:2,currency:"Nepalese Rupee",countries:["Nepal"]},{code:"NZD",number:"554",digits:2,currency:"New Zealand Dollar",countries:["Cook Islands (The)","New Zealand","Niue","Pitcairn","Tokelau"]},{code:"OMR",number:"512",digits:3,currency:"Rial Omani",countries:["Oman"]},{code:"PAB",number:"590",digits:2,currency:"Balboa",countries:["Panama"]},{code:"PEN",number:"604",digits:2,currency:"Sol",countries:["Peru"]},{code:"PGK",number:"598",digits:2,currency:"Kina",countries:["Papua New Guinea"]},{code:"PHP",number:"608",digits:2,currency:"Philippine Peso",countries:["Philippines (The)"]},{code:"PKR",number:"586",digits:2,currency:"Pakistan Rupee",countries:["Pakistan"]},{code:"PLN",number:"985",digits:2,currency:"Zloty",countries:["Poland"]},{code:"PYG",number:"600",digits:0,currency:"Guarani",countries:["Paraguay"]},{code:"QAR",number:"634",digits:2,currency:"Qatari Rial",countries:["Qatar"]},{code:"RON",number:"946",digits:2,currency:"Romanian Leu",countries:["Romania"]},{code:"RSD",number:"941",digits:2,currency:"Serbian Dinar",countries:["Serbia"]},{code:"RUB",number:"643",digits:2,currency:"Russian Ruble",countries:["Russian Federation (The)"]},{code:"RWF",number:"646",digits:0,currency:"Rwanda Franc",countries:["Rwanda"]},{code:"SAR",number:"682",digits:2,currency:"Saudi Riyal",countries:["Saudi Arabia"]},{code:"SBD",number:"090",digits:2,currency:"Solomon Islands Dollar",countries:["Solomon Islands"]},{code:"SCR",number:"690",digits:2,currency:"Seychelles Rupee",countries:["Seychelles"]},{code:"SDG",number:"938",digits:2,currency:"Sudanese Pound",countries:["Sudan (The)"]},{code:"SEK",number:"752",digits:2,currency:"Swedish Krona",countries:["Sweden"]},{code:"SGD",number:"702",digits:2,currency:"Singapore Dollar",countries:["Singapore"]},{code:"SHP",number:"654",digits:2,currency:"Saint Helena Pound",countries:["Saint Helena, Ascension and Tristan Da Cunha"]},{code:"SLE",number:"925",digits:2,currency:"Leone",countries:["Sierra Leone"]},{code:"SOS",number:"706",digits:2,currency:"Somali Shilling",countries:["Somalia"]},{code:"SRD",number:"968",digits:2,currency:"Surinam Dollar",countries:["Suriname"]},{code:"SSP",number:"728",digits:2,currency:"South Sudanese Pound",countries:["South Sudan"]},{code:"STN",number:"930",digits:2,currency:"Dobra",countries:["Sao Tome and Principe"]},{code:"SVC",number:"222",digits:2,currency:"El Salvador Colon",countries:["El Salvador"]},{code:"SYP",number:"760",digits:2,currency:"Syrian Pound",countries:["Syrian Arab Republic"]},{code:"SZL",number:"748",digits:2,currency:"Lilangeni",countries:["Eswatini"]},{code:"THB",number:"764",digits:2,currency:"Baht",countries:["Thailand"]},{code:"TJS",number:"972",digits:2,currency:"Somoni",countries:["Tajikistan"]},{code:"TMT",number:"934",digits:2,currency:"Turkmenistan New Manat",countries:["Turkmenistan"]},{code:"TND",number:"788",digits:3,currency:"Tunisian Dinar",countries:["Tunisia"]},{code:"TOP",number:"776",digits:2,currency:"Pa’anga",countries:["Tonga"]},{code:"TRY",number:"949",digits:2,currency:"Turkish Lira",countries:["Türki̇ye"]},{code:"TTD",number:"780",digits:2,currency:"Trinidad and Tobago Dollar",countries:["Trinidad and Tobago"]},{code:"TWD",number:"901",digits:2,currency:"New Taiwan Dollar",countries:["Taiwan (Province of China)"]},{code:"TZS",number:"834",digits:2,currency:"Tanzanian Shilling",countries:["Tanzania, United Republic Of"]},{code:"UAH",number:"980",digits:2,currency:"Hryvnia",countries:["Ukraine"]},{code:"UGX",number:"800",digits:0,currency:"Uganda Shilling",countries:["Uganda"]},{code:"USD",number:"840",digits:2,currency:"US Dollar",countries:["American Samoa","Bonaire, Sint Eustatius and Saba","British Indian Ocean Territory (The)","Ecuador","El Salvador","Guam","Haiti","Marshall Islands (The)","Micronesia (Federated States Of)","Northern Mariana Islands (The)","Palau","Panama","Puerto Rico","Timor-Leste","Turks and Caicos Islands (The)","United States Minor Outlying Islands (The)","United States of America (The)","Virgin Islands (British)","Virgin Islands (u.s.)"]},{code:"USN",number:"997",digits:2,currency:"US Dollar (Next day)",countries:["United States of America (The)"]},{code:"UYI",number:"940",digits:0,currency:"Uruguay Peso en Unidades Indexadas (UI)",countries:["Uruguay"]},{code:"UYU",number:"858",digits:2,currency:"Peso Uruguayo",countries:["Uruguay"]},{code:"UYW",number:"927",digits:4,currency:"Unidad Previsional",countries:["Uruguay"]},{code:"UZS",number:"860",digits:2,currency:"Uzbekistan Sum",countries:["Uzbekistan"]},{code:"VED",number:"926",digits:2,currency:"Bolívar Soberano",countries:["Venezuela (Bolivarian Republic Of)"]},{code:"VES",number:"928",digits:2,currency:"Bolívar Soberano",countries:["Venezuela (Bolivarian Republic Of)"]},{code:"VND",number:"704",digits:0,currency:"Dong",countries:["Viet Nam"]},{code:"VUV",number:"548",digits:0,currency:"Vatu",countries:["Vanuatu"]},{code:"WST",number:"882",digits:2,currency:"Tala",countries:["Samoa"]},{code:"XAF",number:"950",digits:0,currency:"CFA Franc BEAC",countries:["Cameroon","Central African Republic (The)","Chad","Congo (The)","Equatorial Guinea","Gabon"]},{code:"XAG",number:"961",digits:0,currency:"Silver",countries:["Zz11_silver"]},{code:"XAU",number:"959",digits:0,currency:"Gold",countries:["Zz08_gold"]},{code:"XBA",number:"955",digits:0,currency:"Bond Markets Unit European Composite Unit (EURCO)",countries:["Zz01_bond Markets Unit European_eurco"]},{code:"XBB",number:"956",digits:0,currency:"Bond Markets Unit European Monetary Unit (E.M.U.-6)",countries:["Zz02_bond Markets Unit European_emu-6"]},{code:"XBC",number:"957",digits:0,currency:"Bond Markets Unit European Unit of Account 9 (E.U.A.-9)",countries:["Zz03_bond Markets Unit European_eua-9"]},{code:"XBD",number:"958",digits:0,currency:"Bond Markets Unit European Unit of Account 17 (E.U.A.-17)",countries:["Zz04_bond Markets Unit European_eua-17"]},{code:"XCD",number:"951",digits:2,currency:"East Caribbean Dollar",countries:["Anguilla","Antigua and Barbuda","Dominica","Grenada","Montserrat","Saint Kitts and Nevis","Saint Lucia","Saint Vincent and the Grenadines"]},{code:"XDR",number:"960",digits:0,currency:"SDR (Special Drawing Right)",countries:["International Monetary Fund (Imf) "]},{code:"XOF",number:"952",digits:0,currency:"CFA Franc BCEAO",countries:["Benin","Burkina Faso","Côte D'ivoire","Guinea-Bissau","Mali","Niger (The)","Senegal","Togo"]},{code:"XPD",number:"964",digits:0,currency:"Palladium",countries:["Zz09_palladium"]},{code:"XPF",number:"953",digits:0,currency:"CFP Franc",countries:["French Polynesia","New Caledonia","Wallis and Futuna"]},{code:"XPT",number:"962",digits:0,currency:"Platinum",countries:["Zz10_platinum"]},{code:"XSU",number:"994",digits:0,currency:"Sucre",countries:['Sistema Unitario De Compensacion Regional De Pagos "Sucre"']},{code:"XTS",number:"963",digits:0,currency:"Codes specifically reserved for testing purposes",countries:["Zz06_testing_code"]},{code:"XUA",number:"965",digits:0,currency:"ADB Unit of Account",countries:["Member Countries of the African Development Bank Group"]},{code:"XXX",number:"999",digits:0,currency:"The codes assigned for transactions where no currency is involved",countries:["Zz07_no_currency"]},{code:"YER",number:"886",digits:2,currency:"Yemeni Rial",countries:["Yemen"]},{code:"ZAR",number:"710",digits:2,currency:"Rand",countries:["Lesotho","Namibia","South Africa"]},{code:"ZMW",number:"967",digits:2,currency:"Zambian Kwacha",countries:["Zambia"]},{code:"ZWG",number:"924",digits:2,currency:"Zimbabwe Gold",countries:["Zimbabwe"]}]),ay}var sy,x2;function LQ(){return x2||(x2=1,sy="2024-06-25"),sy}var S2;function UQ(){if(S2)return Xa;S2=1;var r=MQ(),e=_Q(),t=NQ(),n=LQ(),i=function(c){return c=c.toUpperCase(),r(t,function(f){return f.code===c})},a=function(c){return c=c.toLowerCase(),t.filter(function(f){return(f.countries.map(function(d){return d.toLowerCase()})||[]).indexOf(c)>-1})},s=function(c){return r(t,function(f){return f.number===String(c)})},o=function(){return t.map(function(c){return c.code})},l=function(){var c=t.map(function(f){return f.number});return c.filter(function(f){if(f)return f})},u=function(){var c=t.filter(function(f){return f.countries}).map(function(f){return f.countries});return e(Array.prototype.concat.apply([],c))};return Xa.code=i,Xa.country=a,Xa.number=s,Xa.codes=o,Xa.numbers=l,Xa.countries=u,Xa.publishDate=n,Xa.data=t,Xa}var E2=UQ();class LP{formatCurrencyForDisplay(e,t){const n={amount:t||0,currency:e,precision:this.getPrecisionForCurrency(e)};return BQ(n).toFormat(this.getSpecialFormat(e))}getPrecisionForCurrency(e){const t=e,n=E2.code(t);return n?n.digits:2}getSpecialFormat(e){const t=e;if(E2.code(t)?.code==="CLP")return"USD0,0"}}const k2=new LP;class UP{constructor(e,t,n,i){this.presentmentCurrency=void 0,this.presentmentCurrency=i,this.partnerCurrency=n,this.rateFrom=e,this.rateTo=t}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(e){return this.conversionRequired()?Math.ceil(this.subunits(this.units(e,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):e}units(e,t){return e/Math.pow(10,k2.getPrecisionForCurrency(t))}subunits(e,t){return e*Math.pow(10,k2.getPrecisionForCurrency(t))}}const VQ=async(r,e)=>{const t=Y3(e?.assets?.metadata||!1),n={ids:r};console.log("[getWorkflowsInternal] Requesting workflows.",{url:`${ss.getServerUrl()}/graphql`,variables:JSON.stringify(n)}),console.log(`[getWorkflowsInternal] Query:
3056
- ${V2(t)}`);const i=await ze.getShadowGraphqlClient().query({query:t,errorPolicy:"all",variables:n,context:{logRequestHeaders:!0}});if(i.error)throw console.log("[getWorkflowsInternal] Response errored."),i.error;if(i.errors)throw i.errors.forEach(s=>console.error(s)),new Error("Unable to read workflows. Consult GraphQL errors.");if(!i.data.workflows||i.data.workflows.length!==r.length)throw new Error(`Unable to read workflows: ${i.errors??"Length mismatch in response"}`);const a=mo(i.data.workflows);return a.forEach(s=>{s.finalizeStepConfig||(s.finalizeStepConfig={}),s.finalizeStepConfig.termsMarkdown=s.finalizeStepConfig.termsMarkdown||s.partner.termsMarkdown}),a},zQ=async(r,e)=>{const n=(await e).find(i=>i.id===r);if(!n)throw new Error(`Workflow not found: ${r}`);return n},tb=async(r,e)=>{const t=r.map(o=>mf.get({id:o,options:e})),n=r.filter((o,l)=>t[l]===void 0);if(n.length===0)return Promise.all(t);const i=VQ(n,e),a=n.map(o=>mf.set({id:o,options:e},zQ(o,i))),s=t.filter(o=>o!==void 0);return await Promise.all(s.concat(a))},VP=async(r,e)=>(await tb([r],e))[0],zP=async r=>{const e=await ze.getShadowGraphqlClient().query({query:wT,variables:{ids:r},errorPolicy:"all",fetchPolicy:"no-cache"});return e.errors&&console.error(e.errors),e.data.integrationProducts||[]};class $Q{constructor(e){this.activeIntegration=void 0,this.updateTransactionState=async t=>{try{return ze.getShadowGraphqlClient().mutate({...t,mutation:B3})}catch(n){throw console.error(n),new lo("Critical - Unable to synchronize workflow state with server.")}},this.options=e,this.options.applicationKey&&Jk(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 44.5.5"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(e){ss.setHubUrl(e.hubUrl),ss.setServerUrl(e.serverUrl),ss.setServicesApiUrl(e.servicesApiUrl),this.marketplaceThemeInstallId=e.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=e.marketplaceThemeInstallConfigurationId,this.userPoolClientId=e.userPoolClientId,this.userPoolRegion=e.userPoolRegion,this.spiffRegion=e.spiffRegion,e.bearerAuthenticationToken&&Zk(e.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Id.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getVersion(){return"44.5.5"}getAssetManager(){return Ln}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!eB())throw new Error("Application key required to use Flow Service.");return new NI}async getCurrencyContext(e){const n=(await this.getIntegration()).partner.currencyCode,a=await ze.getShadowGraphqlClient().query({query:tM,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:n,to:e}}),{rateFrom:s,rateTo:o}=a.data.currencyConversion;return new UP(s,o,n,e)}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=$P(this.options.applicationKey),this.activeIntegration}async canUseAddon(e){try{return(await this.getIntegration()).partner.activeAddons?.includes(e)??!1}catch(t){return console.error(t),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(e){const t=br.getMap("transactionCustomerIds");t?.has(e)&&(t.delete(e),br.setMap("transactionCustomerIds",t))}async customerHasBundleTemplates(e){const i=(await ze.getShadowGraphqlClient().query({query:Bv,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;return i.id?i.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(e){const t=this.customer?.stakeholders?.find(n=>n.transaction?.id===e);if(t)return t.type}async getOrCreateCustomer(e){this.customer=void 0;const t=ze.getShadowGraphqlClient(),i=(await t.query({query:Bv,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;if(!i.id){const o=(await t.mutate({mutation:bV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:e}}})).data?.customerCreate;if(!o)throw new Error("Unable to create customer.");return this.storeCustomer(o),this.customer=o,{customer:o,isAuthenticated:!1}}this.storeCustomer(i);const a=await this.reloadLoggedInCustomer();return{customer:this.customer||i,isAuthenticated:a}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const e=localStorage.getItem("last-refreshed-cognito-tokens"),t=localStorage.getItem("cognito-tokens"),n=localStorage.getItem("cognito-email");if(!e||!t||!n)return!1;const i=JSON.parse(t),a=new Date().getTime()/1e3;if(!i.ExpiresIn||i.ExpiresIn<a-parseInt(e)){const u=await Id.refreshTokens();if(u?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),i.AccessToken=u.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(i));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=localStorage.getItem("customer-login-token");s&&p0(s);const l=(await ze.getShadowGraphqlClient().query({query:Bv,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:n}})).data.customer;return l.id?(this.customer=l,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(e){await ze.getShadowGraphqlClient().mutate({mutation:CV,variables:{emailAddress:e}}),await Id.generateCode(e)}async verifyCode(e,t){const n=(await this.getIntegration()).partner.id||"",i=await Id.verifyCode(e,t,n);if(i?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(i.AuthenticationResult)),localStorage.setItem("cognito-email",e);const s=(await ze.getShadowGraphqlClient().mutate({mutation:xV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e,verificationCode:t}})).data?.customerVerifyCode;if(!s?.id)throw new Error("Failed to get customer.");return this.customer=s,s.loginToken&&(localStorage.setItem("customer-login-token",s.loginToken),p0(s.loginToken)),!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),localStorage.removeItem("customer-login-token"),p0(""),this.clearCustomer()}async loggedInBearerToken(){const e=localStorage.getItem("last-refreshed-cognito-tokens"),t=localStorage.getItem("cognito-tokens");if(!e||!t)throw new Error("No token data in storage.");const n=JSON.parse(t),i=new Date().getTime()/1e3,a=!n?.AccessToken||vg(n.AccessToken);if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(e)||a){const s=await Id.refreshTokens();if(s?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!n.AccessToken)throw new Error("No bearer token in storage.");return n.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await ze.getShadowGraphqlClient().query({query:SV,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(e,t,n,i){const s=(await ze.getShadowGraphqlClient().mutate({mutation:s9(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:e,initialMetadata:t?Object.entries(t).map((c,f)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,activationId:i,test:n?.test},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!s?.id)throw new Error("Unable to create bundle");const o=br.getMap("bundlePartnerIds")||new Map;o.set(s.id,s.partner.id),br.setMap("bundlePartnerIds",o);const l=br.getMap("bundleOwnerIds")||new Map;l.set(s.id,s.bundleOwnerId),br.setMap("bundleOwnerIds",l);const u=new OE(this,s,void 0,void 0,s.bundleOwnerId,{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts});return await u.getInitializationPromise(),u}async getExistingBundle(e,t,n,i,a){const o=br.getMap("bundleOwnerIds")?.get(e),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const y=Object.entries(localStorage).find(([C,S])=>C.startsWith("CognitoIdentityServiceProvider")&&C.endsWith("idToken"))?.[0]||"",A=localStorage.getItem(y);A&&!vg(A)&&(l.Authorization=`Bearer ${A}`)}const u={bundleOwnerId:o,...l,...i?.graphql?.additionalHeaders},c=await ze.getShadowGraphqlClient().query({query:r9(i?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:e},fetchPolicy:"no-cache",context:{headers:u}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${e}`);const f=c.data?.bundles[0],d=br.getMap("bundlePartnerIds")||new Map;d.set(f.id,f.partner.id),br.setMap("bundlePartnerIds",d);const h=new OE(this,f,t,n,o,{additionalHeaders:i?.graphql?.additionalHeaders,eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:i?.readonly},a);return await h.getInitializationPromise(),h}async duplicateBundle(e,t,n,i){const s={...await GP(e),...i?.graphql?.additionalHeaders},l=(await ze.getShadowGraphqlClient().mutate({mutation:o9(),variables:{id:e,template:t,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:n,test:i?.test},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const u=br.getMap("bundlePartnerIds")||new Map;u.set(l.id,l.partner.id),br.setMap("bundlePartnerIds",u);const c=br.getMap("bundleOwnerIds")||new Map;return c.set(l.id,l.bundleOwnerId),br.setMap("bundleOwnerIds",c),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(e){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:t,...n}=e;return(await ze.getShadowGraphqlClient().query({query:y9(t??!1),variables:{...n,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const e=await ze.getShadowGraphqlClient().query({query:n9,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!e.data?.customers||e.data.customers.length===0)throw new Error("Unable to find customer.");const n=e.data.customers[0].bundleStakeholders||[],i=br.getMap("bundlePartnerIds")||new Map;return n.forEach(a=>{a.bundle?.id&&a.bundle.partner?.id&&i.set(a.bundle.id,a.bundle.partner.id)}),br.setMap("bundlePartnerIds",i),n}async getWorkflowExperience(e,t){if(!e)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const n=await this.getWorkflowExperiences([e],e.graphql),i=n[0],a=i.getWorkflow();return t&&!a&&console.error("No workflow instantiated when trying to create preview service."),t&&a&&await i.getWorkflowManager().injectIntoPreviewService(t(a)),n[0]}async getWorkflowExperiences(e,t,n,i){if(e.length===0)throw new lo("No options provided!");const a=e.map((q,Y)=>({option:q,index:Y})),s=a.filter(q=>q.option.type==="transaction"),o=a.filter(q=>q.option.type==="integration"||q.option.type==="external"||q.option.type==="blank"),l=50,u=hA(s,l),c=hA(o,l);let f=0;const d=ze.getShadowGraphqlClient(),h=async q=>{if(q.length===0)return[];const Y=q.map(oe=>oe.option.transactionId),J=await d.query({query:O3,variables:{ids:Y},errorPolicy:"all",fetchPolicy:"no-cache"}),ae=J.data.transactions;if(f=f+ae.length,i&&i(f,s.length),ae.length!==q.length){const oe=J.errors?.[0]?.message||"Unknown error";throw new lo(`Not all transactions were found: ${oe}`)}return!this.activeIntegration&&ae[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(ae[0].integrationProduct.integration)),ae.map((oe,he)=>({transaction:oe,workflowId:oe.workflowId,readOnly:q.find(ye=>ye.option.transactionId===oe.id)?.option.readOnly??!1,index:q[he].index}))},g=async q=>{if(q.length===0)return[];const Y=await d.mutate({mutation:R3,variables:{inputs:q.map(ae=>({integrationProductId:ae.option.type==="integration"?ae.option.integrationProductId:void 0,externalIntegrationId:ae.option.type==="external"?ae.option.externalIntegrationId:void 0,externalProductId:ae.option.type==="external"?ae.option.externalProductId:void 0,workflowId:ae.option.workflowId,designName:ae.option.designName,claim:!0,quantity:ae.option.quantity,recipient:ae.option.recipient,parentTransactionId:ae.option.parentTransactionId})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.getCreateTransactionContext(q,t)}),J=Y.data?.transactionCreateMany;if(!J||J.length===0){const ae=Y.errors?.[0]?.message||"Unknown error";throw new lo(`Failed to create transactions: ${ae}`)}return f=f+J.length,i&&i(f,s.length),J.map((ae,oe)=>({transaction:ae,workflowId:ae.workflowId,readOnly:!1,index:q[oe].index}))},v=(await Promise.all([...u.map(h),...c.map(g)])).flat();let y=[...new Set(v.map(q=>q.transaction.integrationProductId))].filter(q=>!!q);y=y.filter(q=>!!q);let A=[...new Set(v.map(q=>q.workflowId))].filter(q=>!!q);A=A.filter(q=>!!q);const[C,S]=await Promise.all([(async()=>y.length>0?await zP(y):[])(),(async()=>A.length>0?await tb(A,t):[])()]),F=new Map(C.map(q=>[q.id,q])),E=new Map(S.map(q=>[q.id,q])),R=v.map(async q=>{const{transaction:Y,workflowId:J,readOnly:ae,index:oe}=q,he=J?E.get(J):void 0,ye=e[oe];if(Y.integrationProductId){const re=F.get(Y.integrationProductId);Y.integrationProduct=re,Y.product=re?.product,Y.integrationProduct||console.error("failed to find transaction's product")}const Ue=br.getMap("transactionOwnerIds")||new Map;!Ue.get(Y.id)&&Y.transactionOwnerId&&(Ue.set(Y.id,Y.transactionOwnerId),br.setMap("transactionOwnerIds",Ue));const Re=Ue.get(Y.id)||void 0,Oe=new EV({onMutate:()=>({context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}})}),ee={workflow:he,transaction:Y,singleVariantsRenderable:ye?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:ae?async()=>{throw new nn("State mutation is forbidden in read only mode!")}:async re=>this.updateTransactionState({...re,context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}}),graphQlClient:()=>Oe,readOnly:ae,isReloadedTransaction:ye.type==="transaction"};if(ye.type==="transaction"&&Y.workflowState){const re=JSON.parse(Y.workflowState);await oA(re),ee.reloadedState=re}else if(!ae&&ye.workflowState){const re=JSON.parse(ye.workflowState);await oA(re),ee.reloadedState=re}return ee.delayWorkflowStateSync=!0,{experienceOptions:ee,index:oe,options:ye}}),j=(await Promise.all(R)).sort((q,Y)=>q.index-Y.index);let G=[],ie=[];for(const q of j){const{experienceOptions:Y,options:J}=q,ae=new M1(this,Y);await ae.getWorkflowManager().getInitializationPromise(),n&&n(),J.type!=="transaction"&&this.customer&&ie.push(ae),G=[...G,ae],ae.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}if(ie.length>0){const q=this.customer.emailAddress,Y=ie.map(oe=>oe.getTransaction().id),ae=(await d.mutate({mutation:Y9,variables:{ids:Y,details:{emailAddress:q},type:"Owner"},errorPolicy:"all"})).data?.transactionsAddStakeholder;if(ae&&ae?.length>0){const oe=ae[0].stakeholders?.find(he=>he.customer?.emailAddress===q);if(oe?.customer)for(const he of ie)he.assignCustomerInternal(oe.customer)}}return G}getCreateTransactionContext(e,t){const n=e.find(s=>s.option.parentTransactionId)?.option.parentTransactionId;if(!n&&!t?.bundleOwnerId)return;const i=br.getMap("transactionOwnerIds")||new Map,a=n?i.get(n):void 0;return{...a?{transactionOwnerId:a}:{},...t?.bundleOwnerId?{bundleOwnerId:t.bundleOwnerId}:{}}}storeCustomer(e){const t=br.getMap("partnerCustomerIds")||new Map;t.set(e.partner.id,e.id),br.setMap("partnerCustomerIds",t)}async getIntegrationProductById(e,t){const a=(await ze.getShadowGraphqlClient().query({query:z3(t),variables:{ids:[e]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!a||a.length===0||!a[0]?.id)throw new Error("Integration product not found.");return new mA(a[0])}async getIntegrationProductFromExternalIds(e,t,n){const s=(await ze.getShadowGraphqlClient().query({query:$3(n),variables:{externalProductId:t,externalIntegrationId:e},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!s?.id)throw new Error("Integration product not found.");return new mA(s)}async getIntegrationProduct(e){return e.type==="integration"?this.getIntegrationProductById(e.integrationProductId):this.getIntegrationProductFromExternalIds(e.externalIntegrationId,e.externalProductId)}async getShareActionsForTransaction(e){const n=(br.getMap("transactionOwnerIds")||new Map).get(e)||void 0,i=await ze.getShadowGraphqlClient().query({query:U3,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e},context:{transactionOwnerId:n}});if(!i.data.transactions||i.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${e}`);return i.data.transactions[0].transactionShareActions}async placeOrder(e){const t=await ze.getShadowGraphqlClient().mutate({mutation:eM,variables:{orderItems:e}});if(t.errors)throw new Error(t.errors[0].message);if(!t.data)throw new Error("Failed to create order: No order data in response.");return{id:t.data.orderCreate.id,internalId:t.data.orderCreate.internalId}}}const $P=async(r,e)=>(await ze.getShadowGraphqlClient().query({query:J3,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r},skipIntegrationCheck:!0},variables:{themeConfigurationId:e}})).data.currentIntegration,HQ=async r=>{const t=await ze.getShadowGraphqlClient().query({query:L3,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(t.data.transactions.length!==0)return t.data.transactions[0]},jQ=async(r,e)=>(await ze.getShadowGraphqlClient().query({query:X3,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:e}})).data?.marketplaceThemeInstallConfiguration,GQ=async r=>(await ze.getShadowGraphqlClient().query({query:Z3,errorPolicy:"all",variables:{id:r}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,qQ=async r=>(await ze.getShadowGraphqlClient().query({query:K3,errorPolicy:"all",variables:{id:r}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,HP=async(r,e)=>(await ze.getShadowGraphqlClient().query({query:lM(!!e),errorPolicy:"all",variables:{id:r,productIds:e}})).data?.activation,WQ=async r=>(await HP(r))?.marketplaceThemeInstallConfiguration;async function jP(){const r={};try{const e=await this.loggedInBearerToken();r.Authorization=`Bearer ${e}`}catch{const n=Object.entries(localStorage).find(([a,s])=>a.startsWith("CognitoIdentityServiceProvider")&&a.endsWith("idToken"))?.[0]||"",i=localStorage.getItem(n);i&&!vg(i)&&(r.Authorization=`Bearer ${i}`)}return r}async function GP(r){const t=br.getMap("bundleOwnerIds")?.get(r),n=await jP();return{bundleOwnerId:t,...n}}async function QQ(r){const t=br.getMap("transactionOwnerIds")?.get(r),n=await jP();return{transactionOwnerId:t,...n}}const YQ=async r=>{const e=await GP(r),t=await ze.getShadowGraphqlClient().mutate({mutation:T9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r},context:{headers:e}});if(t.data?.bundleDelete!==r)throw new Error(`Failed to delete bundle: ${t.errors}`)},XQ=async r=>{const e=await QQ(r),t=await ze.getShadowGraphqlClient().mutate({mutation:F9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[r]},context:{headers:e}});if(!t.data?.transactions||t.data.transactions.length!==1||t.data.transactions[0].id!==r)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(t.errors)}`);return t.data.transactions[0].bundle?.id};function qP(r,e,t,n){const i=t.width*r.zoom,a=t.height*r.zoom;if(n){const s=Math.max(e.width/t.width,e.height/t.height),o=Math.max(s,r.zoom),l=t.width*o,u=t.height*o;return{...r,x:Dp(r.x,e.width-l,0),y:Dp(r.y,e.height-u,0),zoom:o}}return{...r,x:Dp(r.x,-i,e.width),y:Dp(r.y,-a,e.height)}}function Dp(r,e,t){return Math.min(Math.max(r,e),t)}class WP{constructor(e,t){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=DI(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.onRotationChangeListeners=[],this.forceImageCover=e,this.initialZoom=t,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(e,t){t&&e.addStepSpecificStorageCallback(async n=>{if(n){const i=n;if(i.currentFrameSources){let a=!1;for(let s=0;s<i.currentFrameSources.length;s++){const o=i.currentFrameSources[s],l=await Xf(o),u=this.frameData?this.frameData[s]:void 0;vf(l,u)||(this.frameData||(this.frameData=new Array(i.currentFrameSources.length)),this.frameData[s]=l,a=!0)}a&&(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)))}}},t),this.workflowManager=e,this.stepName=t}setTargetElements(e){this.targetElements=e}getFrameData(){return this.frameData}setFrameData(e){if(!e){this.frameData=void 0;return}e.forEach((t,n)=>{const i=_u.get(t);i&&(this.frameData||(this.frameData=new Array(e.length)),this.frameData[n]=i)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const e=zg(this.imageData.svg,this.imageData.colors||{},!1);return Ug(e)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(e){this.offsets=e}setZoom(e,t,n,i){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const a=this.frameData.map((s,o)=>{const l=(t[o]-this.offsets[o].x)/this.offsets[o].zoom,u=(n[o]-this.offsets[o].y)/this.offsets[o].zoom,c=t[o]-l*e[o],f=n[o]-u*e[o];return{x:c,y:f,zoom:this.imageData.width*e[o]/this.imageData.width,rotation:this.offsets[o].rotation}});this.updateOffsets(a,i),this.onZoomChangeListeners.forEach(s=>s(e))}}setRotation(e,t){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const n=this.frameData.map((i,a)=>({...this.offsets[a],rotation:e[a]}));this.updateOffsets(n,t),this.onRotationChangeListeners.forEach(i=>i(e))}}setPatternData(e,t=!0){this.imageData=e,e&&this.frameData&&((t||!this.offsets)&&this.recalculateOffsets(e,t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(e,t,n){const i=this.imageData;if(!i||!this.frameData)return;if(this.frameData.length!==e.length)throw new nn("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(e[o].x===s.x&&e[o].y===s.y&&e[o].zoom===s.zoom&&e[o].rotation===s.rotation))&&!n){t&&t();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=qP(e[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,i,this.frameData,this.thresholdSettings,t)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(e){this.thresholdSettings=e,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,e)}onFrameDataChanged(e){e(this.frameData),this.onFrameDataChangeListeners.push(e)}onZoom(e){this.onZoomChangeListeners.push(e)}onRotation(e){this.onRotationChangeListeners.push(e)}updateFrameOffsets(e,t,n,i,a){if(!n||n.length===0||n.some(l=>!l))throw new nn("Frame data not set. This is a bug");if(!this.workflowManager)throw new nn("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getRegionElements(this.stepName||""),o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,u)=>{let c=s.find(f=>f.id===l)?.regionIndex??u;c>=e.length&&(c=u);try{o(new In([new SL(l,t,e[c]),new EL(l,i.useThreshold,i.invertThreshold,i.threshold,i.thresholdSaturation)]))}catch{}}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:e}),a&&a()}recalculateZoomLimits(e,t){(this.minZoomScale.length!==t.length||this.maxZoomScale.length!==t.length)&&(this.minZoomScale=new Array(t.length),this.maxZoomScale=new Array(t.length)),t.forEach((n,i)=>{const a=Math.max(n.width/e.width,n.height/e.height);this.forceImageCover?(this.minZoomScale[i]=a,this.maxZoomScale[i]=a*2.5):(this.minZoomScale[i]=a/10,this.maxZoomScale[i]=a*2.5)})}recalculateOffsets(e,t=!0){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((n,i)=>{const a=t?0:this.offsets[i]?.rotation||0;this.offsets[i]={...x1(e,n,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover),rotation:a}}),this._debouncedUpdateFrameOffsets(this.offsets,e,this.frameData,this.thresholdSettings))}}class JQ{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(e,t,n,i,a,s,o,l,u,c,f,d,h,g,v,y,A){throw new Error("Method not implemented.")}approveTransaction(e){throw new Error("Method not implemented.")}rejectTransaction(e){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(e){this.client=e}getInitializationPromise(){return Promise.resolve()}async updateWorkflowConfiguration(e,t){throw new Error("Method not implemented.")}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(e){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(e){}addPoller(e){}addConfirmCallback(e){}addEditedCallback(e){}addElementsCallback(e){}addInformationResultCallback(e){}addInitCallback(e){}addMakingAdjustmentsCallback(e){}addMandatoryCallback(e){}addMetadataCallback(e){}addSelectionCallback(e){}addStepSpecificStorageCallback(e,t){}addStorageCallback(e){}getCommandDispatcher(){return e=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(e){return[]}getSerializedStep(e,t){}getStepSpecificServices(e){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Promise(()=>new Set)}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(e){}markUpdateCompleted(e){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(e){}setEditedStatus(e,t){}setInformationResults(e){}setMandatoryFulfilled(e,t){}async setSelectionsAndElements(e,t,n){}toggleDesignConfirmed(){}updateMetadata(e,t){}async updateStorage(e,t){}injectIntoPreviewService(e){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(e){}async updateTransactionShareActions(){}addValidationCallback(e){}setStepError(e,t,n){}getStepErrors(e){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(e){return[]}}var QP=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(QP||{}),YP=(r=>(r.Original="original",r.BackgroundRemoved="backgroundRemoved",r.Optimized="optimized",r))(YP||{});class XP extends Ui{constructor(e,t,n){super(e,t,n);const i=t.data;this.frameService=new WP(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(e,t.stepName)}selectVariant(e){const t=this.manager.getRegionElements(this.step.stepName);return so.selectVariant(this.step,e.getResource(),t,this.manager,n=>this.setUpdateState(n))}onFrameDataChanged(e){this.frameService&&this.frameService.onFrameDataChanged(t=>{t&&e(t)})}async selectImage(e,t=!0,n=!0){await so.selectImage(this.step,e,this.manager,n),t&&this.manager.updateStorage(this.step.stepName,{framePatternData:{originalAssetKey:e.key,backgroundRemovedAssetKey:void 0,vectorizedAssetKey:void 0,enhancedAssetKey:void 0,useOriginalAsset:void 0}})}async canUseAdvancedImageManipulation(){return this.manager.getClient().canUseAddon(Bg.AdvancedImageManipulation)}async canRemoveBackground(){return await this.canUseAdvancedImageManipulation()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(e=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseAdvancedImageManipulation to ensure you disable this feature when appropriate.");const t=await this.getOriginalImageSelection();if(!t)throw new Error("You must supply an image selection before attempting to remove the background.");const n=await Ln.removeBackgroundFromAsset(t);e&&await so.selectImage(this.step,n,this.manager,!1);const i=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,backgroundRemovedAssetKey:n.key,useOriginalAsset:!e}}),n}async vectorize(e,t=void 0){const n=e??await this.getOriginalImageSelection();if(!n)throw new Error("You must supply an image selection before attempting to vectorize the image.");const i=await Ln.vectorizeAsset(n,t);await this.selectImage(i,!1);const a=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,vectorizedAssetKey:i.key,useOriginalAsset:!1}}),i}async enhanceWithAI(e,t){const n=e??await this.getOriginalImageSelection();if(!n)throw new Error("You must supply an image selection before attempting to enhance the image with AI.");const i=await Ln.enhanceWithAI(n,t);await this.selectImage(i,!1);const a=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{originalAssetKey:a.originalAssetKey,backgroundRemovedAssetKey:a.backgroundRemovedAssetKey,vectorizedAssetKey:a.vectorizedAssetKey,enhancedAssetKey:i.key,useOriginalAsset:!1}}),i}async getBackgroundRemovedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}async getVectorizedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}async getEnhancedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}hasOriginalImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}hasEnhancedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey}async changeColors(e){await so.changeColors(this.step,this.manager,e)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await ct.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?so.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const e=this.getImageData();return e?.svg?(await Pa(e.svg)).colors:void 0}async mergeColors(e,t,n){const i=this.frameService.getImageData();if(!i?.svg||!i.colors)throw new Error("Cannot merge colors on non-SVG image or image without color information");const{svg:a,colors:s}=pT(i.svg,i.colors,e,t,n);this.frameService.setPatternData({...i,svg:a,colors:s},!1),this.manager.updateStorage(this.step.stepName,{colors:s})}async unmergeColors(e,t,n,i){const a=this.frameService.getImageData();if(!a?.svg||!a.colors)throw new Error("Cannot unmerge colors on non-SVG image or image without color information");this.frameService.setPatternData({...a,svg:i,colors:n},!1),this.manager.updateStorage(this.step.stepName,{colors:n})}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMinimumPixelThresholdForOptimization(){return this.step.data.vectorizationMinimumPixelThreshold}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return so.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(e,t,n,i){return i&&i.length>1&&e===void 0?"SelectFrame":t||n||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.originalAssetKey;if(e)return Ln.getLocalOrFromServer(e)}getCurrentImageState(){const e=this.getFrameStepStorage()?.framePatternData;return e?e.vectorizedAssetKey&&!e.useOriginalAsset?"optimized":e.useOriginalAsset!==!1?"original":"backgroundRemoved":"original"}async setImageState(e){const t=this.getFrameStepStorage()?.framePatternData||{};let n,i;switch(e){case"original":if(n=await this.getOriginalImageSelection(),!n)throw new Error("No original image available");i=!0;break;case"backgroundRemoved":if(n=await this.getBackgroundRemovedImageSelection(),!n)throw new Error("No background-removed image available. Call removeBackgroundFromImageSelection first.");i=!1;break;case"optimized":if(n=await this.getVectorizedImageSelection(),!n)throw new Error("No optimized image available. Call vectorize first.");i=!1;break}await this.selectImage(n,!1,!0),this.manager.updateStorage(this.step.stepName,{framePatternData:{...t,useOriginalAsset:i}})}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(e){const t=this.getFrameStepStorage()?.framePatternData||{};if(t.useOriginalAsset===e)return;const n=await this.getOriginalImageSelection();if(!n)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(e)await this.selectImage(n,!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:{...t,useOriginalAsset:e}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const KQ=Se`
3056
+ ${V2(t)}`);const i=await ze.getShadowGraphqlClient().query({query:t,errorPolicy:"all",variables:n,context:{logRequestHeaders:!0}});if(i.error)throw console.log("[getWorkflowsInternal] Response errored."),i.error;if(i.errors)throw i.errors.forEach(s=>console.error(s)),new Error("Unable to read workflows. Consult GraphQL errors.");if(!i.data.workflows||i.data.workflows.length!==r.length)throw new Error(`Unable to read workflows: ${i.errors??"Length mismatch in response"}`);const a=mo(i.data.workflows);return a.forEach(s=>{s.finalizeStepConfig||(s.finalizeStepConfig={}),s.finalizeStepConfig.termsMarkdown=s.finalizeStepConfig.termsMarkdown||s.partner.termsMarkdown}),a},zQ=async(r,e)=>{const n=(await e).find(i=>i.id===r);if(!n)throw new Error(`Workflow not found: ${r}`);return n},tb=async(r,e)=>{const t=r.map(o=>mf.get({id:o,options:e})),n=r.filter((o,l)=>t[l]===void 0);if(n.length===0)return Promise.all(t);const i=VQ(n,e),a=n.map(o=>mf.set({id:o,options:e},zQ(o,i))),s=t.filter(o=>o!==void 0);return await Promise.all(s.concat(a))},VP=async(r,e)=>(await tb([r],e))[0],zP=async r=>{const e=await ze.getShadowGraphqlClient().query({query:wT,variables:{ids:r},errorPolicy:"all",fetchPolicy:"no-cache"});return e.errors&&console.error(e.errors),e.data.integrationProducts||[]};class $Q{constructor(e){this.activeIntegration=void 0,this.updateTransactionState=async t=>{try{return ze.getShadowGraphqlClient().mutate({...t,mutation:B3})}catch(n){throw console.error(n),new lo("Critical - Unable to synchronize workflow state with server.")}},this.options=e,this.options.applicationKey&&Jk(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 44.5.6-alpha.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(e){ss.setHubUrl(e.hubUrl),ss.setServerUrl(e.serverUrl),ss.setServicesApiUrl(e.servicesApiUrl),this.marketplaceThemeInstallId=e.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=e.marketplaceThemeInstallConfigurationId,this.userPoolClientId=e.userPoolClientId,this.userPoolRegion=e.userPoolRegion,this.spiffRegion=e.spiffRegion,e.bearerAuthenticationToken&&Zk(e.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Id.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getVersion(){return"44.5.6-alpha.0"}getAssetManager(){return Ln}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!eB())throw new Error("Application key required to use Flow Service.");return new NI}async getCurrencyContext(e){const n=(await this.getIntegration()).partner.currencyCode,a=await ze.getShadowGraphqlClient().query({query:tM,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:n,to:e}}),{rateFrom:s,rateTo:o}=a.data.currencyConversion;return new UP(s,o,n,e)}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=$P(this.options.applicationKey),this.activeIntegration}async canUseAddon(e){try{return(await this.getIntegration()).partner.activeAddons?.includes(e)??!1}catch(t){return console.error(t),!1}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(e){const t=br.getMap("transactionCustomerIds");t?.has(e)&&(t.delete(e),br.setMap("transactionCustomerIds",t))}async customerHasBundleTemplates(e){const i=(await ze.getShadowGraphqlClient().query({query:Bv,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;return i.id?i.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(e){const t=this.customer?.stakeholders?.find(n=>n.transaction?.id===e);if(t)return t.type}async getOrCreateCustomer(e){this.customer=void 0;const t=ze.getShadowGraphqlClient(),i=(await t.query({query:Bv,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e}})).data.customer;if(!i.id){const o=(await t.mutate({mutation:bV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:e}}})).data?.customerCreate;if(!o)throw new Error("Unable to create customer.");return this.storeCustomer(o),this.customer=o,{customer:o,isAuthenticated:!1}}this.storeCustomer(i);const a=await this.reloadLoggedInCustomer();return{customer:this.customer||i,isAuthenticated:a}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const e=localStorage.getItem("last-refreshed-cognito-tokens"),t=localStorage.getItem("cognito-tokens"),n=localStorage.getItem("cognito-email");if(!e||!t||!n)return!1;const i=JSON.parse(t),a=new Date().getTime()/1e3;if(!i.ExpiresIn||i.ExpiresIn<a-parseInt(e)){const u=await Id.refreshTokens();if(u?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),i.AccessToken=u.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(i));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=localStorage.getItem("customer-login-token");s&&p0(s);const l=(await ze.getShadowGraphqlClient().query({query:Bv,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:n}})).data.customer;return l.id?(this.customer=l,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(e){await ze.getShadowGraphqlClient().mutate({mutation:CV,variables:{emailAddress:e}}),await Id.generateCode(e)}async verifyCode(e,t){const n=(await this.getIntegration()).partner.id||"",i=await Id.verifyCode(e,t,n);if(i?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(i.AuthenticationResult)),localStorage.setItem("cognito-email",e);const s=(await ze.getShadowGraphqlClient().mutate({mutation:xV,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:e,verificationCode:t}})).data?.customerVerifyCode;if(!s?.id)throw new Error("Failed to get customer.");return this.customer=s,s.loginToken&&(localStorage.setItem("customer-login-token",s.loginToken),p0(s.loginToken)),!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),localStorage.removeItem("customer-login-token"),p0(""),this.clearCustomer()}async loggedInBearerToken(){const e=localStorage.getItem("last-refreshed-cognito-tokens"),t=localStorage.getItem("cognito-tokens");if(!e||!t)throw new Error("No token data in storage.");const n=JSON.parse(t),i=new Date().getTime()/1e3,a=!n?.AccessToken||vg(n.AccessToken);if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(e)||a){const s=await Id.refreshTokens();if(s?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!n.AccessToken)throw new Error("No bearer token in storage.");return n.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await ze.getShadowGraphqlClient().query({query:SV,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(e,t,n,i){const s=(await ze.getShadowGraphqlClient().mutate({mutation:s9(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:e,initialMetadata:t?Object.entries(t).map((c,f)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,activationId:i,test:n?.test},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!s?.id)throw new Error("Unable to create bundle");const o=br.getMap("bundlePartnerIds")||new Map;o.set(s.id,s.partner.id),br.setMap("bundlePartnerIds",o);const l=br.getMap("bundleOwnerIds")||new Map;l.set(s.id,s.bundleOwnerId),br.setMap("bundleOwnerIds",l);const u=new OE(this,s,void 0,void 0,s.bundleOwnerId,{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts});return await u.getInitializationPromise(),u}async getExistingBundle(e,t,n,i,a){const o=br.getMap("bundleOwnerIds")?.get(e),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const y=Object.entries(localStorage).find(([C,S])=>C.startsWith("CognitoIdentityServiceProvider")&&C.endsWith("idToken"))?.[0]||"",A=localStorage.getItem(y);A&&!vg(A)&&(l.Authorization=`Bearer ${A}`)}const u={bundleOwnerId:o,...l,...i?.graphql?.additionalHeaders},c=await ze.getShadowGraphqlClient().query({query:r9(i?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:e},fetchPolicy:"no-cache",context:{headers:u}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${e}`);const f=c.data?.bundles[0],d=br.getMap("bundlePartnerIds")||new Map;d.set(f.id,f.partner.id),br.setMap("bundlePartnerIds",d);const h=new OE(this,f,t,n,o,{additionalHeaders:i?.graphql?.additionalHeaders,eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:i?.readonly},a);return await h.getInitializationPromise(),h}async duplicateBundle(e,t,n,i){const s={...await GP(e),...i?.graphql?.additionalHeaders},l=(await ze.getShadowGraphqlClient().mutate({mutation:o9(),variables:{id:e,template:t,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:n,test:i?.test},context:{headers:s},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const u=br.getMap("bundlePartnerIds")||new Map;u.set(l.id,l.partner.id),br.setMap("bundlePartnerIds",u);const c=br.getMap("bundleOwnerIds")||new Map;return c.set(l.id,l.bundleOwnerId),br.setMap("bundleOwnerIds",c),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:i?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(e){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:t,...n}=e;return(await ze.getShadowGraphqlClient().query({query:y9(t??!1),variables:{...n,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const e=await ze.getShadowGraphqlClient().query({query:n9,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!e.data?.customers||e.data.customers.length===0)throw new Error("Unable to find customer.");const n=e.data.customers[0].bundleStakeholders||[],i=br.getMap("bundlePartnerIds")||new Map;return n.forEach(a=>{a.bundle?.id&&a.bundle.partner?.id&&i.set(a.bundle.id,a.bundle.partner.id)}),br.setMap("bundlePartnerIds",i),n}async getWorkflowExperience(e,t){if(!e)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const n=await this.getWorkflowExperiences([e],e.graphql),i=n[0],a=i.getWorkflow();return t&&!a&&console.error("No workflow instantiated when trying to create preview service."),t&&a&&await i.getWorkflowManager().injectIntoPreviewService(t(a)),n[0]}async getWorkflowExperiences(e,t,n,i){if(e.length===0)throw new lo("No options provided!");const a=e.map((q,Y)=>({option:q,index:Y})),s=a.filter(q=>q.option.type==="transaction"),o=a.filter(q=>q.option.type==="integration"||q.option.type==="external"||q.option.type==="blank"),l=50,u=hA(s,l),c=hA(o,l);let f=0;const d=ze.getShadowGraphqlClient(),h=async q=>{if(q.length===0)return[];const Y=q.map(oe=>oe.option.transactionId),J=await d.query({query:O3,variables:{ids:Y},errorPolicy:"all",fetchPolicy:"no-cache"}),ae=J.data.transactions;if(f=f+ae.length,i&&i(f,s.length),ae.length!==q.length){const oe=J.errors?.[0]?.message||"Unknown error";throw new lo(`Not all transactions were found: ${oe}`)}return!this.activeIntegration&&ae[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(ae[0].integrationProduct.integration)),ae.map((oe,he)=>({transaction:oe,workflowId:oe.workflowId,readOnly:q.find(ye=>ye.option.transactionId===oe.id)?.option.readOnly??!1,index:q[he].index}))},g=async q=>{if(q.length===0)return[];const Y=await d.mutate({mutation:R3,variables:{inputs:q.map(ae=>({integrationProductId:ae.option.type==="integration"?ae.option.integrationProductId:void 0,externalIntegrationId:ae.option.type==="external"?ae.option.externalIntegrationId:void 0,externalProductId:ae.option.type==="external"?ae.option.externalProductId:void 0,workflowId:ae.option.workflowId,designName:ae.option.designName,claim:!0,quantity:ae.option.quantity,recipient:ae.option.recipient,parentTransactionId:ae.option.parentTransactionId})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.getCreateTransactionContext(q,t)}),J=Y.data?.transactionCreateMany;if(!J||J.length===0){const ae=Y.errors?.[0]?.message||"Unknown error";throw new lo(`Failed to create transactions: ${ae}`)}return f=f+J.length,i&&i(f,s.length),J.map((ae,oe)=>({transaction:ae,workflowId:ae.workflowId,readOnly:!1,index:q[oe].index}))},v=(await Promise.all([...u.map(h),...c.map(g)])).flat();let y=[...new Set(v.map(q=>q.transaction.integrationProductId))].filter(q=>!!q);y=y.filter(q=>!!q);let A=[...new Set(v.map(q=>q.workflowId))].filter(q=>!!q);A=A.filter(q=>!!q);const[C,S]=await Promise.all([(async()=>y.length>0?await zP(y):[])(),(async()=>A.length>0?await tb(A,t):[])()]),F=new Map(C.map(q=>[q.id,q])),E=new Map(S.map(q=>[q.id,q])),R=v.map(async q=>{const{transaction:Y,workflowId:J,readOnly:ae,index:oe}=q,he=J?E.get(J):void 0,ye=e[oe];if(Y.integrationProductId){const re=F.get(Y.integrationProductId);Y.integrationProduct=re,Y.product=re?.product,Y.integrationProduct||console.error("failed to find transaction's product")}const Ue=br.getMap("transactionOwnerIds")||new Map;!Ue.get(Y.id)&&Y.transactionOwnerId&&(Ue.set(Y.id,Y.transactionOwnerId),br.setMap("transactionOwnerIds",Ue));const Re=Ue.get(Y.id)||void 0,Oe=new EV({onMutate:()=>({context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}})}),ee={workflow:he,transaction:Y,singleVariantsRenderable:ye?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:ae?async()=>{throw new nn("State mutation is forbidden in read only mode!")}:async re=>this.updateTransactionState({...re,context:{transactionOwnerId:Re,bundleOwnerId:t?.bundleOwnerId}}),graphQlClient:()=>Oe,readOnly:ae,isReloadedTransaction:ye.type==="transaction"};if(ye.type==="transaction"&&Y.workflowState){const re=JSON.parse(Y.workflowState);await oA(re),ee.reloadedState=re}else if(!ae&&ye.workflowState){const re=JSON.parse(ye.workflowState);await oA(re),ee.reloadedState=re}return ee.delayWorkflowStateSync=!0,{experienceOptions:ee,index:oe,options:ye}}),j=(await Promise.all(R)).sort((q,Y)=>q.index-Y.index);let G=[],ie=[];for(const q of j){const{experienceOptions:Y,options:J}=q,ae=new M1(this,Y);await ae.getWorkflowManager().getInitializationPromise(),n&&n(),J.type!=="transaction"&&this.customer&&ie.push(ae),G=[...G,ae],ae.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}if(ie.length>0){const q=this.customer.emailAddress,Y=ie.map(oe=>oe.getTransaction().id),ae=(await d.mutate({mutation:Y9,variables:{ids:Y,details:{emailAddress:q},type:"Owner"},errorPolicy:"all"})).data?.transactionsAddStakeholder;if(ae&&ae?.length>0){const oe=ae[0].stakeholders?.find(he=>he.customer?.emailAddress===q);if(oe?.customer)for(const he of ie)he.assignCustomerInternal(oe.customer)}}return G}getCreateTransactionContext(e,t){const n=e.find(s=>s.option.parentTransactionId)?.option.parentTransactionId;if(!n&&!t?.bundleOwnerId)return;const i=br.getMap("transactionOwnerIds")||new Map,a=n?i.get(n):void 0;return{...a?{transactionOwnerId:a}:{},...t?.bundleOwnerId?{bundleOwnerId:t.bundleOwnerId}:{}}}storeCustomer(e){const t=br.getMap("partnerCustomerIds")||new Map;t.set(e.partner.id,e.id),br.setMap("partnerCustomerIds",t)}async getIntegrationProductById(e,t){const a=(await ze.getShadowGraphqlClient().query({query:z3(t),variables:{ids:[e]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!a||a.length===0||!a[0]?.id)throw new Error("Integration product not found.");return new mA(a[0])}async getIntegrationProductFromExternalIds(e,t,n){const s=(await ze.getShadowGraphqlClient().query({query:$3(n),variables:{externalProductId:t,externalIntegrationId:e},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!s?.id)throw new Error("Integration product not found.");return new mA(s)}async getIntegrationProduct(e){return e.type==="integration"?this.getIntegrationProductById(e.integrationProductId):this.getIntegrationProductFromExternalIds(e.externalIntegrationId,e.externalProductId)}async getShareActionsForTransaction(e){const n=(br.getMap("transactionOwnerIds")||new Map).get(e)||void 0,i=await ze.getShadowGraphqlClient().query({query:U3,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:e},context:{transactionOwnerId:n}});if(!i.data.transactions||i.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${e}`);return i.data.transactions[0].transactionShareActions}async placeOrder(e){const t=await ze.getShadowGraphqlClient().mutate({mutation:eM,variables:{orderItems:e}});if(t.errors)throw new Error(t.errors[0].message);if(!t.data)throw new Error("Failed to create order: No order data in response.");return{id:t.data.orderCreate.id,internalId:t.data.orderCreate.internalId}}}const $P=async(r,e)=>(await ze.getShadowGraphqlClient().query({query:J3,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r},skipIntegrationCheck:!0},variables:{themeConfigurationId:e}})).data.currentIntegration,HQ=async r=>{const t=await ze.getShadowGraphqlClient().query({query:L3,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(t.data.transactions.length!==0)return t.data.transactions[0]},jQ=async(r,e)=>(await ze.getShadowGraphqlClient().query({query:X3,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:e}})).data?.marketplaceThemeInstallConfiguration,GQ=async r=>(await ze.getShadowGraphqlClient().query({query:Z3,errorPolicy:"all",variables:{id:r}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,qQ=async r=>(await ze.getShadowGraphqlClient().query({query:K3,errorPolicy:"all",variables:{id:r}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration,HP=async(r,e)=>(await ze.getShadowGraphqlClient().query({query:lM(!!e),errorPolicy:"all",variables:{id:r,productIds:e}})).data?.activation,WQ=async r=>(await HP(r))?.marketplaceThemeInstallConfiguration;async function jP(){const r={};try{const e=await this.loggedInBearerToken();r.Authorization=`Bearer ${e}`}catch{const n=Object.entries(localStorage).find(([a,s])=>a.startsWith("CognitoIdentityServiceProvider")&&a.endsWith("idToken"))?.[0]||"",i=localStorage.getItem(n);i&&!vg(i)&&(r.Authorization=`Bearer ${i}`)}return r}async function GP(r){const t=br.getMap("bundleOwnerIds")?.get(r),n=await jP();return{bundleOwnerId:t,...n}}async function QQ(r){const t=br.getMap("transactionOwnerIds")?.get(r),n=await jP();return{transactionOwnerId:t,...n}}const YQ=async r=>{const e=await GP(r),t=await ze.getShadowGraphqlClient().mutate({mutation:T9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:r},context:{headers:e}});if(t.data?.bundleDelete!==r)throw new Error(`Failed to delete bundle: ${t.errors}`)},XQ=async r=>{const e=await QQ(r),t=await ze.getShadowGraphqlClient().mutate({mutation:F9,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[r]},context:{headers:e}});if(!t.data?.transactions||t.data.transactions.length!==1||t.data.transactions[0].id!==r)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(t.errors)}`);return t.data.transactions[0].bundle?.id};function qP(r,e,t,n){const i=t.width*r.zoom,a=t.height*r.zoom;if(n){const s=Math.max(e.width/t.width,e.height/t.height),o=Math.max(s,r.zoom),l=t.width*o,u=t.height*o;return{...r,x:Dp(r.x,e.width-l,0),y:Dp(r.y,e.height-u,0),zoom:o}}return{...r,x:Dp(r.x,-i,e.width),y:Dp(r.y,-a,e.height)}}function Dp(r,e,t){return Math.min(Math.max(r,e),t)}class WP{constructor(e,t){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=DI(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.onRotationChangeListeners=[],this.forceImageCover=e,this.initialZoom=t,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(e,t){t&&e.addStepSpecificStorageCallback(async n=>{if(n){const i=n;if(i.currentFrameSources){let a=!1;for(let s=0;s<i.currentFrameSources.length;s++){const o=i.currentFrameSources[s],l=await Xf(o),u=this.frameData?this.frameData[s]:void 0;vf(l,u)||(this.frameData||(this.frameData=new Array(i.currentFrameSources.length)),this.frameData[s]=l,a=!0)}a&&(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)))}}},t),this.workflowManager=e,this.stepName=t}setTargetElements(e){this.targetElements=e}getFrameData(){return this.frameData}setFrameData(e){if(!e){this.frameData=void 0;return}e.forEach((t,n)=>{const i=_u.get(t);i&&(this.frameData||(this.frameData=new Array(e.length)),this.frameData[n]=i)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const e=zg(this.imageData.svg,this.imageData.colors||{},!1);return Ug(e)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(e){this.offsets=e}setZoom(e,t,n,i){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const a=this.frameData.map((s,o)=>{const l=(t[o]-this.offsets[o].x)/this.offsets[o].zoom,u=(n[o]-this.offsets[o].y)/this.offsets[o].zoom,c=t[o]-l*e[o],f=n[o]-u*e[o];return{x:c,y:f,zoom:this.imageData.width*e[o]/this.imageData.width,rotation:this.offsets[o].rotation}});this.updateOffsets(a,i),this.onZoomChangeListeners.forEach(s=>s(e))}}setRotation(e,t){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const n=this.frameData.map((i,a)=>({...this.offsets[a],rotation:e[a]}));this.updateOffsets(n,t),this.onRotationChangeListeners.forEach(i=>i(e))}}setPatternData(e,t=!0){this.imageData=e,e&&this.frameData&&((t||!this.offsets)&&this.recalculateOffsets(e,t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(e,t,n){const i=this.imageData;if(!i||!this.frameData)return;if(this.frameData.length!==e.length)throw new nn("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(e[o].x===s.x&&e[o].y===s.y&&e[o].zoom===s.zoom&&e[o].rotation===s.rotation))&&!n){t&&t();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=qP(e[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,i,this.frameData,this.thresholdSettings,t)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(e){this.thresholdSettings=e,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,e)}onFrameDataChanged(e){e(this.frameData),this.onFrameDataChangeListeners.push(e)}onZoom(e){this.onZoomChangeListeners.push(e)}onRotation(e){this.onRotationChangeListeners.push(e)}updateFrameOffsets(e,t,n,i,a){if(!n||n.length===0||n.some(l=>!l))throw new nn("Frame data not set. This is a bug");if(!this.workflowManager)throw new nn("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getRegionElements(this.stepName||""),o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,u)=>{let c=s.find(f=>f.id===l)?.regionIndex??u;c>=e.length&&(c=u);try{o(new In([new SL(l,t,e[c]),new EL(l,i.useThreshold,i.invertThreshold,i.threshold,i.thresholdSaturation)]))}catch{}}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:e}),a&&a()}recalculateZoomLimits(e,t){(this.minZoomScale.length!==t.length||this.maxZoomScale.length!==t.length)&&(this.minZoomScale=new Array(t.length),this.maxZoomScale=new Array(t.length)),t.forEach((n,i)=>{const a=Math.max(n.width/e.width,n.height/e.height);this.forceImageCover?(this.minZoomScale[i]=a,this.maxZoomScale[i]=a*2.5):(this.minZoomScale[i]=a/10,this.maxZoomScale[i]=a*2.5)})}recalculateOffsets(e,t=!0){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((n,i)=>{const a=t?0:this.offsets[i]?.rotation||0;this.offsets[i]={...x1(e,n,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover),rotation:a}}),this._debouncedUpdateFrameOffsets(this.offsets,e,this.frameData,this.thresholdSettings))}}class JQ{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(e,t,n,i,a,s,o,l,u,c,f,d,h,g,v,y,A){throw new Error("Method not implemented.")}approveTransaction(e){throw new Error("Method not implemented.")}rejectTransaction(e){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(e){this.client=e}getInitializationPromise(){return Promise.resolve()}async updateWorkflowConfiguration(e,t){throw new Error("Method not implemented.")}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(e){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(e){}addPoller(e){}addConfirmCallback(e){}addEditedCallback(e){}addElementsCallback(e){}addInformationResultCallback(e){}addInitCallback(e){}addMakingAdjustmentsCallback(e){}addMandatoryCallback(e){}addMetadataCallback(e){}addSelectionCallback(e){}addStepSpecificStorageCallback(e,t){}addStorageCallback(e){}getCommandDispatcher(){return e=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(e){return[]}getSerializedStep(e,t){}getStepSpecificServices(e){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getInitialOptionIds(){return new Promise(()=>new Set)}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(e){}markUpdateCompleted(e){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(e){}setEditedStatus(e,t){}setInformationResults(e){}setMandatoryFulfilled(e,t){}async setSelectionsAndElements(e,t,n){}toggleDesignConfirmed(){}updateMetadata(e,t){}async updateStorage(e,t){}injectIntoPreviewService(e){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(e){}async updateTransactionShareActions(){}addValidationCallback(e){}setStepError(e,t,n){}getStepErrors(e){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(e){return[]}}var QP=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(QP||{}),YP=(r=>(r.Original="original",r.BackgroundRemoved="backgroundRemoved",r.Optimized="optimized",r))(YP||{});class XP extends Ui{constructor(e,t,n){super(e,t,n);const i=t.data;this.frameService=new WP(i.forceImageCover,i.initialZoomLevel),this.frameService.connectWorkflowManager(e,t.stepName)}selectVariant(e){const t=this.manager.getRegionElements(this.step.stepName);return so.selectVariant(this.step,e.getResource(),t,this.manager,n=>this.setUpdateState(n))}onFrameDataChanged(e){this.frameService&&this.frameService.onFrameDataChanged(t=>{t&&e(t)})}async selectImage(e,t=!0,n=!0){await so.selectImage(this.step,e,this.manager,n),t&&this.manager.updateStorage(this.step.stepName,{framePatternData:{originalAssetKey:e.key,backgroundRemovedAssetKey:void 0,vectorizedAssetKey:void 0,enhancedAssetKey:void 0,useOriginalAsset:void 0}})}async canUseAdvancedImageManipulation(){return this.manager.getClient().canUseAddon(Bg.AdvancedImageManipulation)}async canRemoveBackground(){return await this.canUseAdvancedImageManipulation()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(e=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseAdvancedImageManipulation to ensure you disable this feature when appropriate.");const t=await this.getOriginalImageSelection();if(!t)throw new Error("You must supply an image selection before attempting to remove the background.");const n=await Ln.removeBackgroundFromAsset(t);e&&await so.selectImage(this.step,n,this.manager,!1);const i=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,backgroundRemovedAssetKey:n.key,useOriginalAsset:!e}}),n}async vectorize(e,t=void 0){const n=e??await this.getOriginalImageSelection();if(!n)throw new Error("You must supply an image selection before attempting to vectorize the image.");const i=await Ln.vectorizeAsset(n,t);await this.selectImage(i,!1);const a=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,vectorizedAssetKey:i.key,useOriginalAsset:!1}}),i}async enhanceWithAI(e,t){const n=e??await this.getOriginalImageSelection();if(!n)throw new Error("You must supply an image selection before attempting to enhance the image with AI.");const i=await Ln.enhanceWithAI(n,t);await this.selectImage(i,!1);const a=this.getFrameStepStorage()?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{originalAssetKey:a.originalAssetKey,backgroundRemovedAssetKey:a.backgroundRemovedAssetKey,vectorizedAssetKey:a.vectorizedAssetKey,enhancedAssetKey:i.key,useOriginalAsset:!1}}),i}async getBackgroundRemovedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}async getVectorizedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}async getEnhancedImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey;if(e)return Ln.getLocalOrFromServer(e)}hasOriginalImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}hasEnhancedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.enhancedAssetKey}async changeColors(e){await so.changeColors(this.step,this.manager,e)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await ct.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?so.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const e=this.getImageData();return e?.svg?(await Pa(e.svg)).colors:void 0}async mergeColors(e,t,n){const i=this.frameService.getImageData();if(!i?.svg||!i.colors)throw new Error("Cannot merge colors on non-SVG image or image without color information");const{svg:a,colors:s}=pT(i.svg,i.colors,e,t,n);this.frameService.setPatternData({...i,svg:a,colors:s},!1),this.manager.updateStorage(this.step.stepName,{colors:s})}async unmergeColors(e,t,n,i){const a=this.frameService.getImageData();if(!a?.svg||!a.colors)throw new Error("Cannot unmerge colors on non-SVG image or image without color information");this.frameService.setPatternData({...a,svg:i,colors:n},!1),this.manager.updateStorage(this.step.stepName,{colors:n})}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMinimumPixelThresholdForOptimization(){return this.step.data.vectorizationMinimumPixelThreshold}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return so.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(e,t,n,i){return i&&i.length>1&&e===void 0?"SelectFrame":t||n||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const e=this.getFrameStepStorage()?.framePatternData?.originalAssetKey;if(e)return Ln.getLocalOrFromServer(e)}getCurrentImageState(){const e=this.getFrameStepStorage()?.framePatternData;return e?e.vectorizedAssetKey&&!e.useOriginalAsset?"optimized":e.useOriginalAsset!==!1?"original":"backgroundRemoved":"original"}async setImageState(e){const t=this.getFrameStepStorage()?.framePatternData||{};let n,i;switch(e){case"original":if(n=await this.getOriginalImageSelection(),!n)throw new Error("No original image available");i=!0;break;case"backgroundRemoved":if(n=await this.getBackgroundRemovedImageSelection(),!n)throw new Error("No background-removed image available. Call removeBackgroundFromImageSelection first.");i=!1;break;case"optimized":if(n=await this.getVectorizedImageSelection(),!n)throw new Error("No optimized image available. Call vectorize first.");i=!1;break}await this.selectImage(n,!1,!0),this.manager.updateStorage(this.step.stepName,{framePatternData:{...t,useOriginalAsset:i}})}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(e){const t=this.getFrameStepStorage()?.framePatternData||{};if(t.useOriginalAsset===e)return;const n=await this.getOriginalImageSelection();if(!n)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(e)await this.selectImage(n,!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:{...t,useOriginalAsset:e}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const KQ=Se`
3057
3057
  query GetLoggedInCustomer($email: String!) {
3058
3058
  customer(emailAddress: $email) {
3059
3059
  id
@@ -3266,4 +3266,4 @@ ${V2(t)}`);const i=await ze.getShadowGraphqlClient().query({query:t,errorPolicy:
3266
3266
  }
3267
3267
  }
3268
3268
  `,PY=async r=>(await ze.getShadowGraphqlClient().query({query:IY,variables:{ids:r}})).data.integrationProducts;function DY(r){return new M1({},{stateMutationFunc:(()=>Promise.resolve()),transaction:{id:"local-transaction",product:{modelUrl:r.modelUrl}},graphQlClient:{},workflow:r.workflow,reloadedState:r.reloadedState})}exports.AddonHandle=Bg;exports.AddressValidationJobStatus=ZP;exports.AddressValidationResultConfirmationLevel=KP;exports.AddressValidationStatus=Og;exports.ArrayInput=wV;exports.AspectType=Hn;exports.AssetNotFoundError=So;exports.AssetType=ff;exports.BringForwardCommand=PL;exports.BringToBackCommand=IL;exports.BringToFrontCommand=FL;exports.BundleDesignCreationCartAddMode=Uk;exports.CanvasCommand=bn;exports.CollectionProduct=Pu;exports.ColorOptionGlobalPropertyHandle=pA;exports.CommandContext=WF;exports.ConversionDataType=Qd;exports.CreateElementCommand=ai;exports.CreateLayoutCommand=k1;exports.CurrencyContext=UP;exports.CurrencyService=LP;exports.DeleteElementCommand=Ol;exports.DigitalContentStepHandle=kI;exports.FileUploadGlobalPropertyHandle=RI;exports.FlowExecutionNodeResult=Vd;exports.FlowExecutionResult=LI;exports.FlowService=NI;exports.FontAlignmentCommand=KF;exports.FontColorCommand=lA;exports.FontSizeCommand=JF;exports.FontSourceCommand=uA;exports.FrameService=WP;exports.FrameStep=QP;exports.FrameStepHandle=XP;exports.GlobalPropertyHandle=Jg;exports.GroupCommand=In;exports.IllustrationStepHandle=yI;exports.ImageState=YP;exports.InformationMessageType=Jf;exports.InformationStepHandle=EI;exports.IntegrationProduct=mA;exports.IntegrationType=zk;exports.LayoutElementFactory=wL;exports.LayoutElementType=er;exports.LayoutNotFoundError=Ai;exports.LayoutRenderingPurpose=Ku;exports.MaterialStepHandle=AI;exports.MisconfigurationError=as;exports.MockWorkflowManager=JQ;exports.ModelStepHandle=wI;exports.ModuleStepHandle=TI;exports.MoveCommand=bL;exports.ObjectInput=U1;exports.ObjectInputType=UI;exports.OptionGlobalPropertyHandle=_1;exports.OptionNotFoundError=hf;exports.ParseError=Al;exports.PictureStepHandle=bI;exports.ProductCameraRig=$k;exports.ProductCollection=N1;exports.ProductCollectionProductSortKey=_I;exports.ProductStepHandle=FI;exports.ProductWorkflow=oo;exports.PromiseQueue=Gg;exports.QuestionStepHandle=CI;exports.QueueablePromise=jg;exports.ResizeCommand=xL;exports.ResourceNotFoundError=Zu;exports.RotateCommand=CL;exports.ScaleAxis=gi;exports.SendBackwardsCommand=DL;exports.ShapeStepHandle=xI;exports.ShareActionType=Vk;exports.SpiffCommerceClient=$Q;exports.StakeholderType=qA;exports.StepAspectType=Lk;exports.StepHandle=Ui;exports.StepType=Xe;exports.TextAlgorithm=Fl;exports.TextChangeCommand=ZF;exports.TextGlobalPropertyHandle=OI;exports.TextInput=AV;exports.TextStepHandle=SI;exports.UnhandledBehaviorError=nn;exports.UnitOfMeasurement=Hk;exports.UpdateElementRegionCommand=eI;exports.UpdateImageSourceCommand=kL;exports.Variant=Fa;exports.WorkflowExperienceEventType=yg;exports.WorkflowExperienceImpl=M1;exports.__values=lD;exports.amtChannelsForAspect=BI;exports.assetConfigurationDeleteMutation=iM;exports.assetConfigurationUpdateMutation=nM;exports.assetConfigurationsQuery=rM;exports.assetService=Ln;exports.browserColorToHex=cT;exports.bundleEmailMutation=I9;exports.cmPerPixel=K_;exports.createLocalWorkflowExperience=DY;exports.currentDirection=Y_;exports.dataUrlFromExternalUrl=$4;exports.deleteBundle=YQ;exports.designService=Qp;exports.determineCorrectFontSizeAndLines=Kd;exports.digitalContentStepService=F1;exports.domParser=us;exports.duplicateBundle=lY;exports.duplicateTransaction=uY;exports.fetchAsString=ra;exports.findAngle=$_;exports.findElement=Un;exports.findPmsColors=s3;exports.frameDataCache=_u;exports.frameStepService=so;exports.fromHex=WI;exports.fromUtf8=kl;exports.generate=hr;exports.generateCommands=dI;exports.generateSVGWithUnknownColors=Pa;exports.generateStateFromDesignInputSteps=YU;exports.getActivation=HP;exports.getActivationThemeConfiguration=WQ;exports.getAddressValidationJobs=SY;exports.getAssetsForProductImagesQuery=aM;exports.getAttributesFromArrayBuffer=_f;exports.getAxisAlignedBoundingBox=z_;exports.getBoundedOffsets=qP;exports.getBundleIdForTransaction=XQ;exports.getBundleThemeConfiguration=GQ;exports.getCustomer=cY;exports.getCustomerBundles=dY;exports.getElementVertices=X_;exports.getFrameData=Xf;exports.getGlobalPropertyStateForBundle=ZU;exports.getIntegration=$P;exports.getIntegrationProducts=PY;exports.getLayoutCanvasSize=hI;exports.getNEPoint=W_;exports.getNWPoint=q_;exports.getOrderedTransactions=pY;exports.getOverrideThemeConfiguration=jQ;exports.getPointOfRotation=G_;exports.getProductCollections=hV;exports.getSEPoint=Q_;exports.getSvgElement=Qg;exports.getTemplateBundles=mY;exports.getTemplateTransactions=gY;exports.getTransaction=HQ;exports.getTransactionThemeConfiguration=qQ;exports.getTransactionsForBundle=fY;exports.getTransformedAssetURL=$g;exports.getTrueCoordinates=j_;exports.getUnorderedTransactions=hY;exports.getValidationJobsForWorkflowExperiences=xY;exports.getWorkflow=VP;exports.getWorkflows=tb;exports.graphQlManager=ze;exports.illustrationStepService=Jd;exports.isCloseToValue=H_;exports.loadFont=Rl;exports.matchHexToPms=n3;exports.materialStepService=I1;exports.mergeColorClasses=pT;exports.metafieldManager=Ag;exports.mmPerPixel=J_;exports.modelStepService=P1;exports.modifySVGColors=zg;exports.moduleStepService=D1;exports.nameBundle=sY;exports.nameTransaction=oY;exports.nonPotTexSupport=fI;exports.optionService=ct;exports.outlineFontsInSvg=I7;exports.overrideWorkflowExperienceRecipientAddress=TY;exports.patternImageDataCache=Ds;exports.persistenceService=br;exports.pictureStepService=R1;exports.pmsToRgb=r3;exports.promiseCache=mf;exports.questionStepService=O1;exports.registerFetchImplementation=N4;exports.registerWindowImplementation=_4;exports.rehydrateSerializedLayout=oA;exports.rgbToPms=uT;exports.rotateAroundPoint=Ld;exports.sanitizeSvgTree=Vg;exports.setApplicationKey=Jk;exports.setBearerAuthenticationToken=Zk;exports.setCanvasModule=QA;exports.shapeStepService=Nu;exports.shortenUrl=sI;exports.skipWorkflowExperienceRecipientAddress=FY;exports.spiffCoreConfiguration=ss;exports.stepAspectValuesToDesignInputSteps=QU;exports.svgColorValueToDefinition=Hy;exports.svgStringDimensions=E1;exports.svgToDataUrl=Ug;exports.textStepService=ri;exports.toHex=Ao;exports.toUtf8=em;exports.toast=lI;exports.validateWorkflowExperienceRecipient=EY;exports.validateWorkflowExperienceRecipients=kY;exports.xmlSerializer=Do;
3269
- //# sourceMappingURL=index-6qldwBYr.cjs.map
3269
+ //# sourceMappingURL=index-BdUHDH9C.cjs.map