@spiffcommerce/core 33.5.3 → 33.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -6082,4 +6082,6 @@ declare const overrideWorkflowExperienceRecipientAddress: (workflowExperience: W
6082
6082
  */
6083
6083
  declare const getGlobalPropertyStateForBundle: (bundleId: string) => Promise<GlobalPropertyState | undefined>;
6084
6084
 
6085
- export { AddonHandle, type AddressComponent, type AddressValidationJob, AddressValidationJobStatus, type AddressValidationResult, AddressValidationResultConfirmationLevel, AddressValidationStatus, type Animatable, type AnyStepData, ArrayInput, AspectType, type Asset, type AssetConfiguration, AssetNotFoundError, type AssetObjectVersion, AssetType, BringForwardCommand, BringToBackCommand, BringToFrontCommand, type Bundle$1 as Bundle, BundleDesignCreationCartAddMode, type BundleDesignCreationMessage, type BundleEvent, type BundleEventData, type BundleEventType, type Bundle as BundleRaw, type BundleStakeholder, CanvasCommand, CollectionProduct, type ColorDefinition, type ColorOption, ColorOptionGlobalPropertyHandle, type ColorProfileProps, CommandContext, type CommandState, type Condition, type ConditionalGlobalPropertiesChangedEventData, CreateElementCommand, CreateLayoutCommand, CurrencyContext, CurrencyService, type Customer, type CustomerDetailsInput, DeleteElementCommand, type DesignCreationMessage, type DesignCreationProgressUpdate, type DesignInputStep, type DigitalContentStepData, DigitalContentStepHandle, type EditedSteps, type ExportedStepData, type ExportedStepDataProperty, type ExportedStepDataPropertyType, FileUploadGlobalPropertyHandle, FlowExecutionNodeResult, FlowExecutionResult, FlowService, FontAlignmentCommand, FontColorCommand, FontSizeCommand, FontSourceCommand, type FrameElement, FrameService, FrameStep, type FrameStepData, FrameStepHandle, type FrameThresholdSettings, type GetNewWorkflowExperienceOptions as GetNewWorkflowOptions, type GetWorkflowOptions, type GlobalPropertiesMandatoryChangedEventData, type GlobalPropertyConfiguration, GlobalPropertyHandle, GroupCommand, type ILayout, type IllustrationElement, type IllustrationStepData, IllustrationStepHandle, type ImageElement, InformationMessageType, type InformationResult, type InformationStepData, InformationStepHandle, type Integration, type IntegrationOptionResource, IntegrationProduct, IntegrationType, type LayoutComponentConfiguration, type LayoutData, type LayoutElement, LayoutElementFactory, LayoutElementType, LayoutNotFoundError, LayoutRenderingPurpose, type LayoutState, type LayoutsState, type MandatorySteps, MaterialEffectMode, type MaterialStepData, MaterialStepHandle, MisconfigurationError, MockWorkflowManager, type ModelStepData, ModelStepHandle, type ModuleStepData, ModuleStepHandle, MoveCommand, NodeType, ObjectInput, ObjectInputType, OptionGlobalPropertyHandle, OptionNotFoundError, type OptionResource, type Order, type OrderItem, type PapyrusComponent, ParseError, type PictureStepData, PictureStepHandle, type Placeable, type PmsSearchResult, type Point, type Product, ProductCameraRig, ProductCollection, ProductCollectionProductSortKey, ProductWorkflow$1 as ProductWorkflow, promiseCache as PromiseCache, PromiseQueue, type QuestionStepData, QuestionStepHandle, QueueablePromise, type Recipient, type Region, type RegionElement, type RenderableScene, ResizeCommand, ResourceNotFoundError, RotateCommand, type SavedDesign, ScaleAxis, type SelectionStorage, SendBackwardsCommand, type ShapeStepData, ShapeStepHandle, type ShareAction, ShareActionType, type SilentIllustrationStepData, SpiffCommerceClient, type Stakeholder, StakeholderType, type StateMutationFunc, type Step, type StepAspect, StepAspectType, type StepElements, type StepGroup, StepHandle, type StepStorage, StepType, TextAlgorithm, TextChangeCommand, type TextChangeResult, TextGlobalPropertyHandle, TextInput, type TextStepData, TextStepHandle, type TextStepStorage, type TextboxElement, type Theme, type ToastCallback, type Transaction, Transform, TransformCollection$1 as TransformCollection, UnhandledBehaviorError, UnitOfMeasurement, UpdateImageSourceCommand, Variant, type VariantResource, type Vector3, type Workflow, type WorkflowExperience, WorkflowExperienceEventType, type WorkflowExperienceHoverEventData, WorkflowExperienceImpl, type WorkflowManager, type WorkflowMetadata, type WorkflowPanel, type WorkflowScene, type WorkflowSelections, type WorkflowStorage, assetService, browserColorToHex, cmPerPixel, createDesign, currentDirection, dataUrlFromExternalUrl, deleteBundle, designService, determineCorrectFontSizeAndLines, digitalContentStepService, domParser, duplicateBundle, duplicateTransaction, fetchAsString, findAngle, findElement, findPmsColors, frameDataCache, frameStepService, generate, generateCommands, generateSVGWithUnknownColors, generateStateFromDesignInputSteps, getAddressValidationJobs, getAttributesFromArrayBuffer, getAxisAlignedBoundingBox, getBoundedOffsets, getBundleThemeConfiguration, getCustomer, getCustomerBundles, getElementVertices, getFrameData, getGlobalPropertyStateForBundle, getIntegration, getNEPoint, getNWPoint, getOrderedTransactions, getOverrideThemeConfiguration, getPointOfRotation, getProductCollections, getSEPoint, getSvgElement, getTemplateBundles, getTemplateTransactions, getTransaction, getTransactionThemeConfiguration, getTransactionsForBundle, getTrueCoordinates, getUnorderedTransactions, getValidationJobsForWorkflowExperiences, getWorkflow, getWorkflows, graphQlManager, illustrationStepService, isCloseToValue, loadFont, matchHexToPms, materialStepService, metafieldManager, mmPerPixel, modelStepService, modifySVGColors, moduleStepService, nameBundle, nameTransaction, optionService, outlineFontsInSvg, overrideWorkflowExperienceRecipientAddress, patternImageDataCache, persistenceService, pictureStepService, pmsToRgb, questionStepService, registerFetchImplementation, registerWindowImplementation, rehydrateSerializedLayout, rgbToPms, rotateAroundPoint, sanitizeSvgTree, setBearerAuthenticationToken, setCanvasModule, shapeStepService, shortenUrl, spiffCoreConfiguration, stepAspectValuesToDesignInputSteps, svgColorValueToDefinition, svgStringDimensions, svgToDataUrl, textStepService, toast, validateWorkflowExperienceRecipient, validateWorkflowExperienceRecipients, xmlSerializer };
6085
+ declare const getIntegrationProducts: (ids: string[]) => Promise<IntegrationProductResource[]>;
6086
+
6087
+ export { AddonHandle, type AddressComponent, type AddressValidationJob, AddressValidationJobStatus, type AddressValidationResult, AddressValidationResultConfirmationLevel, AddressValidationStatus, type Animatable, type AnyStepData, ArrayInput, AspectType, type Asset, type AssetConfiguration, AssetNotFoundError, type AssetObjectVersion, AssetType, BringForwardCommand, BringToBackCommand, BringToFrontCommand, type Bundle$1 as Bundle, BundleDesignCreationCartAddMode, type BundleDesignCreationMessage, type BundleEvent, type BundleEventData, type BundleEventType, type Bundle as BundleRaw, type BundleStakeholder, CanvasCommand, CollectionProduct, type ColorDefinition, type ColorOption, ColorOptionGlobalPropertyHandle, type ColorProfileProps, CommandContext, type CommandState, type Condition, type ConditionalGlobalPropertiesChangedEventData, CreateElementCommand, CreateLayoutCommand, CurrencyContext, CurrencyService, type Customer, type CustomerDetailsInput, DeleteElementCommand, type DesignCreationMessage, type DesignCreationProgressUpdate, type DesignInputStep, type DigitalContentStepData, DigitalContentStepHandle, type EditedSteps, type ExportedStepData, type ExportedStepDataProperty, type ExportedStepDataPropertyType, FileUploadGlobalPropertyHandle, FlowExecutionNodeResult, FlowExecutionResult, FlowService, FontAlignmentCommand, FontColorCommand, FontSizeCommand, FontSourceCommand, type FrameElement, FrameService, FrameStep, type FrameStepData, FrameStepHandle, type FrameThresholdSettings, type GetNewWorkflowExperienceOptions as GetNewWorkflowOptions, type GetWorkflowOptions, type GlobalPropertiesMandatoryChangedEventData, type GlobalPropertyConfiguration, GlobalPropertyHandle, GroupCommand, type ILayout, type IllustrationElement, type IllustrationStepData, IllustrationStepHandle, type ImageElement, InformationMessageType, type InformationResult, type InformationStepData, InformationStepHandle, type Integration, type IntegrationOptionResource, IntegrationProduct, IntegrationType, type LayoutComponentConfiguration, type LayoutData, type LayoutElement, LayoutElementFactory, LayoutElementType, LayoutNotFoundError, LayoutRenderingPurpose, type LayoutState, type LayoutsState, type MandatorySteps, MaterialEffectMode, type MaterialStepData, MaterialStepHandle, MisconfigurationError, MockWorkflowManager, type ModelStepData, ModelStepHandle, type ModuleStepData, ModuleStepHandle, MoveCommand, NodeType, ObjectInput, ObjectInputType, OptionGlobalPropertyHandle, OptionNotFoundError, type OptionResource, type Order, type OrderItem, type PapyrusComponent, ParseError, type PictureStepData, PictureStepHandle, type Placeable, type PmsSearchResult, type Point, type Product, ProductCameraRig, ProductCollection, ProductCollectionProductSortKey, ProductWorkflow$1 as ProductWorkflow, promiseCache as PromiseCache, PromiseQueue, type QuestionStepData, QuestionStepHandle, QueueablePromise, type Recipient, type Region, type RegionElement, type RenderableScene, ResizeCommand, ResourceNotFoundError, RotateCommand, type SavedDesign, ScaleAxis, type SelectionStorage, SendBackwardsCommand, type ShapeStepData, ShapeStepHandle, type ShareAction, ShareActionType, type SilentIllustrationStepData, SpiffCommerceClient, type Stakeholder, StakeholderType, type StateMutationFunc, type Step, type StepAspect, StepAspectType, type StepElements, type StepGroup, StepHandle, type StepStorage, StepType, TextAlgorithm, TextChangeCommand, type TextChangeResult, TextGlobalPropertyHandle, TextInput, type TextStepData, TextStepHandle, type TextStepStorage, type TextboxElement, type Theme, type ToastCallback, type Transaction, Transform, TransformCollection$1 as TransformCollection, UnhandledBehaviorError, UnitOfMeasurement, UpdateImageSourceCommand, Variant, type VariantResource, type Vector3, type Workflow, type WorkflowExperience, WorkflowExperienceEventType, type WorkflowExperienceHoverEventData, WorkflowExperienceImpl, type WorkflowManager, type WorkflowMetadata, type WorkflowPanel, type WorkflowScene, type WorkflowSelections, type WorkflowStorage, assetService, browserColorToHex, cmPerPixel, createDesign, currentDirection, dataUrlFromExternalUrl, deleteBundle, designService, determineCorrectFontSizeAndLines, digitalContentStepService, domParser, duplicateBundle, duplicateTransaction, fetchAsString, findAngle, findElement, findPmsColors, frameDataCache, frameStepService, generate, generateCommands, generateSVGWithUnknownColors, generateStateFromDesignInputSteps, getAddressValidationJobs, getAttributesFromArrayBuffer, getAxisAlignedBoundingBox, getBoundedOffsets, getBundleThemeConfiguration, getCustomer, getCustomerBundles, getElementVertices, getFrameData, getGlobalPropertyStateForBundle, getIntegration, getIntegrationProducts, getNEPoint, getNWPoint, getOrderedTransactions, getOverrideThemeConfiguration, getPointOfRotation, getProductCollections, getSEPoint, getSvgElement, getTemplateBundles, getTemplateTransactions, getTransaction, getTransactionThemeConfiguration, getTransactionsForBundle, getTrueCoordinates, getUnorderedTransactions, getValidationJobsForWorkflowExperiences, getWorkflow, getWorkflows, graphQlManager, illustrationStepService, isCloseToValue, loadFont, matchHexToPms, materialStepService, metafieldManager, mmPerPixel, modelStepService, modifySVGColors, moduleStepService, nameBundle, nameTransaction, optionService, outlineFontsInSvg, overrideWorkflowExperienceRecipientAddress, patternImageDataCache, persistenceService, pictureStepService, pmsToRgb, questionStepService, registerFetchImplementation, registerWindowImplementation, rehydrateSerializedLayout, rgbToPms, rotateAroundPoint, sanitizeSvgTree, setBearerAuthenticationToken, setCanvasModule, shapeStepService, shortenUrl, spiffCoreConfiguration, stepAspectValuesToDesignInputSteps, svgColorValueToDefinition, svgStringDimensions, svgToDataUrl, textStepService, toast, validateWorkflowExperienceRecipient, validateWorkflowExperienceRecipients, xmlSerializer };
package/dist/index.js CHANGED
@@ -2653,7 +2653,7 @@
2653
2653
  }
