@spiffcommerce/core 39.2.3 → 39.2.4

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.cjs CHANGED
@@ -2487,7 +2487,7 @@
2487
2487
  }
2488
2488
  }
2489
2489
  }
2490
- `;class Zc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class td{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 n=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 n?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new td;class rr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Rr(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=un.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(un.code(e)?.code==="CLP")return"USD0,0"}}const kn=new rr;class or{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,kn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,kn.getPrecisionForCurrency(e))}}const ed=async(i,t)=>{const e=await y.getShadowGraphqlClient().query({query:is(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:i}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(n=>console.error(n)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==i.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(n=>{n.finalizeStepConfig||(n.finalizeStepConfig={}),n.finalizeStepConfig.termsMarkdown=n.finalizeStepConfig.termsMarkdown||n.partner.termsMarkdown}),a},ad=async(i,t)=>{const a=(await t).find(n=>n.id===i);if(!a)throw new Error(`Workflow not found: ${i}`);return a},sn=async(i,t)=>{const e=i.map(s=>oe.get({id:s,options:t})),a=i.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=ed(a,t),r=a.map(s=>oe.set({id:s,options:t},ad(s,n))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},sr=async(i,t)=>(await sn([i],t))[0],nd=async i=>{const t=await y.getShadowGraphqlClient().query({query:mi,variables:{ids:i},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class id{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:qo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&ao(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 39.2.3"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){gt.setHubUrl(t.hubUrl),gt.setServerUrl(t.serverUrl),gt.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&&ei(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return G}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!no())throw new Error("Application key required to use Flow Service.");return new ar}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await y.getShadowGraphqlClient().query({query:ds,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new or(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=lr(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}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Q.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),Q.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),n=(await e.query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const s=(await e.mutate({mutation:Kc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(n);const r=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:r}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),r=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<r-parseInt(t)){const l=await Wt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:_c,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,r=!a?.AccessToken||Re(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||r){const o=await Wt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Xc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await y.getShadowGraphqlClient().mutate({mutation:Wl(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(!r?.id)throw new Error("Unable to create bundle");const o=Q.getMap("bundlePartnerIds")||new Map;o.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",o);const s=Q.getMap("bundleOwnerIds")||new Map;s.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",s);const l=new Dn(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n,r){const s=Q.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const m=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(m);f&&!Re(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...n?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:zl(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=Q.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),Q.setMap("bundlePartnerIds",A);const h=new Dn(this,u,e,a,s,{additionalHeaders:n?.graphql?.additionalHeaders,eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:n?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,n){const o={...await dr(t),...n?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Yl(),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=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:rc(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:ql,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&n.set(r.bundle.id,r.bundle.partner.id)}),Q.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0],r=n.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await n.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,n){if(t.length===0)throw new ft("No options provided!");const r=t.map((x,T)=>({option:x,index:T})),o=r.filter(x=>x.option.type==="transaction"),s=r.filter(x=>x.option.type==="integration"||x.option.type==="external"||x.option.type==="blank"),l=50,c=pa(o,l),d=pa(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:zo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,n&&n(u,o.length),k.length!==x.length){const X=L.errors?.[0]?.message||"Unknown error";throw new ft(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((X,It)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(mt=>mt.option.transactionId===X.id)?.option.readOnly??!1,index:x[It].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:Lo,variables:{inputs:x.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new ft(`Failed to create transactions: ${k}`)}return u=u+L.length,n&&n(u,o.length),L.map((k,X)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:x[X].index}))},p=(await Promise.all([...c.map(h),...d.map(g)])).flat(),m=[...new Set(p.map(x=>x.transaction.integrationProductId))].filter(x=>x!==void 0),f=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[S,w]=await Promise.all([(async()=>m.length>0?await nd(m):[])(),(async()=>f.length>0?await sn(f,e):[])()]),F=new Map(S.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,It=L?b.get(L):void 0,mt=t[X];if(T.integrationProductId){const ot=F.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const fe=Q.getMap("transactionOwnerIds")||new Map;!fe.get(T.id)&&T.transactionOwnerId&&(fe.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",fe));const ta=fe.get(T.id)||void 0,yr=new Zc({onMutate:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}})}),Ce={workflow:It,transaction:T,singleVariantsRenderable:mt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>yr,readOnly:k,isReloadedTransaction:mt.type==="transaction"};if(mt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await Pa(ot),Ce.reloadedState=ot}else if(!k&&mt.workflowState){const ot=JSON.parse(mt.workflowState);await Pa(ot),Ce.reloadedState=ot}return Ce.delayWorkflowStateSync=!0,{experienceOptions:Ce,index:X,options:mt}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let R=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new Ki(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await y.getShadowGraphqlClient().query({query:Ko(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new Ta(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:_o(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 Ta(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(Q.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await y.getShadowGraphqlClient().query({query:Yo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:cs,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 lr=async(i,t)=>(await y.getShadowGraphqlClient().query({query:os,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":i},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,rd=async i=>{const e=await y.getShadowGraphqlClient().query({query:Wo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:i}});if(e.data.transactions.length!==0)return e.data.transactions[0]},od=async(i,t)=>(await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{themeConfigurationId:i,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,sd=async i=>(await y.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",variables:{id:i}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,ld=async i=>(await y.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",variables:{id:i}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function cr(){const i={};try{const t=await this.loggedInBearerToken();i.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,o])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",n=localStorage.getItem(a);n&&!Re(n)&&(i.Authorization=`Bearer ${n}`)}return i}async function dr(i){const e=Q.getMap("bundleOwnerIds")?.get(i),a=await cr();return{bundleOwnerId:e,...a}}async function cd(i){const e=Q.getMap("transactionOwnerIds")?.get(i),a=await cr();return{transactionOwnerId:e,...a}}const dd=async i=>{const t=await dr(i),e=await y.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i},context:{headers:t}});if(e.data?.bundleDelete!==i)throw new Error(`Failed to delete bundle: ${e.errors}`)},ud=async i=>{const t=await cd(i),e=await y.getShadowGraphqlClient().mutate({mutation:mc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[i]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==i)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function ur(i,t,e,a){const n=e.width*i.zoom,r=e.height*i.zoom;if(a){const s=i,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,i.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Pe(i.x,t.width-c,0),s.y=Pe(i.y,t.height-d,0),s}const o=i;return o.x=Pe(o.x,-n,t.width),o.y=Pe(o.y,-r,t.height),o}function Pe(i,t,e){return Math.min(Math.max(i,t),e)}class Ar{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Vn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let r=!1;for(let o=0;o<n.currentFrameSources.length;o++){const s=n.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;ae(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[o]=l,r=!0)}r&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Mt.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=We(this.imageData.svg,this.imageData.colors||{},!1);return je(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const r=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(r,n),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new O("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]=ur(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,r){if(!a||a.length===0||a.some(l=>!l))throw new O("Frame data not set. This is a bug");if(!this.workflowManager)throw new O("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new U([new Ws(l,e,t[d]),new Ys(l,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),r&&r()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=r,this.maxZoomScale[n]=r*2.5):(this.minZoomScale[n]=r/10,this.maxZoomScale[n]=r*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]=ja(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Ad{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,n,r,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(){}getInitialOptionIds(){return new Promise(()=>new Set)}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 hr=(i=>(i.SelectFrame="SelectFrame",i.SelectImage="SelectImage",i.Position="Position",i))(hr||{});class gr extends Z{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Ar(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return pt.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 pt.selectImage(this.step,t,this.manager,a),e){const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Ve.AdvancedImageManipulation)}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 G.removeBackgroundFromAsset(e);t&&await pt.selectImage(this.step,a,this.manager,!1);const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}async vectorize(t,e=void 0){const a=t??await this.getOriginalImageSelection();if(!a)throw new Error("You must supply an image selection before attempting to vectorize the image.");const n=await G.vectorizeAsset(a,e);await this.selectImage(n,t!==void 0);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,vectorizedAssetKey:n.key,useOriginalAsset:!1}}),n}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return G.getLocalOrFromServer(t)}async getVectorizedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.vectorizedAssetKey;if(t)return G.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}async changeColors(t){await pt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?pt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await rt(t.svg)).colors:void 0}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return pt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return G.getLocalOrFromServer(t)}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const n=await this.getBackgroundRemovedImageSelection();if(!n)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(n,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const hd=C.gql`
2490
+ `;class Zc{constructor(t,e=y.getShadowGraphqlClient.bind(y)){this.options=t,this.client=e}query(t){const e=this.options?.onQuery?this.options?.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){const e=this.options?.onMutate?this.options?.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class td{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 n=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 n?.ChallengeName==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}async refreshTokens(){const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await this.cognitoClient?.send(new we.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}}))}}const Wt=new td;class rr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Rr(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=un.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t;if(un.code(e)?.code==="CLP")return"USD0,0"}}const kn=new rr;class or{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,kn.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,kn.getPrecisionForCurrency(e))}}const ed=async(i,t)=>{const e=await y.getShadowGraphqlClient().query({query:is(t?.assets?.metadata||!1),errorPolicy:"all",variables:{ids:i}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(n=>console.error(n)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==i.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(n=>{n.finalizeStepConfig||(n.finalizeStepConfig={}),n.finalizeStepConfig.termsMarkdown=n.finalizeStepConfig.termsMarkdown||n.partner.termsMarkdown}),a},ad=async(i,t)=>{const a=(await t).find(n=>n.id===i);if(!a)throw new Error(`Workflow not found: ${i}`);return a},sn=async(i,t)=>{const e=i.map(s=>oe.get({id:s,options:t})),a=i.filter((s,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=ed(a,t),r=a.map(s=>oe.set({id:s,options:t},ad(s,n))),o=e.filter(s=>s!==void 0);return await Promise.all(o.concat(r))},sr=async(i,t)=>(await sn([i],t))[0],nd=async i=>{const t=await y.getShadowGraphqlClient().query({query:mi,variables:{ids:i},errorPolicy:"all",fetchPolicy:"no-cache"});return t.errors&&console.error(t.errors),t.data.integrationProducts||[]};class id{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return y.getShadowGraphqlClient().mutate({...e,mutation:qo})}catch(a){throw console.error(a),new ft("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&ao(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 39.2.4"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){gt.setHubUrl(t.hubUrl),gt.setServerUrl(t.serverUrl),gt.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&&ei(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return G}async getBetaEnabled(){return this.options.enableBetaFeatures?!0:(await this.getIntegration()).partner.beta===!0}getFlowService(){if(!no())throw new Error("Application key required to use Flow Service.");return new ar}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,r=await y.getShadowGraphqlClient().query({query:ds,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:o,rateTo:s}=r.data.currencyConversion;return new or(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=lr(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}}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=Q.getMap("transactionCustomerIds");e?.has(t)&&(e.delete(t),Q.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){const e=this.customer?.stakeholders?.find(a=>a.transaction?.id===t);if(e)return e.type}async getOrCreateCustomer(t){this.customer=void 0;const e=y.getShadowGraphqlClient(),n=(await e.query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const s=(await e.mutate({mutation:Kc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data?.customerCreate;if(!s)throw new Error("Unable to create customer.");return this.storeCustomer(s),this.customer=s,{customer:s,isAuthenticated:!1}}this.storeCustomer(n);const r=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:r}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),r=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<r-parseInt(t)){const l=await Wt.refreshTokens();if(l?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const s=(await y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return s.id?(this.customer=s,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await y.getShadowGraphqlClient().mutate({mutation:_c,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n?.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const o=(await y.getShadowGraphqlClient().query({query:Be,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!o.id)throw new Error("Failed to get customer.");return this.customer=o,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,r=!a?.AccessToken||Re(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||r){const o=await Wt.refreshTokens();if(o?.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=o.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){if(!this.customer?.id)throw new Error("Customer must be logged in before calling this function.");return(await y.getShadowGraphqlClient().query({query:Xc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){const r=(await y.getShadowGraphqlClient().mutate({mutation:Wl(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(!r?.id)throw new Error("Unable to create bundle");const o=Q.getMap("bundlePartnerIds")||new Map;o.set(r.id,r.partner.id),Q.setMap("bundlePartnerIds",o);const s=Q.getMap("bundleOwnerIds")||new Map;s.set(r.id,r.bundleOwnerId),Q.setMap("bundleOwnerIds",s);const l=new Dn(this,r,void 0,void 0,r.bundleOwnerId,{eagerFetchProducts:a?.graphql?.productCollection?.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n,r){const s=Q.getMap("bundleOwnerIds")?.get(t),l={};try{const g=await this.loggedInBearerToken();l.Authorization=`Bearer ${g}`}catch{const m=Object.entries(localStorage).find(([S,w])=>S.startsWith("CognitoIdentityServiceProvider")&&S.endsWith("idToken"))?.[0]||"",f=localStorage.getItem(m);f&&!Re(f)&&(l.Authorization=`Bearer ${f}`)}const c={bundleOwnerId:s,...l,...n?.graphql?.additionalHeaders},d=await y.getShadowGraphqlClient().query({query:zl(n?.graphql?.productCollection?.eagerFetchProducts||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:c}});if(!d.data?.bundles||d.data?.bundles.length===0||!d.data?.bundles[0])throw new Error(`Unable to find bundle: ${t}`);const u=d.data?.bundles[0],A=Q.getMap("bundlePartnerIds")||new Map;A.set(u.id,u.partner.id),Q.setMap("bundlePartnerIds",A);const h=new Dn(this,u,e,a,s,{additionalHeaders:n?.graphql?.additionalHeaders,eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState,readonly:n?.readonly},r);return await h.getInitializationPromise(),h}async duplicateBundle(t,e,a,n){const o={...await dr(t),...n?.graphql?.additionalHeaders},l=(await y.getShadowGraphqlClient().mutate({mutation:Yl(),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=Q.getMap("bundlePartnerIds")||new Map;c.set(l.id,l.partner.id),Q.setMap("bundlePartnerIds",c);const d=Q.getMap("bundleOwnerIds")||new Map;return d.set(l.id,l.bundleOwnerId),Q.setMap("bundleOwnerIds",d),async()=>await this.getExistingBundle(l.id,void 0,void 0,{graphql:{productCollection:{eagerFetchProducts:n?.graphql?.productCollection?.eagerFetchProducts||!1}}})}async getBundlesForCustomer(t){if(!this.customer?.id)throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await y.getShadowGraphqlClient().query({query:rc(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){if(!this.customer)throw new Error("Customer not authenticated.");const t=await y.getShadowGraphqlClient().query({query:ql,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!t.data?.customers||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=Q.getMap("bundlePartnerIds")||new Map;return a.forEach(r=>{r.bundle?.id&&r.bundle.partner?.id&&n.set(r.bundle.id,r.bundle.partner.id)}),Q.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0],r=n.getWorkflow();return e&&!r&&console.error("No workflow instantiated when trying to create preview service."),e&&r&&await n.getWorkflowManager().injectIntoPreviewService(e(r)),a[0]}async getWorkflowExperiences(t,e,a,n){if(t.length===0)throw new ft("No options provided!");const r=t.map((x,T)=>({option:x,index:T})),o=r.filter(x=>x.option.type==="transaction"),s=r.filter(x=>x.option.type==="integration"||x.option.type==="external"||x.option.type==="blank"),l=50,c=pa(o,l),d=pa(s,l);let u=0;const A=y.getShadowGraphqlClient(),h=async x=>{if(x.length===0)return[];const T=x.map(X=>X.option.transactionId),L=await A.query({query:zo,variables:{ids:T},errorPolicy:"all",fetchPolicy:"no-cache"}),k=L.data.transactions;if(u=u+k.length,n&&n(u,o.length),k.length!==x.length){const X=L.errors?.[0]?.message||"Unknown error";throw new ft(`Not all transactions were found: ${X}`)}return!this.activeIntegration&&k[0].integrationProduct?.integration&&(this.activeIntegration=Promise.resolve(k[0].integrationProduct.integration)),k.map((X,It)=>({transaction:X,workflowId:X.workflowId,readOnly:x.find(mt=>mt.option.transactionId===X.id)?.option.readOnly??!1,index:x[It].index}))},g=async x=>{if(x.length===0)return[];const T=await A.mutate({mutation:Lo,variables:{inputs:x.map(k=>({integrationProductId:k.option.type==="integration"?k.option.integrationProductId:void 0,externalIntegrationId:k.option.type==="external"?k.option.externalIntegrationId:void 0,externalProductId:k.option.type==="external"?k.option.externalProductId:void 0,workflowId:k.option.workflowId,designName:k.option.designName,claim:!0,quantity:k.option.quantity,recipient:k.option.recipient})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),L=T.data?.transactionCreateMany;if(!L||L.length===0){const k=T.errors?.[0]?.message||"Unknown error";throw new ft(`Failed to create transactions: ${k}`)}return u=u+L.length,n&&n(u,o.length),L.map((k,X)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:x[X].index}))},p=(await Promise.all([...c.map(h),...d.map(g)])).flat(),m=[...new Set(p.map(x=>x.transaction.integrationProductId))].filter(x=>x!==void 0),f=[...new Set(p.map(x=>x.workflowId))].filter(x=>x!==void 0),[S,w]=await Promise.all([(async()=>m.length>0?await nd(m):[])(),(async()=>f.length>0?await sn(f,e):[])()]),F=new Map(S.map(x=>[x.id,x])),b=new Map(w.map(x=>[x.id,x])),v=p.map(async x=>{const{transaction:T,workflowId:L,readOnly:k,index:X}=x,It=L?b.get(L):void 0,mt=t[X];if(T.integrationProductId){const ot=F.get(T.integrationProductId);T.integrationProduct=ot,T.product=ot?.product,T.integrationProduct||console.error("failed to find transaction's product")}const fe=Q.getMap("transactionOwnerIds")||new Map;!fe.get(T.id)&&T.transactionOwnerId&&(fe.set(T.id,T.transactionOwnerId),Q.setMap("transactionOwnerIds",fe));const ta=fe.get(T.id)||void 0,yr=new Zc({onMutate:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}})}),Ce={workflow:It,transaction:T,singleVariantsRenderable:mt?.workflowConfiguration?.singleVariantsRenderable,stateMutationFunc:k?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async ot=>this.updateTransactionState({...ot,context:{transactionOwnerId:ta,bundleOwnerId:e?.bundleOwnerId}}),graphQlClient:()=>yr,readOnly:k,isReloadedTransaction:mt.type==="transaction"};if(mt.type==="transaction"&&T.workflowState){const ot=JSON.parse(T.workflowState);await Pa(ot),Ce.reloadedState=ot}else if(!k&&mt.workflowState){const ot=JSON.parse(mt.workflowState);await Pa(ot),Ce.reloadedState=ot}return Ce.delayWorkflowStateSync=!0,{experienceOptions:Ce,index:X,options:mt}}),M=(await Promise.all(v)).sort((x,T)=>x.index-T.index);let R=[];for(const x of M){const{experienceOptions:T,options:L}=x,k=new Ki(this,T);await k.getWorkflowManager().getInitializationPromise(),a&&a(),L.type!=="transaction"&&this.customer&&await k.attachCustomerDetails({email:this.customer.emailAddress}),R=[...R,k],k.getWorkflowManager().setWorkflowStateSyncEnabled(!0)}return R}storeCustomer(t){const e=Q.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),Q.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){const r=(await y.getShadowGraphqlClient().query({query:Ko(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data?.integrationProducts;if(!r||r.length===0||!r[0]?.id)throw new Error("Integration product not found.");return new Ta(r[0])}async getIntegrationProductFromExternalIds(t,e,a){const o=(await y.getShadowGraphqlClient().query({query:_o(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 Ta(o)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(Q.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await y.getShadowGraphqlClient().query({query:Yo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await y.getShadowGraphqlClient().mutate({mutation:cs,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 lr=async(i,t)=>(await y.getShadowGraphqlClient().query({query:os,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":i},skipIntegrationCheck:!0},variables:{themeConfigurationId:t}})).data.currentIntegration,rd=async i=>{const e=await y.getShadowGraphqlClient().query({query:Wo,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:i}});if(e.data.transactions.length!==0)return e.data.transactions[0]},od=async(i,t)=>(await y.getShadowGraphqlClient().query({query:rs,errorPolicy:"all",variables:{themeConfigurationId:i,themeInstallId:t}})).data?.marketplaceThemeInstallConfiguration,sd=async i=>(await y.getShadowGraphqlClient().query({query:ls,errorPolicy:"all",variables:{id:i}})).data?.bundles?.[0]?.marketplaceThemeInstallConfiguration,ld=async i=>(await y.getShadowGraphqlClient().query({query:ss,errorPolicy:"all",variables:{id:i}})).data?.transactions?.[0]?.marketplaceThemeInstallConfiguration;async function cr(){const i={};try{const t=await this.loggedInBearerToken();i.Authorization=`Bearer ${t}`}catch{const a=Object.entries(localStorage).find(([r,o])=>r.startsWith("CognitoIdentityServiceProvider")&&r.endsWith("idToken"))?.[0]||"",n=localStorage.getItem(a);n&&!Re(n)&&(i.Authorization=`Bearer ${n}`)}return i}async function dr(i){const e=Q.getMap("bundleOwnerIds")?.get(i),a=await cr();return{bundleOwnerId:e,...a}}async function cd(i){const e=Q.getMap("transactionOwnerIds")?.get(i),a=await cr();return{transactionOwnerId:e,...a}}const dd=async i=>{const t=await dr(i),e=await y.getShadowGraphqlClient().mutate({mutation:gc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:i},context:{headers:t}});if(e.data?.bundleDelete!==i)throw new Error(`Failed to delete bundle: ${e.errors}`)},ud=async i=>{const t=await cd(i),e=await y.getShadowGraphqlClient().mutate({mutation:mc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{ids:[i]},context:{headers:t}});if(!e.data?.transactions||e.data.transactions.length!==1||e.data.transactions[0].id!==i)throw new Error(`Failed to find transaction to read bundle id: ${JSON.stringify(e.errors)}`);return e.data.transactions[0].bundle?.id};function ur(i,t,e,a){const n=e.width*i.zoom,r=e.height*i.zoom;if(a){const s=i,l=Math.max(t.width/e.width,t.height/e.height);s.zoom=Math.max(l,i.zoom);const c=e.width*s.zoom,d=e.height*s.zoom;return s.x=Pe(i.x,t.width-c,0),s.y=Pe(i.y,t.height-d,0),s}const o=i;return o.x=Pe(o.x,-n,t.width),o.y=Pe(o.y,-r,t.height),o}function Pe(i,t,e){return Math.min(Math.max(i,t),e)}class Ar{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=Vn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let r=!1;for(let o=0;o<n.currentFrameSources.length;o++){const s=n.currentFrameSources[o],l=await me(s),c=this.frameData?this.frameData[o]:void 0;ae(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[o]=l,r=!0)}r&&(this.onFrameDataChangeListeners.forEach(o=>o(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Mt.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=We(this.imageData.svg,this.imageData.colors||{},!1);return je(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const r=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(r,n),this.onZoomChangeListeners.forEach(o=>o(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new O("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]=ur(t[s],o,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,r){if(!a||a.length===0||a.some(l=>!l))throw new O("Frame data not set. This is a bug");if(!this.workflowManager)throw new O("No workflow manager set, cannot update offsets.");const o=this.workflowManager.getRegionElements(this.stepName||""),s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((l,c)=>{let d=o.find(u=>u.id===l)?.regionIndex??c;d>=t.length&&(d=c),s(new U([new Ws(l,e,t[d]),new Ys(l,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),r&&r()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const r=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=r,this.maxZoomScale[n]=r*2.5):(this.minZoomScale[n]=r/10,this.maxZoomScale[n]=r*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]=ja(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Ad{traversableScenes(){throw new Error("Method not implemented.")}updateRecipient(t,e,a,n,r,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(){}getInitialOptionIds(){return new Promise(()=>new Set)}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 hr=(i=>(i.SelectFrame="SelectFrame",i.SelectImage="SelectImage",i.Position="Position",i))(hr||{});class gr extends Z{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Ar(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return pt.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 pt.selectImage(this.step,t,this.manager,a),e){const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseAdvancedImageManipulation(){return this.manager.getClient().canUseAddon(Ve.AdvancedImageManipulation)}async canRemoveBackground(){return await this.canUseAdvancedImageManipulation()&&this.hasOriginalImageSelection()&&!!this.frameService?.getImageData()?.src&&!this.frameService?.getImageData()?.svg}async removeBackgroundFromImageSelection(t=!0){if(!await this.canUseAdvancedImageManipulation())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseAdvancedImageManipulation to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await G.removeBackgroundFromAsset(e);t&&await pt.selectImage(this.step,a,this.manager,!1);const n=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}async vectorize(t,e=void 0){const a=t??await this.getOriginalImageSelection();if(!a)throw new Error("You must supply an image selection before attempting to vectorize the image.");const n=await G.vectorizeAsset(a,e);await this.selectImage(n,t!==void 0);const r=this.manager.getStepStorage(this.step.stepName)?.framePatternData||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...r,vectorizedAssetKey:n.key,useOriginalAsset:!1}}),n}async getBackgroundRemovedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.backgroundRemovedAssetKey;if(t)return G.getLocalOrFromServer(t)}async getVectorizedImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.vectorizedAssetKey;if(t)return G.getLocalOrFromServer(t)}hasOriginalImageSelection(){return!!this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey}hasBackgroundRemovedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.backgroundRemovedAssetKey}hasVectorizedImageSelection(){return!!this.getFrameStepStorage()?.framePatternData?.vectorizedAssetKey}async changeColors(t){await pt.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return await P.ensureFullOption(this.step.data.colorOption)}getAvailableColors(){return this.step.data.colorPickerEnabled?pt.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t?.svg?(await rt(t.svg)).colors:void 0}getShouldVectorize(){return this.step.data.shouldVectorize??!1}getVectorizeMaxColors(){return this.step.data.vectorizeMaxColors}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return pt.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){const t=this.manager.getStepStorage(this.step.stepName)?.framePatternData?.originalAssetKey;if(t)return G.getLocalOrFromServer(t)}getUseOriginalImageSelection(){return this.getFrameStepStorage()?.framePatternData?.useOriginalAsset??!1}async setUseOriginalImageSelection(t){const e=this.getFrameStepStorage()?.framePatternData||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const n=await this.getBackgroundRemovedImageSelection();if(!n)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(n,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}isVariantCategoriesEnabled(){return this.step.data.enableVariantCategories??!1}}const hd=C.gql`
2491
2491
  query GetLoggedInCustomer($email: String!) {
2492
2492
  customer(emailAddress: $email) {
2493
2493
  id