@spiffcommerce/core 25.1.1 → 25.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -3378,4 +3378,4 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
3378
3378
  }
3379
3379
  }
3380
3380
  }
3381
- `,Dt=async n=>{var t;for(const e in n.layouts){const A=n.layouts[e].elements.filter(i=>i.type===k.Illustration);for(let i=0;i<A.length;++i){const s=A[i];s.src&&s.svg&&(s.cachedObjectURL=await te(s.svg))}const a=n.layouts[e].elements.filter(i=>i.type===k.Textbox);for(let i=0;i<a.length;++i){const s=a[i];(t=s.fontData)!=null&&t.assetUrl&&await bt(s.fontData.assetUrl)}}},fr=async(n,t)=>{var a;const e=await Y.getShadowGraphqlClient().query({query:ur(((a=t==null?void 0:t.assets)==null?void 0:a.metadata)||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const A=e.data.workflows;if(A===void 0||A.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return A.forEach(i=>{i.steps.forEach(s=>{var o,r,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((r=s.option.defaultVariant)!=null&&r.asset&&T.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&T.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(l=>{l.asset&&T.cacheAsset(l.asset),l.thumbnail&&T.cacheAsset(l.thumbnail),l.material&&T.cacheMaterial(l.material)}),Nt.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.partner.termsMarkdown}),A},Qr=async(n,t)=>{const A=(await t).find(a=>a.id===n);if(!A)throw new Error(`Workflow not found: ${n}`);return A},OA=async(n,t)=>{const e=n.map(o=>Nt.get({id:o,options:t})),A=n.filter((o,r)=>e[r]===void 0);if(A.length===0)return Promise.all(e);const a=fr(A,t),i=A.map(o=>Nt.set({id:o,options:t},Qr(o,a))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},Kt=async(n,t)=>(await OA([n],t))[0],pr=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:R(),panelId:t.name,name:t.name,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),We=(n,t)=>{const e=n.workflowState,A=e?JSON.parse(e):void 0;return A?Object.values(A.layouts).map(a=>a.layout):pr(t.panels)};class bn{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return Y.getShadowGraphqlClient().mutate({...e,mutation:vi})}catch(A){throw console.error(A),new U("Critical - Unable to synchronize workflow state with server.")}},this.initialized=!1,this.options=t,this.options.applicationKey&&si(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 25.1.1"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configureUrls(t,e,A){nt.setHubUrl(t),nt.setServerUrl(e),nt.setServicesApiUrl(A),this.options.applicationKey&&this.getIntegration()}configure(t){nt.setHubUrl(t.hubUrl),nt.setServerUrl(t.serverUrl),nt.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,t.bearerAuthenticationToken&&Da(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return T}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!oi())throw new Error("Application key required to use Flow Service.");return new kn}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");const t=async()=>(await Y.getShadowGraphqlClient().query({query:xi,errorPolicy:"all",fetchPolicy:"no-cache"})).data.currentIntegration;return this.activeIntegration=t(),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(A){return console.error(A),!1}}async authenticateBundleFromLocalStorage(t){var a,i;const e=P.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:qt.Owner});const A=P.getMap("bundlePartnerIds")||new Map;if(A.has(t)){const s=A.get(t),r=(P.getMap("partnerCustomerIds")||new Map).get(s);if(r&&await this.authenticateCustomerId(r)){const l=(i=(a=this.customer)==null?void 0:a.bundleStakeholders)==null?void 0:i.find(g=>{var d;return((d=g.bundle)==null?void 0:d.id)===t});if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var l,g,d,B,h,C;const e=Y.getShadowGraphqlClient(),A=await e.query({query:Er,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!A.data.transactions||A.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const a=A.data.transactions[0];if(!((g=(l=a.product)==null?void 0:l.partner)==null?void 0:g.id))throw new Error(`Unable to read transaction: ${t}`);if(a.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=P.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:qt.Owner});const o=P.getMap("transactionCustomerIds");if(o!=null&&o.has(t)){const w=o.get(t);if(w&&await this.authenticateCustomerId(w)){const E=((B=(d=this.customer)==null?void 0:d.bundleStakeholders)==null?void 0:B.find(m=>{var f,p;return(p=(f=m.bundle)==null?void 0:f.transactions)==null?void 0:p.some(I=>I.id===t)}))||((C=(h=this.customer)==null?void 0:h.stakeholders)==null?void 0:C.find(m=>{var f;return((f=m.transaction)==null?void 0:f.id)===t}));if(E)return Promise.resolve({success:!0,stakeholderType:E.type})}}const c=(await e.query({query:mr,errorPolicy:"all",variables:{id:a.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${a.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:a.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=P.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),P.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const a=(await Y.getShadowGraphqlClient().query({query:sa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return a.id?a.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var A,a;const e=(a=(A=this.customer)==null?void 0:A.stakeholders)==null?void 0:a.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=Y.getShadowGraphqlClient(),a=(await e.query({query:sa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!a.id){const r=(s=(await e.mutate({mutation:rr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!r)throw new Error("Unable to create customer.");return this.storeCustomer(r),this.customer=r,{customer:r,isAuthenticated:!1}}this.storeCustomer(a);const i=await this.authenticateCustomerId(a.id);return{customer:this.customer||a,isAuthenticated:i}}getCustomer(){return this.customer}async authenticateCustomerId(t){var o;const e=Y.getShadowGraphqlClient(),A=P.getMap("customerTokens");if(!(A!=null&&A.has(t)))return!1;const a=A.get(t);if(!a)return!1;const s=(o=(await e.mutate({mutation:cr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:a}})).data)==null?void 0:o.customerAuthenticate;return s?(this.storeCustomer(s),WA(a),this.customer=s,!0):!1}async generateVerificationCode(t){await Y.getShadowGraphqlClient().mutate({mutation:lr,variables:{emailAddress:t}})}async verifyCode(t,e){var i,s;const a=(i=(await Y.getShadowGraphqlClient().mutate({mutation:gr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data)==null?void 0:i.customerVerifyCode;if(a!=null&&a.loginToken){if(!((s=a.partner)!=null&&s.id))throw new Error(`Unable to find customer: ${t}`);const o=P.getMap("customerTokens")||new Map;return o.set(a.id,a.loginToken),P.setMap("customerTokens",o),this.storeCustomer(a),WA(a.loginToken),this.customer={...a,loginToken:void 0},!0}return!1}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await Y.getShadowGraphqlClient().query({query:dr,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,A){var c,l,g,d,B;const i=(g=(await Y.getShadowGraphqlClient().mutate({mutation:Go(((l=(c=A==null?void 0:A.graphql)==null?void 0:c.productCollection)==null?void 0:l.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((h,C)=>({key:h[0],value:h[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:g.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=P.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),P.setMap("bundlePartnerIds",s);const o=P.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),P.setMap("bundleOwnerIds",o);const r=new Ve(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(B=(d=A==null?void 0:A.graphql)==null?void 0:d.productCollection)==null?void 0:B.eagerFetchProducts,createNewGlobalState:!0});return await r.getInitializationPromise(),r}async getExistingBundle(t,e,A,a){var w,u,E,m,f,p,I,Q,F,y,x;const i=P.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),r=((w=Object.entries(localStorage).find(([v,N])=>v.startsWith("CognitoIdentityServiceProvider")&&v.endsWith("idToken")))==null?void 0:w[0])||"",c=localStorage.getItem(r),l={};c&&!ye(c)&&(l.Authorization=`Bearer ${c}`);const g={bundleOwnerId:s,...l,...(u=a==null?void 0:a.graphql)==null?void 0:u.additionalHeaders},d=await Y.getShadowGraphqlClient().query({query:Ho(((m=(E=a==null?void 0:a.graphql)==null?void 0:E.productCollection)==null?void 0:m.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:g}});if(!((f=d.data)!=null&&f.bundles)||((p=d.data)==null?void 0:p.bundles.length)===0||!((I=d.data)!=null&&I.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const B=(Q=d.data)==null?void 0:Q.bundles[0],h=P.getMap("bundlePartnerIds")||new Map;h.set(B.id,B.partner.id),P.setMap("bundlePartnerIds",h);const C=new Ve(this,B,e,A,s,{additionalHeaders:(F=a==null?void 0:a.graphql)==null?void 0:F.additionalHeaders,eagerFetchProducts:(x=(y=a==null?void 0:a.graphql)==null?void 0:y.productCollection)==null?void 0:x.eagerFetchProducts});return await C.getInitializationPromise(),C}async duplicateBundle(t,e,A,a){var w,u,E,m,f,p,I,Q;const i=(w=P.getMap("bundleOwnerIds"))==null?void 0:w.get(t),o=((u=Object.entries(localStorage).find(([F,y])=>F.startsWith("CognitoIdentityServiceProvider")&&F.endsWith("idToken")))==null?void 0:u[0])||"",r=localStorage.getItem(o),c={};r&&!ye(r)&&(c.Authorization=`Bearer ${r}`);const l={bundleOwnerId:i,...c,...(E=a==null?void 0:a.graphql)==null?void 0:E.additionalHeaders},d=(p=(await Y.getShadowGraphqlClient().mutate({mutation:To(((f=(m=a==null?void 0:a.graphql)==null?void 0:m.productCollection)==null?void 0:f.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:A},context:{headers:l},fetchPolicy:"no-cache"})).data)==null?void 0:p.bundleDuplicate;if(!(d!=null&&d.id))throw new Error("Unable to duplicate bundle");const B=P.getMap("bundlePartnerIds")||new Map;B.set(d.id,d.partner.id),P.setMap("bundlePartnerIds",B);const h=P.getMap("bundleOwnerIds")||new Map;h.set(d.id,d.bundleOwnerId),P.setMap("bundleOwnerIds",h);const C=new Ve(this,d,void 0,void 0,d.bundleOwnerId,{eagerFetchProducts:(Q=(I=a==null?void 0:a.graphql)==null?void 0:I.productCollection)==null?void 0:Q.eagerFetchProducts});return await C.getInitializationPromise(),C}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...A}=t;return(await Y.getShadowGraphqlClient().query({query:Zo(e??!1),variables:{...A,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){var i;if(!this.customer)throw new Error("Customer not authenticated.");const t=await Y.getShadowGraphqlClient().query({query:bo,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const A=t.data.customers[0].bundleStakeholders||[],a=P.getMap("bundlePartnerIds")||new Map;return A.forEach(s=>{var o,r;(o=s.bundle)!=null&&o.id&&((r=s.bundle.partner)!=null&&r.id)&&a.set(s.bundle.id,s.bundle.partner.id)}),P.setMap("bundlePartnerIds",a),A}async getWorkflowExperience(t,e,A,a){var g,d,B,h,C;if(!a)return await this.getWorkflowExperienceDeprecated(t,e,A);const i=async()=>{var u,E,m;const w=Y.getShadowGraphqlClient();if(a.type==="transaction"){const{transactionId:f,readOnly:p}=a,I=await w.query({query:he,variables:{ids:[f]},errorPolicy:"all",fetchPolicy:"no-cache"});if(!((u=I.data)!=null&&u.transactions)||I.data.transactions.length===0)throw new U("Existing transaction not found.");const Q=(E=I.data)==null?void 0:E.transactions[0];if(!Q.workflowId)throw new U("Existing transaction has no workflow ID.");const F=await Kt(Q.workflowId);if(!Q.product)throw new U("Failed to load transaction, product not available.");return!this.activeIntegration&&((m=Q.integrationProduct)!=null&&m.integration)&&(this.activeIntegration=Promise.resolve(Q.integrationProduct.integration)),{transaction:Q,workflow:F,readOnly:p}}if(a.type==="integration"||a.type==="external"){const f=async()=>{const F=a.type==="integration"?{integrationProductId:a.integrationProductId}:{externalIntegrationId:a.externalIntegrationId,externalProductId:a.externalProductId},y=await w.mutate({mutation:qA,variables:{...F,workflowId:a.workflowId,designName:a.designName,claim:!0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!y.data||!y.data.transactionCreate)throw new U("Failed to create transaction!");const x=y.data.transactionCreate;if(!x.product)throw new U("Failed to create transaction, product not available.");return x},p=Kt(a.workflowId,a==null?void 0:a.graphql),[I,Q]=await Promise.all([f(),p]);return{transaction:I,workflow:Q}}throw new U("No workflow ID provided.")},{transaction:s,workflow:o,readOnly:r}=await i();this.currencyCode=(g=s.product.partner)==null?void 0:g.currencyCode;const c={product:s.product,transaction:s,layouts:[],singleVariantsRenderable:(d=a==null?void 0:a.workflowConfiguration)==null?void 0:d.singleVariantsRenderable,stateMutationFunc:r?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async w=>{const E=(P.getMap("transactionOwnerIds")||new Map).get(s.id)||void 0;return this.updateTransactionState({...w,context:{transactionOwnerId:E}})},readOnly:r,workflow:o};if(a.type==="transaction"&&s.workflowState){const w=JSON.parse(s.workflowState);c.layouts=Object.values(w.layouts).map(u=>u.layout),await Et(w),await Dt(w),c.reloadedState=w}else if(!r&&a.workflowState){const w=JSON.parse(a.workflowState);c.layouts=Object.values(w.layouts).map(u=>u.layout),await Et(w),await Dt(w),c.reloadedState=w}else c.layouts=We(c.transaction,c.workflow);if(c.renderableContextService=new Ee(c.layouts),a.previewService?(c.previewService=a.previewService,(B=c.product)!=null&&B.modelUrl&&(c.modelContainer=c.previewService.loadModel({model:c.product.modelUrl,contextService:c.renderableContextService}))):(c.previewService=A&&A(o),(h=c.product)!=null&&h.modelUrl&&(c.modelContainer=(C=c.previewService)==null?void 0:C.loadModel({model:c.product.modelUrl,contextService:c.renderableContextService}))),a.type!=="transaction"){const w=P.getMap("transactionOwnerIds")||new Map;w.set(s.id,s.transactionOwnerId),P.setMap("transactionOwnerIds",w)}else c.isReloadedTransaction=!0;this.initialized=!0,this.experienceOptions=c;const l=new zt(this,c);return await l.getWorkflowManager().getInitializationPromise(),a.type!=="transaction"&&this.customer&&await l.attachCustomerDetails({email:this.customer.emailAddress}),l}async getWorkflowExperiences(t,e){if(t.length===0)throw new U("No options provided!");const A=Y.getShadowGraphqlClient(),a=async p=>{var y,x,v;if(p.length===0)return[];const I=p.map(N=>N.option.transactionId),Q=await A.query({query:he,variables:{ids:I},errorPolicy:"all",fetchPolicy:"no-cache"}),F=Q.data.transactions;if(F.length!==p.length){const N=((x=(y=Q.errors)==null?void 0:y[0])==null?void 0:x.message)||"Unknown error";throw new U(`Not all transactions were found: ${N}`)}return!this.activeIntegration&&((v=F[0].integrationProduct)!=null&&v.integration)&&(this.activeIntegration=Promise.resolve(F[0].integrationProduct.integration)),F.map((N,H)=>{var V;return{transaction:N,workflowId:N.workflowId,readOnly:((V=p.find(z=>z.option.transactionId===N.id))==null?void 0:V.option.readOnly)??!1,index:p[H].index}})},i=async p=>{var F,y,x;if(p.length===0)return[];const I=await A.mutate({mutation:Yi,variables:{inputs:p.map(v=>({integrationProductId:v.option.type==="integration"?v.option.integrationProductId:void 0,externalIntegrationId:v.option.type==="external"?v.option.externalIntegrationId:void 0,externalProductId:v.option.type==="external"?v.option.externalProductId:void 0,workflowId:v.option.workflowId,designName:v.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),Q=(F=I.data)==null?void 0:F.transactionCreateMany;if(!Q||Q.length===0){const v=((x=(y=I.errors)==null?void 0:y[0])==null?void 0:x.message)||"Unknown error";throw new U(`Failed to create transactions: ${v}`)}return Q.map((v,N)=>({transaction:v,workflowId:v.workflowId,readOnly:!1,index:p[N].index}))},s=t.map((p,I)=>({option:p,index:I})),o=s.filter(p=>p.option.type==="transaction"),r=s.filter(p=>p.option.type==="integration"||p.option.type==="external"),c=LA(o,10),l=LA(r,10),g=(await Promise.all([...c.map(a),...l.map(i)])).flat(),d=[...new Set(g.map(p=>p.workflowId))],B=await OA(d,e),h=new Map(B.map(p=>[p.id,p])),C=P.getMap("transactionOwnerIds")||new Map,w=g.map(async p=>{var V;const{transaction:I,workflowId:Q,readOnly:F,index:y}=p,x=h.get(Q),v=t[y];!C.get(I.id)&&I.transactionOwnerId&&C.set(I.id,I.transactionOwnerId);const N=C.get(I.id)||void 0,H={product:I.product,transaction:I,layouts:[],singleVariantsRenderable:(V=v==null?void 0:v.workflowConfiguration)==null?void 0:V.singleVariantsRenderable,stateMutationFunc:F?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async z=>this.updateTransactionState({...z,context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),readOnly:F,workflow:x,isReloadedTransaction:v.type==="transaction"};if(v.type==="transaction"&&I.workflowState){const z=JSON.parse(I.workflowState);H.layouts=Object.values(z.layouts||{}).map(at=>at.layout),await Et(z),await Dt(z),H.reloadedState=z}else if(!F&&v.workflowState){const z=JSON.parse(v.workflowState);H.layouts=Object.values(z.layouts||{}).map(at=>at.layout),await Et(z),await Dt(z),H.reloadedState=z}else H.layouts=We(H.transaction,H.workflow);return H.renderableContextService=new Ee(H.layouts),H.delayWorkflowStateSync=!0,this.initialized=!0,this.experienceOptions=H,{experienceOptions:H,index:y,options:v}}),u=await Promise.all(w);P.setMap("transactionOwnerIds",C);const m=u.sort((p,I)=>p.index-I.index).map(async p=>{const{experienceOptions:I,options:Q}=p,F=new zt(this,I);return await F.getWorkflowManager().getInitializationPromise(),Q.type!=="transaction"&&this.customer&&await F.attachCustomerDetails({email:this.customer.emailAddress}),F}),f=await Promise.all(m);return f.forEach(p=>p.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),f}async initFromIntegrationProduct(t){var s;if(t==="")throw new U("No integration product ID provided.");const A=await Y.getShadowGraphqlClient().mutate({mutation:qA,variables:{integrationProductId:t,claim:!0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new U("Failed to create transaction!");const a=A.data.transactionCreate;if(!a.product)throw new U("Failed to create transaction, product not available.");this.currencyCode=(s=a.product.partner)==null?void 0:s.currencyCode;const i=P.getMap("transactionOwnerIds")||new Map;i.set(a.id,a.transactionOwnerId),P.setMap("transactionOwnerIds",i),this.experienceOptions={product:a.product,transaction:a,layouts:[],stateMutationFunc:async o=>this.updateTransactionState({...o,context:{transactionOwnerId:a.transactionOwnerId}})},this.initialized=!0}async initFromTransaction(t,e=!1){var o,r,c,l;if(t==="")throw new U("No transaction ID provided.");const A=Y.getShadowGraphqlClient(),a=async()=>{var B,h;const d=(B=(await A.query({query:he,variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:B.transactions[0];if(!d)throw new U("Failed to read transaction.");if(!d.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(h=d.product.partner)==null?void 0:h.currencyCode,this.experienceOptions={product:d.product,transaction:d,layouts:[],stateMutationFunc:async()=>{throw new O("State mutation is forbidden in read only mode!")},readOnly:e},this.initialized=!0};if(e)return await a();const i=P.getMap("transactionOwnerIds")||new Map,s=i.get(t);if(s){const d=(o=(await A.query({query:he,variables:{ids:[t]},errorPolicy:"all"})).data)==null?void 0:o.transactions[0];if(!d)throw new U("Failed to read transaction.");if(!d.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(r=d.product.partner)==null?void 0:r.currencyCode,this.experienceOptions={product:d.product,transaction:d,layouts:[],stateMutationFunc:async B=>this.updateTransactionState({...B,context:{transactionOwnerId:s}}),readOnly:e},this.initialized=!0;return}try{const d=(c=(await A.mutate({mutation:Pi,variables:{id:t},errorPolicy:"all"})).data)==null?void 0:c.transactionClaim;if(!d)throw new U("Failed to read transaction.");if(!d.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(l=d.product.partner)==null?void 0:l.currencyCode,d.transactionOwnerId&&(i.set(d.id,d.transactionOwnerId),P.setMap("transactionOwnerIds",i)),this.experienceOptions={product:d.product,transaction:d,layouts:[],stateMutationFunc:async B=>this.updateTransactionState({...B,context:{transactionOwnerId:d.transactionOwnerId}}),readOnly:e},this.initialized=!0}catch{throw new U("Attempted to access a transaction that isn't available.")}}async getWorkflowExperienceDeprecated(t,e,A){var a,i,s,o;if(!this.initialized||!this.experienceOptions)throw new U("Cannot launch experience: Not initialized.");if(this.experienceOptions.transaction.workflowId){const r=await Kt(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=r,this.experienceOptions.transaction.workflowState){const l=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(l.layouts).map(g=>g.layout),await Et(l),await Dt(l),this.experienceOptions.reloadedState=l}this.experienceOptions.previewService=A&&A(r),this.experienceOptions.renderableContextService=new Ee(this.experienceOptions.layouts),(a=this.experienceOptions.product)!=null&&a.modelUrl&&(this.experienceOptions.modelContainer=(i=this.experienceOptions.previewService)==null?void 0:i.loadModel({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}));const c=new zt(this,this.experienceOptions);return await c.getWorkflowManager().getInitializationPromise(),c}if(t){const c=(P.getMap("transactionOwnerIds")||new Map).get(this.experienceOptions.transaction.id),l=Y.getShadowGraphqlClient().mutate({mutation:Ni,variables:{workflowId:t,id:this.experienceOptions.transaction.id},context:{transactionOwnerId:c}}),g=Kt(t);if(await Promise.all([l,g]),this.experienceOptions.workflow=await g,e){const B=JSON.parse(e);this.experienceOptions.layouts=Object.values(B.layouts).map(h=>h.layout),await Et(B),await Dt(B),this.experienceOptions.reloadedState=B}else this.experienceOptions.layouts=We(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await g),this.experienceOptions.renderableContextService=new Ee(this.experienceOptions.layouts),(s=this.experienceOptions.product)!=null&&s.modelUrl&&(this.experienceOptions.modelContainer=(o=this.experienceOptions.previewService)==null?void 0:o.loadModel({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}));const d=new zt(this,this.experienceOptions);return await d.getWorkflowManager().getInitializationPromise(),d}throw new U("No workflow ID provided.")}getPreviewService(){var t;return(t=this.experienceOptions)==null?void 0:t.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new U("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new U("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}storeCustomer(t){const e=P.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),P.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t){var i,s;const a=(i=(await Y.getShadowGraphqlClient().query({query:Hi,variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:i.integrationProducts;if(!a||a.length===0||!((s=a[0])!=null&&s.id))throw new Error("Integration product not found.");return new gA(a[0])}async getIntegrationProductFromExternalIds(t,e){var s;const i=(s=(await Y.getShadowGraphqlClient().query({query:bi,variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProductFromExternalIds;if(!(i!=null&&i.id))throw new Error("Integration product not found.");return new gA(i)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const A=(P.getMap("transactionOwnerIds")||new Map).get(t)||void 0,a=await Y.getShadowGraphqlClient().query({query:Ri,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:A}});if(!a.data.transactions||a.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return a.data.transactions[0].transactionShareActions}}class Ir{getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,A){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,A){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Un=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Un||{});class Gn extends At{constructor(t,e,A){var a;super(t,e,A),this.frameService=(a=this.manager.getStepSpecificServices(this.getId()))==null?void 0:a.frameService}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ct.selectVariant(this.step,t.getResource(),e,this.manager,A=>this.setUpdateState(A))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,A=!0){var a;if(await ct.selectImage(this.step,t,this.manager,A),e){const i=((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Me.BackgroundRemover)}async canRemoveBackground(){var t,e,A,a;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((a=(A=this.frameService)==null?void 0:A.getImageData())!=null&&a.svg)}async removeBackgroundFromImageSelection(t=!0){var i;if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const A=await T.removeBackgroundFromAsset(e);t&&await ct.selectImage(this.step,A,this.manager,!1);const a=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,backgroundRemovedAssetKey:A.key,useOriginalAsset:!t}}),A}changeColors(t){ct.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?ct.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ct.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,A,a){return a&&a.length>1&&t===void 0?"SelectFrame":e||A||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.originalAssetKey;if(t)return T.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.backgroundRemovedAssetKey;if(t)return T.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var a;const e=((a=this.getFrameStepStorage())==null?void 0:a.framePatternData)||{};if(e.useOriginalAsset===t)return;const A=await this.getOriginalImageSelection();if(!A)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(A,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}exports.AddonHandle=Me;exports.ArrayInput=or;exports.AspectType=st;exports.AssetNotFoundError=dt;exports.AssetType=Xt;exports.BringForwardCommand=Hs;exports.BringToBackCommand=Rs;exports.BringToFrontCommand=ks;exports.CanvasCommand=J;exports.CollectionProduct=Qe;exports.ColorOptionGlobalPropertyHandle=lA;exports.CommandContext=Va;exports.ConversionDataType=Ca;exports.ConversionLocation=ha;exports.CreateElementCommand=j;exports.CreateLayoutCommand=MA;exports.DeleteElementCommand=Ct;exports.DigitalContentStepHandle=fn;exports.FileUploadGlobalPropertyHandle=xn;exports.FlowExecutionNodeResult=jt;exports.FlowExecutionResult=Rn;exports.FlowService=kn;exports.FontAlignmentCommand=Za;exports.FontColorCommand=Xa;exports.FontSizeCommand=qa;exports.FontSourceCommand=sA;exports.FrameService=tn;exports.FrameStep=Un;exports.FrameStepHandle=Gn;exports.GlobalPropertyHandle=Re;exports.GroupCommand=G;exports.IllustrationStepHandle=dn;exports.InformationMessageType=ge;exports.InformationStepHandle=mn;exports.IntegrationProduct=gA;exports.IntegrationType=da;exports.LayoutElementFactory=Us;exports.LayoutElementType=k;exports.LayoutNotFoundError=X;exports.LayoutRenderingPurpose=Pt;exports.MaterialStepHandle=Bn;exports.MisconfigurationError=$t;exports.MockWorkflowManager=Ir;exports.ModelStepHandle=hn;exports.ModuleStepHandle=Qn;exports.MoveCommand=Ms;exports.ObjectInput=JA;exports.ObjectInputType=Hn;exports.OptionGlobalPropertyHandle=UA;exports.OptionNotFoundError=Zt;exports.ParseError=yt;exports.PictureStepHandle=Cn;exports.ProductCameraRig=Ba;exports.ProductCollection=Pn;exports.ProductWorkflow=Yt;exports.PromiseCache=Nt;exports.PromiseQueue=fA;exports.QuestionStepHandle=wn;exports.QueueablePromise=mA;exports.ResizeCommand=xs;exports.ResourceNotFoundError=vt;exports.RotateCommand=Ss;exports.ScaleAxis=W;exports.SendBackwardsCommand=bs;exports.ShapeStepHandle=un;exports.ShareActionType=ga;exports.SpiffCommerceClient=bn;exports.StakeholderType=qt;exports.StepAspectType=la;exports.StepHandle=At;exports.StepType=M;exports.TextAlgorithm=Qt;exports.TextChangeCommand=$a;exports.TextGlobalPropertyHandle=Yn;exports.TextInput=sr;exports.TextStepHandle=En;exports.Transform=Nn;exports.TransformCollection=vn;exports.UnhandledBehaviorError=O;exports.UnitOfMeasurement=wa;exports.UpdateImageSourceCommand=vs;exports.Variant=it;exports.WorkflowExperienceEventType=yn;exports.WorkflowExperienceImpl=zt;exports.assetService=T;exports.browserColorToHex=Ha;exports.cmPerPixel=Bs;exports.createDesign=Fn;exports.currentDirection=ls;exports.dataUrlFromExternalUrl=Ai;exports.designService=fe;exports.determineCorrectFontSizeAndLines=Wt;exports.digitalContentStepService=SA;exports.fetchAsString=tt;exports.findAngle=as;exports.findElement=L;exports.findPmsColors=Xi;exports.frameDataCache=Mt;exports.frameStepService=ct;exports.generate=R;exports.generateCommands=Mn;exports.generateSVGWithUnknownColors=ot;exports.generateStateFromDesignInputSteps=ko;exports.getAttributesFromArrayBuffer=se;exports.getAxisAlignedBoundingBox=As;exports.getBoundedOffsets=_a;exports.getElementVertices=gs;exports.getFrameData=ce;exports.getNEPoint=rs;exports.getNWPoint=os;exports.getPointOfRotation=ss;exports.getSEPoint=cs;exports.getSvgElement=Ne;exports.getTrueCoordinates=is;exports.getWorkflow=Kt;exports.getWorkflows=OA;exports.graphQlManager=Y;exports.illustrationStepService=Vt;exports.isCloseToValue=ns;exports.loadFont=bt;exports.matchHexToPms=Ki;exports.materialStepService=xA;exports.mmPerPixel=ds;exports.modelStepService=YA;exports.moduleStepService=PA;exports.optionService=_;exports.patternImageDataCache=lt;exports.persistenceService=P;exports.pictureStepService=vA;exports.pmsToRgb=ji;exports.questionStepService=NA;exports.registerFetchImplementation=$n;exports.registerWindowImplementation=Zn;exports.rehydrateSerializedLayout=Et;exports.rgbToPms=Ra;exports.rotateAroundPoint=Lt;exports.sanitizeSvgTree=ve;exports.setBearerAuthenticationToken=Da;exports.setCanvasModule=wA;exports.shapeStepService=St;exports.shortenUrl=An;exports.spiffCoreConfiguration=nt;exports.stepAspectValuesToDesignInputSteps=No;exports.svgColorValueToDefinition=nA;exports.svgStringDimensions=pA;exports.svgToDataUrl=hA;exports.textStepService=q;exports.toast=nn;exports.xmlSerializer=ae;
3381
+ `,Dt=async n=>{var t;for(const e in n.layouts){const A=n.layouts[e].elements.filter(i=>i.type===k.Illustration);for(let i=0;i<A.length;++i){const s=A[i];s.src&&s.svg&&(s.cachedObjectURL=await te(s.svg))}const a=n.layouts[e].elements.filter(i=>i.type===k.Textbox);for(let i=0;i<a.length;++i){const s=a[i];(t=s.fontData)!=null&&t.assetUrl&&await bt(s.fontData.assetUrl)}}},fr=async(n,t)=>{var a;const e=await Y.getShadowGraphqlClient().query({query:ur(((a=t==null?void 0:t.assets)==null?void 0:a.metadata)||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const A=e.data.workflows;if(A===void 0||A.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return A.forEach(i=>{i.steps.forEach(s=>{var o,r,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((r=s.option.defaultVariant)!=null&&r.asset&&T.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&T.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(l=>{l.asset&&T.cacheAsset(l.asset),l.thumbnail&&T.cacheAsset(l.thumbnail),l.material&&T.cacheMaterial(l.material)}),Nt.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.partner.termsMarkdown}),A},Qr=async(n,t)=>{const A=(await t).find(a=>a.id===n);if(!A)throw new Error(`Workflow not found: ${n}`);return A},OA=async(n,t)=>{const e=n.map(o=>Nt.get({id:o,options:t})),A=n.filter((o,r)=>e[r]===void 0);if(A.length===0)return Promise.all(e);const a=fr(A,t),i=A.map(o=>Nt.set({id:o,options:t},Qr(o,a))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},Kt=async(n,t)=>(await OA([n],t))[0],pr=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:R(),panelId:t.name,name:t.name,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),We=(n,t)=>{const e=n.workflowState,A=e?JSON.parse(e):void 0;return A?Object.values(A.layouts).map(a=>a.layout):pr(t.panels)};class bn{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return Y.getShadowGraphqlClient().mutate({...e,mutation:vi})}catch(A){throw console.error(A),new U("Critical - Unable to synchronize workflow state with server.")}},this.initialized=!1,this.options=t,this.options.applicationKey&&si(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 25.1.2"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configureUrls(t,e,A){nt.setHubUrl(t),nt.setServerUrl(e),nt.setServicesApiUrl(A),this.options.applicationKey&&this.getIntegration()}configure(t){nt.setHubUrl(t.hubUrl),nt.setServerUrl(t.serverUrl),nt.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,t.bearerAuthenticationToken&&Da(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return T}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!oi())throw new Error("Application key required to use Flow Service.");return new kn}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");const t=async()=>(await Y.getShadowGraphqlClient().query({query:xi,errorPolicy:"all",fetchPolicy:"no-cache"})).data.currentIntegration;return this.activeIntegration=t(),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(A){return console.error(A),!1}}async authenticateBundleFromLocalStorage(t){var a,i;const e=P.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:qt.Owner});const A=P.getMap("bundlePartnerIds")||new Map;if(A.has(t)){const s=A.get(t),r=(P.getMap("partnerCustomerIds")||new Map).get(s);if(r&&await this.authenticateCustomerId(r)){const l=(i=(a=this.customer)==null?void 0:a.bundleStakeholders)==null?void 0:i.find(g=>{var d;return((d=g.bundle)==null?void 0:d.id)===t});if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var l,g,d,B,h,C;const e=Y.getShadowGraphqlClient(),A=await e.query({query:Er,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!A.data.transactions||A.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const a=A.data.transactions[0];if(!((g=(l=a.product)==null?void 0:l.partner)==null?void 0:g.id))throw new Error(`Unable to read transaction: ${t}`);if(a.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=P.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:qt.Owner});const o=P.getMap("transactionCustomerIds");if(o!=null&&o.has(t)){const w=o.get(t);if(w&&await this.authenticateCustomerId(w)){const E=((B=(d=this.customer)==null?void 0:d.bundleStakeholders)==null?void 0:B.find(m=>{var f,p;return(p=(f=m.bundle)==null?void 0:f.transactions)==null?void 0:p.some(I=>I.id===t)}))||((C=(h=this.customer)==null?void 0:h.stakeholders)==null?void 0:C.find(m=>{var f;return((f=m.transaction)==null?void 0:f.id)===t}));if(E)return Promise.resolve({success:!0,stakeholderType:E.type})}}const c=(await e.query({query:mr,errorPolicy:"all",variables:{id:a.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${a.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:a.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=P.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),P.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const a=(await Y.getShadowGraphqlClient().query({query:sa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return a.id?a.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var A,a;const e=(a=(A=this.customer)==null?void 0:A.stakeholders)==null?void 0:a.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=Y.getShadowGraphqlClient(),a=(await e.query({query:sa,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!a.id){const r=(s=(await e.mutate({mutation:rr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!r)throw new Error("Unable to create customer.");return this.storeCustomer(r),this.customer=r,{customer:r,isAuthenticated:!1}}this.storeCustomer(a);const i=await this.authenticateCustomerId(a.id);return{customer:this.customer||a,isAuthenticated:i}}getCustomer(){return this.customer}async authenticateCustomerId(t){var o;const e=Y.getShadowGraphqlClient(),A=P.getMap("customerTokens");if(!(A!=null&&A.has(t)))return!1;const a=A.get(t);if(!a)return!1;const s=(o=(await e.mutate({mutation:cr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:a}})).data)==null?void 0:o.customerAuthenticate;return s?(this.storeCustomer(s),WA(a),this.customer=s,!0):!1}async generateVerificationCode(t){await Y.getShadowGraphqlClient().mutate({mutation:lr,variables:{emailAddress:t}})}async verifyCode(t,e){var i,s;const a=(i=(await Y.getShadowGraphqlClient().mutate({mutation:gr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data)==null?void 0:i.customerVerifyCode;if(a!=null&&a.loginToken){if(!((s=a.partner)!=null&&s.id))throw new Error(`Unable to find customer: ${t}`);const o=P.getMap("customerTokens")||new Map;return o.set(a.id,a.loginToken),P.setMap("customerTokens",o),this.storeCustomer(a),WA(a.loginToken),this.customer={...a,loginToken:void 0},!0}return!1}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await Y.getShadowGraphqlClient().query({query:dr,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,A){var c,l,g,d,B;const i=(g=(await Y.getShadowGraphqlClient().mutate({mutation:Go(((l=(c=A==null?void 0:A.graphql)==null?void 0:c.productCollection)==null?void 0:l.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((h,C)=>({key:h[0],value:h[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:g.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=P.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),P.setMap("bundlePartnerIds",s);const o=P.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),P.setMap("bundleOwnerIds",o);const r=new Ve(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(B=(d=A==null?void 0:A.graphql)==null?void 0:d.productCollection)==null?void 0:B.eagerFetchProducts,createNewGlobalState:!0});return await r.getInitializationPromise(),r}async getExistingBundle(t,e,A,a){var w,u,E,m,f,p,I,Q,F,y,x;const i=P.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),r=((w=Object.entries(localStorage).find(([v,N])=>v.startsWith("CognitoIdentityServiceProvider")&&v.endsWith("idToken")))==null?void 0:w[0])||"",c=localStorage.getItem(r),l={};c&&!ye(c)&&(l.Authorization=`Bearer ${c}`);const g={bundleOwnerId:s,...l,...(u=a==null?void 0:a.graphql)==null?void 0:u.additionalHeaders},d=await Y.getShadowGraphqlClient().query({query:Ho(((m=(E=a==null?void 0:a.graphql)==null?void 0:E.productCollection)==null?void 0:m.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:g}});if(!((f=d.data)!=null&&f.bundles)||((p=d.data)==null?void 0:p.bundles.length)===0||!((I=d.data)!=null&&I.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const B=(Q=d.data)==null?void 0:Q.bundles[0],h=P.getMap("bundlePartnerIds")||new Map;h.set(B.id,B.partner.id),P.setMap("bundlePartnerIds",h);const C=new Ve(this,B,e,A,s,{additionalHeaders:(F=a==null?void 0:a.graphql)==null?void 0:F.additionalHeaders,eagerFetchProducts:(x=(y=a==null?void 0:a.graphql)==null?void 0:y.productCollection)==null?void 0:x.eagerFetchProducts});return await C.getInitializationPromise(),C}async duplicateBundle(t,e,A,a){var w,u,E,m,f,p,I,Q;const i=(w=P.getMap("bundleOwnerIds"))==null?void 0:w.get(t),o=((u=Object.entries(localStorage).find(([F,y])=>F.startsWith("CognitoIdentityServiceProvider")&&F.endsWith("idToken")))==null?void 0:u[0])||"",r=localStorage.getItem(o),c={};r&&!ye(r)&&(c.Authorization=`Bearer ${r}`);const l={bundleOwnerId:i,...c,...(E=a==null?void 0:a.graphql)==null?void 0:E.additionalHeaders},d=(p=(await Y.getShadowGraphqlClient().mutate({mutation:To(((f=(m=a==null?void 0:a.graphql)==null?void 0:m.productCollection)==null?void 0:f.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:A},context:{headers:l},fetchPolicy:"no-cache"})).data)==null?void 0:p.bundleDuplicate;if(!(d!=null&&d.id))throw new Error("Unable to duplicate bundle");const B=P.getMap("bundlePartnerIds")||new Map;B.set(d.id,d.partner.id),P.setMap("bundlePartnerIds",B);const h=P.getMap("bundleOwnerIds")||new Map;h.set(d.id,d.bundleOwnerId),P.setMap("bundleOwnerIds",h);const C=new Ve(this,d,void 0,void 0,d.bundleOwnerId,{eagerFetchProducts:(Q=(I=a==null?void 0:a.graphql)==null?void 0:I.productCollection)==null?void 0:Q.eagerFetchProducts});return await C.getInitializationPromise(),C}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...A}=t;return(await Y.getShadowGraphqlClient().query({query:Zo(e??!1),variables:{...A,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){var i;if(!this.customer)throw new Error("Customer not authenticated.");const t=await Y.getShadowGraphqlClient().query({query:bo,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const A=t.data.customers[0].bundleStakeholders||[],a=P.getMap("bundlePartnerIds")||new Map;return A.forEach(s=>{var o,r;(o=s.bundle)!=null&&o.id&&((r=s.bundle.partner)!=null&&r.id)&&a.set(s.bundle.id,s.bundle.partner.id)}),P.setMap("bundlePartnerIds",a),A}async getWorkflowExperience(t,e,A,a){var g,d,B,h,C;if(!a)return await this.getWorkflowExperienceDeprecated(t,e,A);const i=async()=>{var u,E,m;const w=Y.getShadowGraphqlClient();if(a.type==="transaction"){const{transactionId:f,readOnly:p}=a,I=await w.query({query:he,variables:{ids:[f]},errorPolicy:"all",fetchPolicy:"no-cache"});if(!((u=I.data)!=null&&u.transactions)||I.data.transactions.length===0)throw new U("Existing transaction not found.");const Q=(E=I.data)==null?void 0:E.transactions[0];if(!Q.workflowId)throw new U("Existing transaction has no workflow ID.");const F=await Kt(Q.workflowId);if(!Q.product)throw new U("Failed to load transaction, product not available.");return!this.activeIntegration&&((m=Q.integrationProduct)!=null&&m.integration)&&(this.activeIntegration=Promise.resolve(Q.integrationProduct.integration)),{transaction:Q,workflow:F,readOnly:p}}if(a.type==="integration"||a.type==="external"){const f=async()=>{const F=a.type==="integration"?{integrationProductId:a.integrationProductId}:{externalIntegrationId:a.externalIntegrationId,externalProductId:a.externalProductId},y=await w.mutate({mutation:qA,variables:{...F,workflowId:a.workflowId,designName:a.designName,claim:!0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!y.data||!y.data.transactionCreate)throw new U("Failed to create transaction!");const x=y.data.transactionCreate;if(!x.product)throw new U("Failed to create transaction, product not available.");return x},p=Kt(a.workflowId,a==null?void 0:a.graphql),[I,Q]=await Promise.all([f(),p]);return{transaction:I,workflow:Q}}throw new U("No workflow ID provided.")},{transaction:s,workflow:o,readOnly:r}=await i();this.currencyCode=(g=s.product.partner)==null?void 0:g.currencyCode;const c={product:s.product,transaction:s,layouts:[],singleVariantsRenderable:(d=a==null?void 0:a.workflowConfiguration)==null?void 0:d.singleVariantsRenderable,stateMutationFunc:r?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async w=>{const E=(P.getMap("transactionOwnerIds")||new Map).get(s.id)||void 0;return this.updateTransactionState({...w,context:{transactionOwnerId:E}})},readOnly:r,workflow:o};if(a.type==="transaction"&&s.workflowState){const w=JSON.parse(s.workflowState);c.layouts=Object.values(w.layouts).map(u=>u.layout),await Et(w),await Dt(w),c.reloadedState=w}else if(!r&&a.workflowState){const w=JSON.parse(a.workflowState);c.layouts=Object.values(w.layouts).map(u=>u.layout),await Et(w),await Dt(w),c.reloadedState=w}else c.layouts=We(c.transaction,c.workflow);if(c.renderableContextService=new Ee(c.layouts),a.previewService?(c.previewService=a.previewService,(B=c.product)!=null&&B.modelUrl&&(c.modelContainer=c.previewService.loadModel({model:c.product.modelUrl,contextService:c.renderableContextService}))):(c.previewService=A&&A(o),(h=c.product)!=null&&h.modelUrl&&(c.modelContainer=(C=c.previewService)==null?void 0:C.loadModel({model:c.product.modelUrl,contextService:c.renderableContextService}))),a.type!=="transaction"){const w=P.getMap("transactionOwnerIds")||new Map;w.set(s.id,s.transactionOwnerId),P.setMap("transactionOwnerIds",w)}else c.isReloadedTransaction=!0;this.initialized=!0,this.experienceOptions=c;const l=new zt(this,c);return await l.getWorkflowManager().getInitializationPromise(),a.type!=="transaction"&&this.customer&&await l.attachCustomerDetails({email:this.customer.emailAddress}),l}async getWorkflowExperiences(t,e){if(t.length===0)throw new U("No options provided!");const A=Y.getShadowGraphqlClient(),a=async p=>{var y,x,v;if(p.length===0)return[];const I=p.map(N=>N.option.transactionId),Q=await A.query({query:he,variables:{ids:I},errorPolicy:"all",fetchPolicy:"no-cache"}),F=Q.data.transactions;if(F.length!==p.length){const N=((x=(y=Q.errors)==null?void 0:y[0])==null?void 0:x.message)||"Unknown error";throw new U(`Not all transactions were found: ${N}`)}return!this.activeIntegration&&((v=F[0].integrationProduct)!=null&&v.integration)&&(this.activeIntegration=Promise.resolve(F[0].integrationProduct.integration)),F.map((N,H)=>{var V;return{transaction:N,workflowId:N.workflowId,readOnly:((V=p.find(z=>z.option.transactionId===N.id))==null?void 0:V.option.readOnly)??!1,index:p[H].index}})},i=async p=>{var F,y,x;if(p.length===0)return[];const I=await A.mutate({mutation:Yi,variables:{inputs:p.map(v=>({integrationProductId:v.option.type==="integration"?v.option.integrationProductId:void 0,externalIntegrationId:v.option.type==="external"?v.option.externalIntegrationId:void 0,externalProductId:v.option.type==="external"?v.option.externalProductId:void 0,workflowId:v.option.workflowId,designName:v.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),Q=(F=I.data)==null?void 0:F.transactionCreateMany;if(!Q||Q.length===0){const v=((x=(y=I.errors)==null?void 0:y[0])==null?void 0:x.message)||"Unknown error";throw new U(`Failed to create transactions: ${v}`)}return Q.map((v,N)=>({transaction:v,workflowId:v.workflowId,readOnly:!1,index:p[N].index}))},s=t.map((p,I)=>({option:p,index:I})),o=s.filter(p=>p.option.type==="transaction"),r=s.filter(p=>p.option.type==="integration"||p.option.type==="external"),c=LA(o,10),l=LA(r,10),g=(await Promise.all([...c.map(a),...l.map(i)])).flat(),d=[...new Set(g.map(p=>p.workflowId))],B=await OA(d,e),h=new Map(B.map(p=>[p.id,p])),C=P.getMap("transactionOwnerIds")||new Map,w=g.map(async p=>{var V;const{transaction:I,workflowId:Q,readOnly:F,index:y}=p,x=h.get(Q),v=t[y];!C.get(I.id)&&I.transactionOwnerId&&C.set(I.id,I.transactionOwnerId);const N=C.get(I.id)||void 0,H={product:I.product,transaction:I,layouts:[],singleVariantsRenderable:(V=v==null?void 0:v.workflowConfiguration)==null?void 0:V.singleVariantsRenderable,stateMutationFunc:F?async()=>{throw new O("State mutation is forbidden in read only mode!")}:async z=>this.updateTransactionState({...z,context:{transactionOwnerId:N,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),readOnly:F,workflow:x,isReloadedTransaction:v.type==="transaction"};if(v.type==="transaction"&&I.workflowState){const z=JSON.parse(I.workflowState);H.layouts=Object.values(z.layouts||{}).map(at=>at.layout),await Et(z),await Dt(z),H.reloadedState=z}else if(!F&&v.workflowState){const z=JSON.parse(v.workflowState);H.layouts=Object.values(z.layouts||{}).map(at=>at.layout),await Et(z),await Dt(z),H.reloadedState=z}else H.layouts=We(H.transaction,H.workflow);return H.renderableContextService=new Ee(H.layouts),H.delayWorkflowStateSync=!0,this.initialized=!0,this.experienceOptions=H,{experienceOptions:H,index:y,options:v}}),u=await Promise.all(w);P.setMap("transactionOwnerIds",C);const m=u.sort((p,I)=>p.index-I.index).map(async p=>{const{experienceOptions:I,options:Q}=p,F=new zt(this,I);return await F.getWorkflowManager().getInitializationPromise(),Q.type!=="transaction"&&this.customer&&await F.attachCustomerDetails({email:this.customer.emailAddress}),F}),f=await Promise.all(m);return f.forEach(p=>p.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),f}async initFromIntegrationProduct(t){var s;if(t==="")throw new U("No integration product ID provided.");const A=await Y.getShadowGraphqlClient().mutate({mutation:qA,variables:{integrationProductId:t,claim:!0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache",context:this.options.applicationKey?{headers:{"X-Application-Key":this.options.applicationKey}}:void 0});if(!A.data||!A.data.transactionCreate)throw new U("Failed to create transaction!");const a=A.data.transactionCreate;if(!a.product)throw new U("Failed to create transaction, product not available.");this.currencyCode=(s=a.product.partner)==null?void 0:s.currencyCode;const i=P.getMap("transactionOwnerIds")||new Map;i.set(a.id,a.transactionOwnerId),P.setMap("transactionOwnerIds",i),this.experienceOptions={product:a.product,transaction:a,layouts:[],stateMutationFunc:async o=>this.updateTransactionState({...o,context:{transactionOwnerId:a.transactionOwnerId}})},this.initialized=!0}async initFromTransaction(t,e=!1){var o,r,c,l;if(t==="")throw new U("No transaction ID provided.");const A=Y.getShadowGraphqlClient(),a=async()=>{var B,h;const d=(B=(await A.query({query:he,variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:B.transactions[0];if(!d)throw new U("Failed to read transaction.");if(!d.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(h=d.product.partner)==null?void 0:h.currencyCode,this.experienceOptions={product:d.product,transaction:d,layouts:[],stateMutationFunc:async()=>{throw new O("State mutation is forbidden in read only mode!")},readOnly:e},this.initialized=!0};if(e)return await a();const i=P.getMap("transactionOwnerIds")||new Map,s=i.get(t);if(s){const d=(o=(await A.query({query:he,variables:{ids:[t]},errorPolicy:"all"})).data)==null?void 0:o.transactions[0];if(!d)throw new U("Failed to read transaction.");if(!d.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(r=d.product.partner)==null?void 0:r.currencyCode,this.experienceOptions={product:d.product,transaction:d,layouts:[],stateMutationFunc:async B=>this.updateTransactionState({...B,context:{transactionOwnerId:s}}),readOnly:e},this.initialized=!0;return}try{const d=(c=(await A.mutate({mutation:Pi,variables:{id:t},errorPolicy:"all"})).data)==null?void 0:c.transactionClaim;if(!d)throw new U("Failed to read transaction.");if(!d.product)throw new U("Failed to load transaction, product not available.");this.currencyCode=(l=d.product.partner)==null?void 0:l.currencyCode,d.transactionOwnerId&&(i.set(d.id,d.transactionOwnerId),P.setMap("transactionOwnerIds",i)),this.experienceOptions={product:d.product,transaction:d,layouts:[],stateMutationFunc:async B=>this.updateTransactionState({...B,context:{transactionOwnerId:d.transactionOwnerId}}),readOnly:e},this.initialized=!0}catch{throw new U("Attempted to access a transaction that isn't available.")}}async getWorkflowExperienceDeprecated(t,e,A){var a,i,s,o;if(!this.initialized||!this.experienceOptions)throw new U("Cannot launch experience: Not initialized.");if(this.experienceOptions.transaction.workflowId){const r=await Kt(this.experienceOptions.transaction.workflowId);if(this.experienceOptions.workflow=r,this.experienceOptions.transaction.workflowState){const l=JSON.parse(this.experienceOptions.transaction.workflowState);this.experienceOptions.layouts=Object.values(l.layouts).map(g=>g.layout),await Et(l),await Dt(l),this.experienceOptions.reloadedState=l}this.experienceOptions.previewService=A&&A(r),this.experienceOptions.renderableContextService=new Ee(this.experienceOptions.layouts),(a=this.experienceOptions.product)!=null&&a.modelUrl&&(this.experienceOptions.modelContainer=(i=this.experienceOptions.previewService)==null?void 0:i.loadModel({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}));const c=new zt(this,this.experienceOptions);return await c.getWorkflowManager().getInitializationPromise(),c}if(t){const c=(P.getMap("transactionOwnerIds")||new Map).get(this.experienceOptions.transaction.id),l=Y.getShadowGraphqlClient().mutate({mutation:Ni,variables:{workflowId:t,id:this.experienceOptions.transaction.id},context:{transactionOwnerId:c}}),g=Kt(t);if(await Promise.all([l,g]),this.experienceOptions.workflow=await g,e){const B=JSON.parse(e);this.experienceOptions.layouts=Object.values(B.layouts).map(h=>h.layout),await Et(B),await Dt(B),this.experienceOptions.reloadedState=B}else this.experienceOptions.layouts=We(this.experienceOptions.transaction,this.experienceOptions.workflow);this.experienceOptions.previewService=A&&A(await g),this.experienceOptions.renderableContextService=new Ee(this.experienceOptions.layouts),(s=this.experienceOptions.product)!=null&&s.modelUrl&&(this.experienceOptions.modelContainer=(o=this.experienceOptions.previewService)==null?void 0:o.loadModel({model:this.experienceOptions.product.modelUrl,contextService:this.experienceOptions.renderableContextService}));const d=new zt(this,this.experienceOptions);return await d.getWorkflowManager().getInitializationPromise(),d}throw new U("No workflow ID provided.")}getPreviewService(){var t;return(t=this.experienceOptions)==null?void 0:t.previewService}getProduct(){if(!this.initialized||!this.experienceOptions)throw new U("Cannot get product: Not initialized.");return this.experienceOptions.product}getTransaction(){if(!this.initialized||!this.experienceOptions)throw new U("Cannot get transaction: Not initialized.");return this.experienceOptions.transaction}storeCustomer(t){const e=P.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),P.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t){var i,s;const a=(i=(await Y.getShadowGraphqlClient().query({query:Hi,variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:i.integrationProducts;if(!a||a.length===0||!((s=a[0])!=null&&s.id))throw new Error("Integration product not found.");return new gA(a[0])}async getIntegrationProductFromExternalIds(t,e){var s;const i=(s=(await Y.getShadowGraphqlClient().query({query:bi,variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProductFromExternalIds;if(!(i!=null&&i.id))throw new Error("Integration product not found.");return new gA(i)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const A=(P.getMap("transactionOwnerIds")||new Map).get(t)||void 0,a=await Y.getShadowGraphqlClient().query({query:Ri,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:A}});if(!a.data.transactions||a.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return a.data.transactions[0].transactionShareActions}}class Ir{getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,A){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,A){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Un=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(Un||{});class Gn extends At{constructor(t,e,A){var a;super(t,e,A),this.frameService=(a=this.manager.getStepSpecificServices(this.getId()))==null?void 0:a.frameService}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ct.selectVariant(this.step,t.getResource(),e,this.manager,A=>this.setUpdateState(A))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,A=!0){var a;if(await ct.selectImage(this.step,t,this.manager,A),e){const i=((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Me.BackgroundRemover)}async canRemoveBackground(){var t,e,A,a;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((a=(A=this.frameService)==null?void 0:A.getImageData())!=null&&a.svg)}async removeBackgroundFromImageSelection(t=!0){var i;if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const A=await T.removeBackgroundFromAsset(e);t&&await ct.selectImage(this.step,A,this.manager,!1);const a=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,backgroundRemovedAssetKey:A.key,useOriginalAsset:!t}}),A}changeColors(t){ct.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?ct.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ct.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,A,a){return a&&a.length>1&&t===void 0?"SelectFrame":e||A||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.originalAssetKey;if(t)return T.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.backgroundRemovedAssetKey;if(t)return T.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var a;const e=((a=this.getFrameStepStorage())==null?void 0:a.framePatternData)||{};if(e.useOriginalAsset===t)return;const A=await this.getOriginalImageSelection();if(!A)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(A,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}exports.AddonHandle=Me;exports.ArrayInput=or;exports.AspectType=st;exports.AssetNotFoundError=dt;exports.AssetType=Xt;exports.BringForwardCommand=Hs;exports.BringToBackCommand=Rs;exports.BringToFrontCommand=ks;exports.CanvasCommand=J;exports.CollectionProduct=Qe;exports.ColorOptionGlobalPropertyHandle=lA;exports.CommandContext=Va;exports.ConversionDataType=Ca;exports.ConversionLocation=ha;exports.CreateElementCommand=j;exports.CreateLayoutCommand=MA;exports.DeleteElementCommand=Ct;exports.DigitalContentStepHandle=fn;exports.FileUploadGlobalPropertyHandle=xn;exports.FlowExecutionNodeResult=jt;exports.FlowExecutionResult=Rn;exports.FlowService=kn;exports.FontAlignmentCommand=Za;exports.FontColorCommand=Xa;exports.FontSizeCommand=qa;exports.FontSourceCommand=sA;exports.FrameService=tn;exports.FrameStep=Un;exports.FrameStepHandle=Gn;exports.GlobalPropertyHandle=Re;exports.GroupCommand=G;exports.IllustrationStepHandle=dn;exports.InformationMessageType=ge;exports.InformationStepHandle=mn;exports.IntegrationProduct=gA;exports.IntegrationType=da;exports.LayoutElementFactory=Us;exports.LayoutElementType=k;exports.LayoutNotFoundError=X;exports.LayoutRenderingPurpose=Pt;exports.MaterialStepHandle=Bn;exports.MisconfigurationError=$t;exports.MockWorkflowManager=Ir;exports.ModelStepHandle=hn;exports.ModuleStepHandle=Qn;exports.MoveCommand=Ms;exports.ObjectInput=JA;exports.ObjectInputType=Hn;exports.OptionGlobalPropertyHandle=UA;exports.OptionNotFoundError=Zt;exports.ParseError=yt;exports.PictureStepHandle=Cn;exports.ProductCameraRig=Ba;exports.ProductCollection=Pn;exports.ProductWorkflow=Yt;exports.PromiseCache=Nt;exports.PromiseQueue=fA;exports.QuestionStepHandle=wn;exports.QueueablePromise=mA;exports.ResizeCommand=xs;exports.ResourceNotFoundError=vt;exports.RotateCommand=Ss;exports.ScaleAxis=W;exports.SendBackwardsCommand=bs;exports.ShapeStepHandle=un;exports.ShareActionType=ga;exports.SpiffCommerceClient=bn;exports.StakeholderType=qt;exports.StepAspectType=la;exports.StepHandle=At;exports.StepType=M;exports.TextAlgorithm=Qt;exports.TextChangeCommand=$a;exports.TextGlobalPropertyHandle=Yn;exports.TextInput=sr;exports.TextStepHandle=En;exports.Transform=Nn;exports.TransformCollection=vn;exports.UnhandledBehaviorError=O;exports.UnitOfMeasurement=wa;exports.UpdateImageSourceCommand=vs;exports.Variant=it;exports.WorkflowExperienceEventType=yn;exports.WorkflowExperienceImpl=zt;exports.assetService=T;exports.browserColorToHex=Ha;exports.cmPerPixel=Bs;exports.createDesign=Fn;exports.currentDirection=ls;exports.dataUrlFromExternalUrl=Ai;exports.designService=fe;exports.determineCorrectFontSizeAndLines=Wt;exports.digitalContentStepService=SA;exports.fetchAsString=tt;exports.findAngle=as;exports.findElement=L;exports.findPmsColors=Xi;exports.frameDataCache=Mt;exports.frameStepService=ct;exports.generate=R;exports.generateCommands=Mn;exports.generateSVGWithUnknownColors=ot;exports.generateStateFromDesignInputSteps=ko;exports.getAttributesFromArrayBuffer=se;exports.getAxisAlignedBoundingBox=As;exports.getBoundedOffsets=_a;exports.getElementVertices=gs;exports.getFrameData=ce;exports.getNEPoint=rs;exports.getNWPoint=os;exports.getPointOfRotation=ss;exports.getSEPoint=cs;exports.getSvgElement=Ne;exports.getTrueCoordinates=is;exports.getWorkflow=Kt;exports.getWorkflows=OA;exports.graphQlManager=Y;exports.illustrationStepService=Vt;exports.isCloseToValue=ns;exports.loadFont=bt;exports.matchHexToPms=Ki;exports.materialStepService=xA;exports.mmPerPixel=ds;exports.modelStepService=YA;exports.moduleStepService=PA;exports.optionService=_;exports.patternImageDataCache=lt;exports.persistenceService=P;exports.pictureStepService=vA;exports.pmsToRgb=ji;exports.questionStepService=NA;exports.registerFetchImplementation=$n;exports.registerWindowImplementation=Zn;exports.rehydrateSerializedLayout=Et;exports.rgbToPms=Ra;exports.rotateAroundPoint=Lt;exports.sanitizeSvgTree=ve;exports.setBearerAuthenticationToken=Da;exports.setCanvasModule=wA;exports.shapeStepService=St;exports.shortenUrl=An;exports.spiffCoreConfiguration=nt;exports.stepAspectValuesToDesignInputSteps=No;exports.svgColorValueToDefinition=nA;exports.svgStringDimensions=pA;exports.svgToDataUrl=hA;exports.textStepService=q;exports.toast=nn;exports.xmlSerializer=ae;
package/dist/index.mjs CHANGED
@@ -16084,7 +16084,7 @@ class Xo {
16084
16084
  } catch (A) {
16085
16085
  throw console.error(A), new U("Critical - Unable to synchronize workflow state with server.");
16086
16086
  }
16087
- }, this.initialized = !1, this.options = t, this.options.applicationKey && Mn(this.options.applicationKey), console.debug("------------------------"), console.debug("Spiff Commerce Core SDK"), console.debug("Version: 25.1.1"), console.debug(`Application Key Provided: ${!!this.options.applicationKey}`), console.debug("------------------------");
16087
+ }, this.initialized = !1, this.options = t, this.options.applicationKey && Mn(this.options.applicationKey), console.debug("------------------------"), console.debug("Spiff Commerce Core SDK"), console.debug("Version: 25.1.2"), console.debug(`Application Key Provided: ${!!this.options.applicationKey}`), console.debug("------------------------");
16088
16088
  }
16089
16089
  /** @deprecated Use `configure` instead */
16090
16090
  configureUrls(t, e, A) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spiffcommerce/core",
3
- "version": "25.1.1",
3
+ "version": "25.1.2",
4
4
  "description": "Core client API for interacting with the Spiff Commerce backend.",
5
5
  "source": "src/index.ts",
6
6
  "main": "./dist/index.js",