2654
2654
  }
2655
2655
  }
2656
- `;class Mc{constructor(t,e=S.getShadowGraphqlClient.bind(S)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Tc{init(t,e,a){this.cognitoClient=new we.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new we.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Tc;class Jr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Ci(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Za.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Za.code(e)?.code==="CLP")return"USD0,0"}}const fn=new Jr;class Kr{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,fn.getPrecisionForCurrency(e))}}const Nc=async(n,t)=>{const e=await S.getShadowGraphqlClient().query({query:To(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&O.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&O.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&O.cacheAsset(o.asset),o.thumbnail&&O.cacheAsset(o.thumbnail),o.material&&O.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},Qc=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},Ja=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=Nc(a,t),i=a.map(s=>$t.set({id:s,options:t},Qc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},_r=async(n,t)=>(await Ja([n],t))[0];class Rc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return S.getShadowGraphqlClient().mutate({...e,mutation:wo})}catch(a){throw console.error(a),new gt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ri(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 33.5.3"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ut.setHubUrl(t.hubUrl),ut.setServerUrl(t.serverUrl),ut.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Vn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return O}getFlowService(){if(!Oi())throw new Error("Application key required to use Flow Service.");return new Wr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await S.getShadowGraphqlClient().query({query:Vo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new Kr(o,s,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Xr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}async authenticateBundleFromLocalStorage(t){if(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=S.getShadowGraphqlClient(),a=await e.query({query:No,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const A=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(A)return Promise.resolve({success:!0,stakeholderType:A.type})}const c=(await e.query({query:Qo,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await S.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=S.getShadowGraphqlClient(),r=(await e.query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:Fc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await S.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await S.getShadowGraphqlClient().mutate({mutation:Dc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await jt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await S.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),r=new Date().getTime()/1e3,i=!a?.AccessToken||oe(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await S.getShadowGraphqlClient().query({query:kc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await S.getShadowGraphqlClient().mutate({mutation:Bl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!i?.id)throw new Error("Unable to create bundle");const o=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new ra(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const p=Object.entries(localStorage).find(([f,w])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",m=localStorage.getItem(p);m&&!oe(m)&&(s.Authorization=`Bearer ${m}`)}const l={bundleOwnerId:o,...s,...r?.graphql?.additionalHeaders},c=await S.getShadowGraphqlClient().query({query:Sl(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],u=k.getMap("bundlePartnerIds")||new Map;u.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",u);const A=new ra(this,d,e,a,o,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:r?.readonly});return await A.getInitializationPromise(),A}async duplicateBundle(t,e,a,r){const o={...await Zr(t),...r?.graphql?.additionalHeaders},l=(await S.getShadowGraphqlClient().mutate({mutation:Pl(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=k.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),k.setMap("bundlePartnerIds",c);const d=k.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),k.setMap("bundleOwnerIds",d),async()=>{const u=new ra(this,l,void 0,void 0,l.bundleOwnerId,{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:l.globalPropertyState});return await u.getInitializationPromise(),u}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await S.getShadowGraphqlClient().query({query:$l(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await S.getShadowGraphqlClient().query({query:vl,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],r=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",r),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),r=a[0],i=r.getWorkflow();return e&&!i&&console.error("No workflow instantiated when trying to create preview service."),e&&i&&await r.getWorkflowManager().injectIntoPreviewService(e(i)),a[0]}async getWorkflowExperiences(t,e,a){if(t.length===0)throw new gt("No options provided!");const r=S.getShadowGraphqlClient(),i=async y=>{if(y.length===0)return[];const I=y.map(T=>T.option.transactionId),x=await r.query({query:Co,variables:{ids:I},errorPolicy:"all",fetchPolicy:"no-cache"}),B=x.data.transactions;if(B.length!==y.length){const T=x.errors?.[0]?.message||"Unknown error";throw new gt(`Not all transactions were found: ${T}`)}return!this.activeIntegration&&B[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(B[0].integrationProduct.integration)),B.map((T,V)=>({transaction:T,workflowId:T.workflowId,readOnly:y.find(H=>H.option.transactionId===T.id)?.option.readOnly??!1,index:y[V].index}))},o=async y=>{if(y.length===0)return[];const I=await r.mutate({mutation:fo,variables:{inputs:y.map(B=>({integrationProductId:B.option.type==="integration"?B.option.integrationProductId:void 0,externalIntegrationId:B.option.type==="external"?B.option.externalIntegrationId:void 0,externalProductId:B.option.type==="external"?B.option.externalProductId:void 0,workflowId:B.option.workflowId,designName:B.option.designName,claim:!0,quantity:B.option.quantity,recipient:B.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),x=I.data?.transactionCreateMany;if(!x||x.length===0){const B=I.errors?.[0]?.message||"Unknown error";throw new gt(`Failed to create transactions: ${B}`)}return x.map((B,T)=>({transaction:B,workflowId:B.workflowId,readOnly:!1,index:y[T].index}))},s=t.map((y,I)=>({option:y,index:I})),l=s.filter(y=>y.option.type==="transaction"),c=s.filter(y=>y.option.type==="integration"||y.option.type==="external"||y.option.type==="blank"),d=50,u=Xa(l,d),A=Xa(c,d),h=(await Promise.all([...u.map(i),...A.map(o)])).flat(),g=[...new Set(h.map(y=>y.workflowId))].filter(y=>y!==void 0),p=g.length>0?await Ja(g,e):[],m=new Map(p.map(y=>[y.id,y])),f=k.getMap("transactionOwnerIds")||new Map,w=h.map(async y=>{const{transaction:I,workflowId:x,readOnly:B,index:T}=y,V=x?m.get(x):void 0,H=t[T];!f.get(I.id)&&I.transactionOwnerId&&f.set(I.id,I.transactionOwnerId);const _=f.get(I.id)||void 0,St=new Mc({onMutate:()=>({context:{transactionOwnerId:_,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:_,bundleOwnerId:e?.bundleOwnerId}})}),et={workflow:V,transaction:I,singleVariantsRenderable:H?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:B?async()=>{throw new N("State mutation is forbidden in read only mode!")}:async nt=>this.updateTransactionState({...nt,context:{transactionOwnerId:_,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>St,readOnly:B,isReloadedTransaction:H.type==="transaction"};if(H.type==="transaction"&&I.workflowState){const nt=JSON.parse(I.workflowState);await fa(nt),et.reloadedState=nt}else if(!B&&H.workflowState){const nt=JSON.parse(H.workflowState);await fa(nt),et.reloadedState=nt}return et.delayWorkflowStateSync=!0,{experienceOptions:et,index:T,options:H}}),b=await Promise.all(w);k.setMap("transactionOwnerIds",f);const F=b.sort((y,I)=>y.index-I.index);let E=[];for(const y of F){const{experienceOptions:I,options:x}=y,B=new $r(this,I);await B.getWorkflowManager().getInitializationPromise(),a&&a(),x.type!=="transaction"&&this.customer&&await B.attachCustomerDetails({email:this.customer.emailAddress}),E=[...E,B],B.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return E}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await S.getShadowGraphqlClient().query({query:Io(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new va(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await S.getShadowGraphqlClient().query({query:Bo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new va(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await S.getShadowGraphqlClient().query({query:bo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await S.getShadowGraphqlClient().mutate({mutation:Lo,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const Xr=async(n,t)=>(await S.getShadowGraphqlClient().query({query:Oo,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,Oc=async n=>{const e=await S.getShadowGraphqlClient().query({query:Eo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},$c=async(n,t)=>(await S.getShadowGraphqlClient().query({query:Ro,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,Uc=async n=>(await S.getShadowGraphqlClient().query({query:Uo,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Lc=async n=>(await S.getShadowGraphqlClient().query({query:$o,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function Zr(n){const e=k.getMap("bundleOwnerIds")?.get(n),a={};try{const r=await this.loggedInBearerToken();a.Authorization=`Bearer ${r}`}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!oe(s)&&(a.Authorization=`Bearer ${s}`)}return{bundleOwnerId:e,...a}}const Vc=async n=>{const t=await Zr(n),e=await S.getShadowGraphqlClient().mutate({mutation:Hl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)};function ti(n,t,e,a){const r=e.width*n.zoom,i=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Be(n.x,t.width-c,0),s.y=Be(n.y,t.height-d,0),s}const o=n;return o.x=Be(o.x,-r,t.width),o.y=Be(o.y,-i,t.height),o}function Be(n,t,e){return Math.min(Math.max(n,t),e)}class ei{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Pn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;Zt(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const r=Dt.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=ze(this.imageData.svg,this.imageData.colors||{},!1);return Ve(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new N("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=ti(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,r,i){if(!a||a.length===0||a.some(s=>!s))throw new N("Frame data not set. This is a bug");if(!this.workflowManager)throw new N("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new R([new Is(s,e,t[l]),new Bs(s,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,r)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Na(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class qc{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,g,p,m,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var ai=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(ai||{});class ni extends X{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new ei(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await ht.selectImage(this.step,t,this.manager,a),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Re.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await O.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,r){return r&&r.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return O.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return O.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const zc=C.gql`
2656
+ `;class Mc{constructor(t,e=S.getShadowGraphqlClient.bind(S)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class Tc{init(t,e,a){this.cognitoClient=new we.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){const e=await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}}));e?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){const r=await this.cognitoClient?.send(new we.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}}));return r?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=r.Session),r}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const jt=new Tc;class Jr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Ci(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Za.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(Za.code(e)?.code==="CLP")return"USD0,0"}}const fn=new Jr;class Kr{constructor(t,e,a,r){this.presentmentCurrency=void 0,this.presentmentCurrency=r,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,fn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,fn.getPrecisionForCurrency(e))}}const Nc=async(n,t)=>{const e=await S.getShadowGraphqlClient().query({query:To(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(r=>console.error(r)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(r=>{r.steps.forEach(i=>{delete i.data.__typename,i.option?.id&&(i.option.defaultVariant?.asset&&O.cacheAsset(i.option.defaultVariant.asset),i.option.colorProfile&&O.cacheAsset(i.option.colorProfile),i.option.variants?.forEach(o=>{o.asset&&O.cacheAsset(o.asset),o.thumbnail&&O.cacheAsset(o.thumbnail),o.material&&O.cacheMaterial(o.material)}),$t.set({id:i.option.id},Promise.resolve(i.option)))}),r.finalizeStepConfig||(r.finalizeStepConfig={}),r.finalizeStepConfig.termsMarkdown=r.finalizeStepConfig.termsMarkdown||r.partner.termsMarkdown}),a},Qc=async(n,t)=>{const a=(await t).find(r=>r.id===n);if(!a)throw new Error(`Workflow not found: ${n}`);return a},Ja=async(n,t)=>{const e=n.map(s=>$t.get({id:s,options:t})),a=n.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const r=Nc(a,t),i=a.map(s=>$t.set({id:s,options:t},Qc(s,r))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(i))},_r=async(n,t)=>(await Ja([n],t))[0];class Rc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return S.getShadowGraphqlClient().mutate({...e,mutation:wo})}catch(a){throw console.error(a),new gt("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ri(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 33.6.0"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){ut.setHubUrl(t.hubUrl),ut.setServerUrl(t.serverUrl),ut.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Vn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&jt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return O}getFlowService(){if(!Oi())throw new Error("Application key required to use Flow Service.");return new Wr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await S.getShadowGraphqlClient().query({query:Vo,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=i.data.currencyConversion;return new Kr(o,s,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Xr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){try{return(await this.getIntegration()).partner.activeAddons?.includes(t)??!1}catch(e){return console.error(e),!1}}async authenticateBundleFromLocalStorage(t){if(k.getMap("bundleOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const a=k.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const r=a.get(t);if((k.getMap("partnerCustomerIds")||new Map).get(r)&&await this.reloadLoggedInCustomer()){const l=this.customer?.bundleStakeholders?.find(c=>c.bundle?.id===t);if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){const e=S.getShadowGraphqlClient(),a=await e.query({query:No,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const r=a.data.transactions[0];if(!r.product?.partner?.id)throw new Error(`Unable to read transaction: ${t}`);if(r.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});if(k.getMap("transactionOwnerIds")?.has(t))return Promise.resolve({success:!0,stakeholderType:ee.Owner});const s=k.getMap("transactionCustomerIds");if(s?.has(t)&&s.get(t)&&await this.reloadLoggedInCustomer()){const A=this.customer?.bundleStakeholders?.find(h=>h.bundle?.transactions?.some(g=>g.id===t))||this.customer?.stakeholders?.find(h=>h.transaction?.id===t);if(A)return Promise.resolve({success:!0,stakeholderType:A.type})}const c=(await e.query({query:Qo,errorPolicy:"all",variables:{id:r.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${r.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:r.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=k.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),k.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const r=(await S.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return r.id?r.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=S.getShadowGraphqlClient(),r=(await e.query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!r.id){const s=(await e.mutate({mutation:Fc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(r);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||r,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const r=JSON.parse(e),i=new Date().getTime()/1e3;if(!r.ExpiresIn||r.ExpiresIn<i-parseInt(t)){const l=await jt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),r.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(r));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await S.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await S.getShadowGraphqlClient().mutate({mutation:Dc,variables:{emailAddress:t}}),await jt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",r=await jt.verifyCode(t,e,a);if(r?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(r.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await S.getShadowGraphqlClient().query({query:Ie,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),r=new Date().getTime()/1e3,i=!a?.AccessToken||oe(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<r-parseInt(t)||i){const o=await jt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await S.getShadowGraphqlClient().query({query:kc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const i=(await S.getShadowGraphqlClient().mutate({mutation:Bl(a?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((c,d)=>({key:c[0],value:c[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data?.bundleCreate;if(!i?.id)throw new Error("Unable to create bundle");const o=k.getMap("bundlePartnerIds")||new Map;o.set(i.id,i.partner.id),k.setMap("bundlePartnerIds",o);const s=k.getMap("bundleOwnerIds")||new Map;s.set(i.id,i.bundleOwnerId),k.setMap("bundleOwnerIds",s);const l=new ra(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,r){const o=k.getMap("bundleOwnerIds")?.get(t),s={};try{const h=await this.loggedInBearerToken();s.Authorization=`Bearer ${h}`}catch{const p=Object.entries(localStorage).find(([f,w])=>f.startsWith("CognitoIdentityServiceProvider")&&f.endsWith("idToken"))?.[0]||"",m=localStorage.getItem(p);m&&!oe(m)&&(s.Authorization=`Bearer ${m}`)}const l={bundleOwnerId:o,...s,...r?.graphql?.additionalHeaders},c=await S.getShadowGraphqlClient().query({query:Sl(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!c.data?.bundles||c.data?.bundles.length===0||!c.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const d=c.data?.bundles[0],u=k.getMap("bundlePartnerIds")||new Map;u.set(d.id,d.partner.id),k.setMap("bundlePartnerIds",u);const A=new ra(this,d,e,a,o,{additionalHeaders:r?.graphql?.additionalHeaders,eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:r?.readonly});return await A.getInitializationPromise(),A}async duplicateBundle(t,e,a,r){const o={...await Zr(t),...r?.graphql?.additionalHeaders},l=(await S.getShadowGraphqlClient().mutate({mutation:Pl(r?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data?.bundleDuplicate;if(!l?.id)throw new Error("Unable to duplicate bundle");const c=k.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),k.setMap("bundlePartnerIds",c);const d=k.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),k.setMap("bundleOwnerIds",d),async()=>{const u=new ra(this,l,void 0,void 0,l.bundleOwnerId,{eagerFetchProducts:r?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:l.globalPropertyState});return await u.getInitializationPromise(),u}}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await S.getShadowGraphqlClient().query({query:$l(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await S.getShadowGraphqlClient().query({query:vl,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],r=k.getMap("bundlePartnerIds")||new Map;return a.forEach(i=>{i.bundle?.id&&i.bundle.partner?.id&&r.set(i.bundle.id,i.bundle.partner.id)}),k.setMap("bundlePartnerIds",r),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),r=a[0],i=r.getWorkflow();return e&&!i&&console.error("No workflow instantiated when trying to create preview service."),e&&i&&await r.getWorkflowManager().injectIntoPreviewService(e(i)),a[0]}async getWorkflowExperiences(t,e,a){if(t.length===0)throw new gt("No options provided!");const r=S.getShadowGraphqlClient(),i=async y=>{if(y.length===0)return[];const I=y.map(T=>T.option.transactionId),x=await r.query({query:Co,variables:{ids:I},errorPolicy:"all",fetchPolicy:"no-cache"}),B=x.data.transactions;if(B.length!==y.length){const T=x.errors?.[0]?.message||"Unknown error";throw new gt(`Not all transactions were found: ${T}`)}return!this.activeIntegration&&B[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(B[0].integrationProduct.integration)),B.map((T,V)=>({transaction:T,workflowId:T.workflowId,readOnly:y.find(H=>H.option.transactionId===T.id)?.option.readOnly??!1,index:y[V].index}))},o=async y=>{if(y.length===0)return[];const I=await r.mutate({mutation:fo,variables:{inputs:y.map(B=>({integrationProductId:B.option.type==="integration"?B.option.integrationProductId:void 0,externalIntegrationId:B.option.type==="external"?B.option.externalIntegrationId:void 0,externalProductId:B.option.type==="external"?B.option.externalProductId:void 0,workflowId:B.option.workflowId,designName:B.option.designName,claim:!0,quantity:B.option.quantity,recipient:B.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),x=I.data?.transactionCreateMany;if(!x||x.length===0){const B=I.errors?.[0]?.message||"Unknown error";throw new gt(`Failed to create transactions: ${B}`)}return x.map((B,T)=>({transaction:B,workflowId:B.workflowId,readOnly:!1,index:y[T].index}))},s=t.map((y,I)=>({option:y,index:I})),l=s.filter(y=>y.option.type==="transaction"),c=s.filter(y=>y.option.type==="integration"||y.option.type==="external"||y.option.type==="blank"),d=50,u=Xa(l,d),A=Xa(c,d),h=(await Promise.all([...u.map(i),...A.map(o)])).flat(),g=[...new Set(h.map(y=>y.workflowId))].filter(y=>y!==void 0),p=g.length>0?await Ja(g,e):[],m=new Map(p.map(y=>[y.id,y])),f=k.getMap("transactionOwnerIds")||new Map,w=h.map(async y=>{const{transaction:I,workflowId:x,readOnly:B,index:T}=y,V=x?m.get(x):void 0,H=t[T];!f.get(I.id)&&I.transactionOwnerId&&f.set(I.id,I.transactionOwnerId);const _=f.get(I.id)||void 0,St=new Mc({onMutate:()=>({context:{transactionOwnerId:_,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:_,bundleOwnerId:e?.bundleOwnerId}})}),et={workflow:V,transaction:I,singleVariantsRenderable:H?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:B?async()=>{throw new N("State mutation is forbidden in read only mode!")}:async nt=>this.updateTransactionState({...nt,context:{transactionOwnerId:_,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>St,readOnly:B,isReloadedTransaction:H.type==="transaction"};if(H.type==="transaction"&&I.workflowState){const nt=JSON.parse(I.workflowState);await fa(nt),et.reloadedState=nt}else if(!B&&H.workflowState){const nt=JSON.parse(H.workflowState);await fa(nt),et.reloadedState=nt}return et.delayWorkflowStateSync=!0,{experienceOptions:et,index:T,options:H}}),b=await Promise.all(w);k.setMap("transactionOwnerIds",f);const F=b.sort((y,I)=>y.index-I.index);let E=[];for(const y of F){const{experienceOptions:I,options:x}=y,B=new $r(this,I);await B.getWorkflowManager().getInitializationPromise(),a&&a(),x.type!=="transaction"&&this.customer&&await B.attachCustomerDetails({email:this.customer.emailAddress}),E=[...E,B],B.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return E}storeCustomer(t){const e=k.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),k.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const i=(await S.getShadowGraphqlClient().query({query:Io(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!i||i.length===0||!i[0]?.id)throw new Error("Integration product not found.");return new va(i[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await S.getShadowGraphqlClient().query({query:Bo(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProductFromExternalIds;if(!o?.id)throw new Error("Integration product not found.");return new va(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(k.getMap("transactionOwnerIds")||new Map).get(t)||void 0,r=await S.getShadowGraphqlClient().query({query:bo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!r.data.transactions||r.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return r.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await S.getShadowGraphqlClient().mutate({mutation:Lo,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const Xr=async(n,t)=>(await S.getShadowGraphqlClient().query({query:Oo,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}},variables:{themeConfigurationId:t}})).data.currentIntegration,Oc=async n=>{const e=await S.getShadowGraphqlClient().query({query:Eo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},$c=async(n,t)=>(await S.getShadowGraphqlClient().query({query:Ro,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,Uc=async n=>(await S.getShadowGraphqlClient().query({query:Uo,errorPolicy:"all",variables:{id:n}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,Lc=async n=>(await S.getShadowGraphqlClient().query({query:$o,errorPolicy:"all",variables:{id:n}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function Zr(n){const e=k.getMap("bundleOwnerIds")?.get(n),a={};try{const r=await this.loggedInBearerToken();a.Authorization=`Bearer ${r}`}catch{const o=Object.entries(localStorage).find(([l,c])=>l.startsWith("CognitoIdentityServiceProvider")&&l.endsWith("idToken"))?.[0]||"",s=localStorage.getItem(o);s&&!oe(s)&&(a.Authorization=`Bearer ${s}`)}return{bundleOwnerId:e,...a}}const Vc=async n=>{const t=await Zr(n),e=await S.getShadowGraphqlClient().mutate({mutation:Hl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:n},context:{headers:t}});if(e.data?.bundleDelete!==n)throw new Error(`Failed to delete bundle: ${e.errors}`)};function ti(n,t,e,a){const r=e.width*n.zoom,i=e.height*n.zoom;if(a){const s=n,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,n.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Be(n.x,t.width-c,0),s.y=Be(n.y,t.height-d,0),s}const o=n;return o.x=Be(o.x,-r,t.width),o.y=Be(o.y,-i,t.height),o}function Be(n,t,e){return Math.min(Math.max(n,t),e)}class ei{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Pn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const r=a;if(r.currentFrameSources){let i=!1;for(let o=0;o<r.currentFrameSources.length;o++){const s=r.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;Zt(l,c)||(this.frameData||(this.frameData=new Array(r.currentFrameSources.length)),this.frameData[o]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const r=Dt.get(e);r&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=r)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=ze(this.imageData.svg,this.imageData.colors||{},!1);return Ve(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,r){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((o,s)=>{const l=(e[s]-this.offsets[s].x)/this.offsets[s].zoom,c=(a[s]-this.offsets[s].y)/this.offsets[s].zoom,d=e[s]-l*t[s],u=a[s]-c*t[s];return{x:d,y:u,zoom:this.imageData.width*t[s]/this.imageData.width}});this.updateOffsets(i,r),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const r=this.imageData;if(!r||!this.frameData)return;if(this.frameData.length!==t.length)throw new N("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((o,s)=>!(t[s].x===o.x&&t[s].y===o.y&&t[s].zoom===o.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((o,s)=>{this.offsets[s]=ti(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,r,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,r,i){if(!a||a.length===0||a.some(s=>!s))throw new N("Frame data not set. This is a bug");if(!this.workflowManager)throw new N("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((s,l)=>{o(new R([new Is(s,e,t[l]),new Bs(s,r.useThreshold,r.invertThreshold,r.threshold,r.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,r)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[r]=i,this.maxZoomScale[r]=i*2.5):(this.minZoomScale[r]=i/10,this.maxZoomScale[r]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Na(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class qc{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,r,i,o,s,l,c,d,u,A,h,g,p,m,f){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var ai=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(ai||{});class ni extends X{constructor(t,e,a){super(t,e,a);const r=e.data;this.frameService=new ei(r.forceImageCover,r.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ht.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){if(await ht.selectImage(this.step,t,this.manager,a),e){const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Re.BackgroundRemover)}async canRemoveBackground(){return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await O.removeBackgroundFromAsset(e);t&&await ht.selectImage(this.step,a,this.manager,!1);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ht.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ht.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ht.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,r){return r&&r.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return O.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return O.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const r=await this.getBackgroundRemovedImageSelection();if(!r)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(r,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const zc=C.gql`
2657
2657
  query GetLoggedInCustomer($email: String!) {
2658
2658
  customer(emailAddress: $email) {
2659
2659
  id
@@ -2844,5 +2844,15 @@
2844
2844
  id
2845
2845
  }
2846
2846
  }
2847
- `;var si=(n=>(n.Confirmed="Confirmed",n.Plausible="Plausible",n.Unlikely="Unlikely",n))(si||{}),li=(n=>(n.Created="Created",n.Processing="Processing",n.Completed="Completed",n.Failed="Failed",n.Cancelled="Cancelled",n))(li||{});const md=async n=>{const t=n.map(a=>a.getTransaction().recipient?.id).filter(a=>!!a),e=await S.getShadowGraphqlClient().query({query:ud,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return n.map(a=>{const r=a.getTransaction().recipient?.id;if(r)return e.data?.recipients?.find(i=>i.id===r)?.addressValidationJob})},pd=async n=>(await S.getShadowGraphqlClient().query({query:dd,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:n}})).data?.addressValidationJobs,fd=async n=>n.getTransaction().recipient?.id?(await S.getShadowGraphqlClient().mutate({mutation:Ad,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n.getTransaction().recipient.id}})).data?.recipientValidate:void 0,Cd=async n=>{const t=n.map(a=>a.getTransaction().recipient?.id).filter(a=>!!a),e=await S.getShadowGraphqlClient().mutate({mutation:hd,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return n.map(a=>{const r=a.getTransaction().recipient?.id;if(r)return e.data?.recipientValidateBatch?.find(i=>i.entityId===r)})},wd=async n=>{const t=n.getTransaction().recipient?.id;if(!t)return;(await S.getShadowGraphqlClient().mutate({mutation:gd,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:t}})).data?.recipientOverrideAddress?.id&&(n.getTransaction().addressValidationStatus=Ia.Overridden)};exports.AddonHandle=Re;exports.AddressValidationJobStatus=li;exports.AddressValidationResultConfirmationLevel=si;exports.AddressValidationStatus=Ia;exports.ArrayInput=xc;exports.AspectType=U;exports.AssetNotFoundError=pt;exports.AssetType=te;exports.BringForwardCommand=ks;exports.BringToBackCommand=Ds;exports.BringToFrontCommand=Fs;exports.BundleDesignCreationCartAddMode=Dn;exports.CanvasCommand=Q;exports.CollectionProduct=Ht;exports.ColorOptionGlobalPropertyHandle=ya;exports.CommandContext=cr;exports.ConversionDataType=_t;exports.ConversionLocation=ri;exports.CreateElementCommand=q;exports.CreateLayoutCommand=Oa;exports.CurrencyContext=Kr;exports.CurrencyService=Jr;exports.DeleteElementCommand=xt;exports.DigitalContentStepHandle=kr;exports.FileUploadGlobalPropertyHandle=Ur;exports.FlowExecutionNodeResult=Yt;exports.FlowExecutionResult=Hr;exports.FlowService=Wr;exports.FontAlignmentCommand=mr;exports.FontColorCommand=hr;exports.FontSizeCommand=gr;exports.FontSourceCommand=Ca;exports.FrameService=ei;exports.FrameStep=ai;exports.FrameStepHandle=ni;exports.GlobalPropertyHandle=We;exports.GroupCommand=R;exports.IllustrationStepHandle=Er;exports.InformationMessageType=Ce;exports.InformationStepHandle=Dr;exports.IntegrationProduct=va;exports.IntegrationType=Mn;exports.LayoutElementFactory=Ss;exports.LayoutElementType=D;exports.LayoutNotFoundError=W;exports.LayoutRenderingPurpose=Nt;exports.MaterialStepHandle=br;exports.MisconfigurationError=ne;exports.MockWorkflowManager=qc;exports.ModelStepHandle=Ir;exports.ModuleStepHandle=Mr;exports.MoveCommand=vs;exports.ObjectInput=Ya;exports.ObjectInputType=Yr;exports.OptionGlobalPropertyHandle=ja;exports.OptionNotFoundError=ae;exports.ParseError=Et;exports.PictureStepHandle=Br;exports.ProductCameraRig=Tn;exports.ProductCollection=Wa;exports.ProductCollectionProductSortKey=zr;exports.ProductWorkflow=Tt;exports.PromiseCache=$t;exports.PromiseQueue=Ma;exports.QuestionStepHandle=Pr;exports.QueueablePromise=ka;exports.ResizeCommand=bs;exports.ResourceNotFoundError=Qt;exports.RotateCommand=Es;exports.ScaleAxis=G;exports.SendBackwardsCommand=Ms;exports.ShapeStepHandle=xr;exports.ShareActionType=kn;exports.SpiffCommerceClient=Rc;exports.StakeholderType=ee;exports.StepAspectType=Fn;exports.StepHandle=X;exports.StepType=v;exports.TextAlgorithm=Bt;exports.TextChangeCommand=pr;exports.TextGlobalPropertyHandle=Lr;exports.TextInput=Pc;exports.TextStepHandle=Fr;exports.Transform=jr;exports.TransformCollection=Gr;exports.UnhandledBehaviorError=N;exports.UnitOfMeasurement=Nn;exports.UpdateImageSourceCommand=Ps;exports.Variant=rt;exports.WorkflowExperienceEventType=Or;exports.WorkflowExperienceImpl=$r;exports.assetService=O;exports.browserColorToHex=Gn;exports.cmPerPixel=rs;exports.createDesign=Rr;exports.currentDirection=es;exports.dataUrlFromExternalUrl=ki;exports.deleteBundle=Vc;exports.designService=xe;exports.determineCorrectFontSizeAndLines=Kt;exports.digitalContentStepService=$a;exports.domParser=lt;exports.duplicateBundle=Zc;exports.duplicateTransaction=td;exports.fetchAsString=tt;exports.findAngle=Yo;exports.findElement=$;exports.findPmsColors=Ki;exports.frameDataCache=Dt;exports.frameStepService=ht;exports.generate=M;exports.generateCommands=Sr;exports.generateSVGWithUnknownColors=ot;exports.generateStateFromDesignInputSteps=ml;exports.getAddressValidationJobs=pd;exports.getAttributesFromArrayBuffer=de;exports.getAxisAlignedBoundingBox=Ho;exports.getBoundedOffsets=ti;exports.getBundleThemeConfiguration=Uc;exports.getCustomer=ed;exports.getCustomerBundles=ad;exports.getElementVertices=as;exports.getFrameData=me;exports.getGlobalPropertyStateForBundle=wl;exports.getIntegration=Xr;exports.getNEPoint=Zo;exports.getNWPoint=Xo;exports.getOrderedTransactions=id;exports.getOverrideThemeConfiguration=$c;exports.getPointOfRotation=_o;exports.getProductCollections=Sc;exports.getSEPoint=ts;exports.getSvgElement=je;exports.getTemplateBundles=sd;exports.getTemplateTransactions=od;exports.getTransaction=Oc;exports.getTransactionThemeConfiguration=Lc;exports.getTransactionsForBundle=nd;exports.getTrueCoordinates=Ko;exports.getUnorderedTransactions=rd;exports.getValidationJobsForWorkflowExperiences=md;exports.getWorkflow=_r;exports.getWorkflows=Ja;exports.graphQlManager=S;exports.illustrationStepService=Jt;exports.isCloseToValue=Jo;exports.loadFont=Pt;exports.matchHexToPms=Hi;exports.materialStepService=Ua;exports.metafieldManager=qr;exports.mmPerPixel=ns;exports.modelStepService=La;exports.modifySVGColors=ze;exports.moduleStepService=Va;exports.nameBundle=_c;exports.nameTransaction=Xc;exports.optionService=j;exports.outlineFontsInSvg=cs;exports.overrideWorkflowExperienceRecipientAddress=wd;exports.patternImageDataCache=dt;exports.persistenceService=k;exports.pictureStepService=qa;exports.pmsToRgb=Wi;exports.questionStepService=za;exports.registerFetchImplementation=Bi;exports.registerWindowImplementation=Ii;exports.rehydrateSerializedLayout=fa;exports.rgbToPms=zn;exports.rotateAroundPoint=Wt;exports.sanitizeSvgTree=qe;exports.setBearerAuthenticationToken=Vn;exports.setCanvasModule=Pa;exports.shapeStepService=kt;exports.shortenUrl=fr;exports.spiffCoreConfiguration=ut;exports.stepAspectValuesToDesignInputSteps=gl;exports.svgColorValueToDefinition=ha;exports.svgStringDimensions=Ra;exports.svgToDataUrl=Ve;exports.textStepService=z;exports.toast=wr;exports.validateWorkflowExperienceRecipient=fd;exports.validateWorkflowExperienceRecipients=Cd;exports.xmlSerializer=yt;
2847
+ `;var si=(n=>(n.Confirmed="Confirmed",n.Plausible="Plausible",n.Unlikely="Unlikely",n))(si||{}),li=(n=>(n.Created="Created",n.Processing="Processing",n.Completed="Completed",n.Failed="Failed",n.Cancelled="Cancelled",n))(li||{});const md=async n=>{const t=n.map(a=>a.getTransaction().recipient?.id).filter(a=>!!a),e=await S.getShadowGraphqlClient().query({query:ud,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return n.map(a=>{const r=a.getTransaction().recipient?.id;if(r)return e.data?.recipients?.find(i=>i.id===r)?.addressValidationJob})},pd=async n=>(await S.getShadowGraphqlClient().query({query:dd,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:n}})).data?.addressValidationJobs,fd=async n=>n.getTransaction().recipient?.id?(await S.getShadowGraphqlClient().mutate({mutation:Ad,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n.getTransaction().recipient.id}})).data?.recipientValidate:void 0,Cd=async n=>{const t=n.map(a=>a.getTransaction().recipient?.id).filter(a=>!!a),e=await S.getShadowGraphqlClient().mutate({mutation:hd,errorPolicy:"all",fetchPolicy:"network-only",variables:{ids:t}});return n.map(a=>{const r=a.getTransaction().recipient?.id;if(r)return e.data?.recipientValidateBatch?.find(i=>i.entityId===r)})},wd=async n=>{const t=n.getTransaction().recipient?.id;if(!t)return;(await S.getShadowGraphqlClient().mutate({mutation:gd,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:t}})).data?.recipientOverrideAddress?.id&&(n.getTransaction().addressValidationStatus=Ia.Overridden)},yd=C.gql`
2848
+ query GetIntegrationProductsForIds($ids: [String!]!) {
2849
+ integrationProducts(ids: $ids) {
2850
+ id
2851
+ product {
2852
+ id
2853
+ name
2854
+ }
2855
+ }
2856
+ }
2857
+ `,Sd=async n=>(await S.getShadowGraphqlClient().query({query:yd,variables:{ids:n}})).data.integrationProducts;exports.AddonHandle=Re;exports.AddressValidationJobStatus=li;exports.AddressValidationResultConfirmationLevel=si;exports.AddressValidationStatus=Ia;exports.ArrayInput=xc;exports.AspectType=U;exports.AssetNotFoundError=pt;exports.AssetType=te;exports.BringForwardCommand=ks;exports.BringToBackCommand=Ds;exports.BringToFrontCommand=Fs;exports.BundleDesignCreationCartAddMode=Dn;exports.CanvasCommand=Q;exports.CollectionProduct=Ht;exports.ColorOptionGlobalPropertyHandle=ya;exports.CommandContext=cr;exports.ConversionDataType=_t;exports.ConversionLocation=ri;exports.CreateElementCommand=q;exports.CreateLayoutCommand=Oa;exports.CurrencyContext=Kr;exports.CurrencyService=Jr;exports.DeleteElementCommand=xt;exports.DigitalContentStepHandle=kr;exports.FileUploadGlobalPropertyHandle=Ur;exports.FlowExecutionNodeResult=Yt;exports.FlowExecutionResult=Hr;exports.FlowService=Wr;exports.FontAlignmentCommand=mr;exports.FontColorCommand=hr;exports.FontSizeCommand=gr;exports.FontSourceCommand=Ca;exports.FrameService=ei;exports.FrameStep=ai;exports.FrameStepHandle=ni;exports.GlobalPropertyHandle=We;exports.GroupCommand=R;exports.IllustrationStepHandle=Er;exports.InformationMessageType=Ce;exports.InformationStepHandle=Dr;exports.IntegrationProduct=va;exports.IntegrationType=Mn;exports.LayoutElementFactory=Ss;exports.LayoutElementType=D;exports.LayoutNotFoundError=W;exports.LayoutRenderingPurpose=Nt;exports.MaterialStepHandle=br;exports.MisconfigurationError=ne;exports.MockWorkflowManager=qc;exports.ModelStepHandle=Ir;exports.ModuleStepHandle=Mr;exports.MoveCommand=vs;exports.ObjectInput=Ya;exports.ObjectInputType=Yr;exports.OptionGlobalPropertyHandle=ja;exports.OptionNotFoundError=ae;exports.ParseError=Et;exports.PictureStepHandle=Br;exports.ProductCameraRig=Tn;exports.ProductCollection=Wa;exports.ProductCollectionProductSortKey=zr;exports.ProductWorkflow=Tt;exports.PromiseCache=$t;exports.PromiseQueue=Ma;exports.QuestionStepHandle=Pr;exports.QueueablePromise=ka;exports.ResizeCommand=bs;exports.ResourceNotFoundError=Qt;exports.RotateCommand=Es;exports.ScaleAxis=G;exports.SendBackwardsCommand=Ms;exports.ShapeStepHandle=xr;exports.ShareActionType=kn;exports.SpiffCommerceClient=Rc;exports.StakeholderType=ee;exports.StepAspectType=Fn;exports.StepHandle=X;exports.StepType=v;exports.TextAlgorithm=Bt;exports.TextChangeCommand=pr;exports.TextGlobalPropertyHandle=Lr;exports.TextInput=Pc;exports.TextStepHandle=Fr;exports.Transform=jr;exports.TransformCollection=Gr;exports.UnhandledBehaviorError=N;exports.UnitOfMeasurement=Nn;exports.UpdateImageSourceCommand=Ps;exports.Variant=rt;exports.WorkflowExperienceEventType=Or;exports.WorkflowExperienceImpl=$r;exports.assetService=O;exports.browserColorToHex=Gn;exports.cmPerPixel=rs;exports.createDesign=Rr;exports.currentDirection=es;exports.dataUrlFromExternalUrl=ki;exports.deleteBundle=Vc;exports.designService=xe;exports.determineCorrectFontSizeAndLines=Kt;exports.digitalContentStepService=$a;exports.domParser=lt;exports.duplicateBundle=Zc;exports.duplicateTransaction=td;exports.fetchAsString=tt;exports.findAngle=Yo;exports.findElement=$;exports.findPmsColors=Ki;exports.frameDataCache=Dt;exports.frameStepService=ht;exports.generate=M;exports.generateCommands=Sr;exports.generateSVGWithUnknownColors=ot;exports.generateStateFromDesignInputSteps=ml;exports.getAddressValidationJobs=pd;exports.getAttributesFromArrayBuffer=de;exports.getAxisAlignedBoundingBox=Ho;exports.getBoundedOffsets=ti;exports.getBundleThemeConfiguration=Uc;exports.getCustomer=ed;exports.getCustomerBundles=ad;exports.getElementVertices=as;exports.getFrameData=me;exports.getGlobalPropertyStateForBundle=wl;exports.getIntegration=Xr;exports.getIntegrationProducts=Sd;exports.getNEPoint=Zo;exports.getNWPoint=Xo;exports.getOrderedTransactions=id;exports.getOverrideThemeConfiguration=$c;exports.getPointOfRotation=_o;exports.getProductCollections=Sc;exports.getSEPoint=ts;exports.getSvgElement=je;exports.getTemplateBundles=sd;exports.getTemplateTransactions=od;exports.getTransaction=Oc;exports.getTransactionThemeConfiguration=Lc;exports.getTransactionsForBundle=nd;exports.getTrueCoordinates=Ko;exports.getUnorderedTransactions=rd;exports.getValidationJobsForWorkflowExperiences=md;exports.getWorkflow=_r;exports.getWorkflows=Ja;exports.graphQlManager=S;exports.illustrationStepService=Jt;exports.isCloseToValue=Jo;exports.loadFont=Pt;exports.matchHexToPms=Hi;exports.materialStepService=Ua;exports.metafieldManager=qr;exports.mmPerPixel=ns;exports.modelStepService=La;exports.modifySVGColors=ze;exports.moduleStepService=Va;exports.nameBundle=_c;exports.nameTransaction=Xc;exports.optionService=j;exports.outlineFontsInSvg=cs;exports.overrideWorkflowExperienceRecipientAddress=wd;exports.patternImageDataCache=dt;exports.persistenceService=k;exports.pictureStepService=qa;exports.pmsToRgb=Wi;exports.questionStepService=za;exports.registerFetchImplementation=Bi;exports.registerWindowImplementation=Ii;exports.rehydrateSerializedLayout=fa;exports.rgbToPms=zn;exports.rotateAroundPoint=Wt;exports.sanitizeSvgTree=qe;exports.setBearerAuthenticationToken=Vn;exports.setCanvasModule=Pa;exports.shapeStepService=kt;exports.shortenUrl=fr;exports.spiffCoreConfiguration=ut;exports.stepAspectValuesToDesignInputSteps=gl;exports.svgColorValueToDefinition=ha;exports.svgStringDimensions=Ra;exports.svgToDataUrl=Ve;exports.textStepService=z;exports.toast=wr;exports.validateWorkflowExperienceRecipient=fd;exports.validateWorkflowExperienceRecipients=Cd;exports.xmlSerializer=yt;
2848
2858
  //# sourceMappingURL=index.js.map