@spiffcommerce/core 26.38.0-beta.d98620d3-59a9-5edf-b33f-1e6356cd6536 → 26.38.0-beta.dee44cf8-0a6e-500b-b49b-8c367d7deed0
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 +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +267 -265
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -2234,7 +2234,7 @@
|
|
|
2234
2234
|
}
|
|
2235
2235
|
}
|
|
2236
2236
|
}
|
|
2237
|
-
`;class ql{constructor(){this.internalMap=new Map}async requestKeysForEntity(t,e){const a=new Map;return await this.ensureIdsArePresent([t]),e.forEach(n=>{const i=this.requestKeyForEntityIfAvailable(t,n);i&&a.set(n,i)}),a}async ensureIdsArePresent(t){if(t.every(a=>this.internalMap.has(a)))return;const e=await b.getShadowGraphqlClient().query({query:Gl,errorPolicy:"all",variables:{entityIds:t.filter(a=>!this.internalMap.has(a))}});t.forEach((a,n)=>{const i=e.data.metafieldsMany[n];this.internalMap.set(a,i.map(s=>({key:s.metafieldConfiguration.name,value:s.value})))})}async requestKeyForEntity(t,e){if(!this.internalMap.has(t))return;let a=this.internalMap.get(t);const n=a.find(i=>i.key===e);return n||(await this.ensureIdsArePresent([t]),a=this.internalMap.get(t)),n?JSON.parse(n.value):void 0}requestKeyForEntityIfAvailable(t,e){if(!this.internalMap.has(t))return;const n=this.internalMap.get(t).find(i=>i.key===e);if(n)return JSON.parse(n.value)}}const Mr=new ql;var Tr=(r=>(r.Default="Default",r.Name="Name",r.Price="Price",r))(Tr||{});class La{constructor(t){this.fullFetched=!1,this.fetched=!1,this.collection=t;const e=this.collection.productCollectionProducts;e&&e.length>0&&(this.fullFetched=!0)}getId(){return this.collection.id}getName(){return this.collection.name}getDescription(){return this.collection.description||""}getImage(){return this.collection.image}getProducts(){if(!this.collection.productCollectionProducts)throw new Error("Failed to find products on collection. Ensure you fetch them first!");return this.collection.productCollectionProducts.filter(t=>!!t.product).map(t=>new jt(t))}async fetchProducts(t){if(this.fullFetched)return this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new jt(a));const e=await b.getShadowGraphqlClient().query({query:$o,variables:{id:this.getId(),productIds:t},errorPolicy:"all"});return t||(this.fullFetched=!0),this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new jt(a))}async filterProducts(t,e,a,n){var l,c;const i=await b.getShadowGraphqlClient().query({query:Uo,errorPolicy:"all",variables:{id:this.getId(),filters:t?{link:"And",metafields:t}:void 0,tags:e?{include:e.include??[],exclude:e.exclude??[]}:void 0,sortKey:a,sortDescending:n}});if(!((l=i.data)!=null&&l.productCollections)||((c=i.data)==null?void 0:c.productCollections.length)===0)throw new Error("Failed to filter product collection products.");const s=this.getProducts(),o=i.data.productCollections[0].productCollectionProducts.map(d=>d.product.id);return s.filter(d=>o.includes(d.getId()))}async fetchProductsFeed(t,e,a,n,i,s){var
|
|
2237
|
+
`;class ql{constructor(){this.internalMap=new Map}async requestKeysForEntity(t,e){const a=new Map;return await this.ensureIdsArePresent([t]),e.forEach(n=>{const i=this.requestKeyForEntityIfAvailable(t,n);i&&a.set(n,i)}),a}async ensureIdsArePresent(t){if(t.every(a=>this.internalMap.has(a)))return;const e=await b.getShadowGraphqlClient().query({query:Gl,errorPolicy:"all",variables:{entityIds:t.filter(a=>!this.internalMap.has(a))}});t.forEach((a,n)=>{const i=e.data.metafieldsMany[n];this.internalMap.set(a,i.map(s=>({key:s.metafieldConfiguration.name,value:s.value})))})}async requestKeyForEntity(t,e){if(!this.internalMap.has(t))return;let a=this.internalMap.get(t);const n=a.find(i=>i.key===e);return n||(await this.ensureIdsArePresent([t]),a=this.internalMap.get(t)),n?JSON.parse(n.value):void 0}requestKeyForEntityIfAvailable(t,e){if(!this.internalMap.has(t))return;const n=this.internalMap.get(t).find(i=>i.key===e);if(n)return JSON.parse(n.value)}}const Mr=new ql;var Tr=(r=>(r.Default="Default",r.Name="Name",r.Price="Price",r))(Tr||{});class La{constructor(t){this.fullFetched=!1,this.fetched=!1,this.collection=t;const e=this.collection.productCollectionProducts;e&&e.length>0&&(this.fullFetched=!0)}getId(){return this.collection.id}getName(){return this.collection.name}getDescription(){return this.collection.description||""}getImage(){return this.collection.image}getProducts(){if(!this.collection.productCollectionProducts)throw new Error("Failed to find products on collection. Ensure you fetch them first!");return this.collection.productCollectionProducts.filter(t=>!!t.product).map(t=>new jt(t))}async fetchProducts(t){if(this.fullFetched)return this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new jt(a));const e=await b.getShadowGraphqlClient().query({query:$o,variables:{id:this.getId(),productIds:t},errorPolicy:"all"});return t||(this.fullFetched=!0),this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new jt(a))}async filterProducts(t,e,a,n){var l,c;const i=await b.getShadowGraphqlClient().query({query:Uo,errorPolicy:"all",variables:{id:this.getId(),filters:t?{link:"And",metafields:t}:void 0,tags:e?{include:e.include??[],exclude:e.exclude??[]}:void 0,sortKey:a,sortDescending:n}});if(!((l=i.data)!=null&&l.productCollections)||((c=i.data)==null?void 0:c.productCollections.length)===0)throw new Error("Failed to filter product collection products.");const s=this.getProducts(),o=i.data.productCollections[0].productCollectionProducts.map(d=>d.product.id);return s.filter(d=>o.includes(d.getId()))}async fetchProductsFeed(t,e,a,n,i,s){var d,A,u,h,g,m;if(this.fullFetched){const p=await(a?this.filterProducts(a):this.fetchProducts());return{total:p.length,items:p.slice(t,t+e)}}const o=b.getShadowGraphqlClient();console.log({client:o});const l=await b.getShadowGraphqlClient().query({query:Lo,variables:{id:this.getId(),limit:e,offset:t,filters:a?{link:"And",metafields:a}:void 0,tags:n?{include:n.include??[],exclude:n.exclude??[]}:void 0,sortKey:i,sortDescending:s},errorPolicy:"all",fetchPolicy:this.fetched?"cache-only":"cache-first"});return this.fetched=!0,{items:((u=(A=(d=l==null?void 0:l.data)==null?void 0:d.productCollections)==null?void 0:A[0].productCollectionProductsFeed)==null?void 0:u.items.filter(p=>!!p.product).map(p=>new jt(p)))||[],total:((m=(g=(h=l==null?void 0:l.data)==null?void 0:h.productCollections)==null?void 0:g[0].productCollectionProductsFeed)==null?void 0:m.total)??0}}getTransformCollection(){if(this.collection.transformCollection)return new Qr(this.collection.transformCollection)}getResource(){return this.collection}}class jt{constructor(t){this.product=t.product,this.productResource=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t,e){const n=(this.product.integrationProducts||[]).find(i=>{var c,d,A;const s=(c=i.integration)==null?void 0:c.type,o=((d=i.integration)==null?void 0:d.type)===t,l=e?((A=i.integration)==null?void 0:A.externalIntegrationId)===e:!0;return s&&o&&l});if(!n)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return n}getCurrentIntegration(){const e=(this.product.integrationProducts||[]).find(a=>{var n;return(n=a.integration)==null?void 0:n.isCurrent});if(!e)throw new Error(`Product: ${this.productResource.id} is not linked to this current integration. This is generally due to a configuration error.`);return e}getDefaultWorkflow(){const t=this.product.workflows;if(t===void 0)throw new ht("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(t.length===0)throw new ht("Called getDefaultWorkflow() but no workflows on requested product. Ensure at least 1 workflow is assigned to this product.");const e=this.productResource.workflowId;if(e){const a=t.find(n=>n.workflowName===e);if(a)return new Tt(a)}if(t.length===1)return console.warn("Called getDefaultWorkflow() but no default was configured. There is only one workflow available so we will fall back to using this!"),new Tt(t[0]);throw new ht("Called getDefaultWorkflow() but no default workflow is configured for the requested product. Multiple workflows exist so we can't assume!")}getAllWorkflows(){if((this.product.workflows||[]).length===0)throw new ht("No workflows on configured product. Ensure at least 1 workflow is assigned to this product.");return this.product.workflows.sort((e,a)=>(e.index??0)-(a.index??0)).map(e=>new Tt(e))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(t){var n,i,s,o;const e=this.product.basePrice||0;if(!t)return e;if(!t.integrationType&&!t.externalId&&!t.integrationId)throw new Error("You must provide at least one of the following fields on the includeAdditionalProduct object: integrationType, externalId, integrationId");let a;return t.integrationId?a=(n=this.product.integrationProducts)==null?void 0:n.find(l=>{var c;return((c=l.integration)==null?void 0:c.id)===t.integrationId}):t.externalId?a=(i=this.product.integrationProducts)==null?void 0:i.find(l=>{var c;return((c=l.integration)==null?void 0:c.externalIntegrationId)===t.externalId}):a=(s=this.product.integrationProducts)==null?void 0:s.find(l=>{var c;return((c=l.integration)==null?void 0:c.type)===t.integrationType}),(o=a==null?void 0:a.additionalIntegrationProduct)!=null&&o.product?e+(a.additionalIntegrationProduct.product.basePrice||0):e}async requestMetafields(t){return Mr.requestKeysForEntity(this.product.id,t)}}class Tt{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class Qr{constructor(t){this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(t=>new Nr(t))}}class Nr{constructor(t){this.transform=t}getId(){return this.transform.id}getName(){return this.transform.name}get(){return{position:this.transform.position,rotation:this.transform.rotation,scale:this.transform.scale}}}const Wl=w.gql`
|
|
2238
2238
|
${Ae(!1)}
|
|
2239
2239
|
query GetProductCollections($ids: [String!]!) {
|
|
2240
2240
|
productCollections(ids: $ids) {
|
|
@@ -2399,7 +2399,7 @@
|
|
|
2399
2399
|
}
|
|
2400
2400
|
}
|
|
2401
2401
|
}
|
|
2402
|
-
`;class ic{constructor(t,e=b.getShadowGraphqlClient.bind(b)){this.options=t,this.client=e}query(t){var a,n;const e=(a=this.options)!=null&&a.onQuery?(n=this.options)==null?void 0:n.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){var a,n;const e=(a=this.options)!=null&&a.onMutate?(n=this.options)==null?void 0:n.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}const sc=async(r,t)=>{var n;const e=await b.getShadowGraphqlClient().query({query:hs(((n=t==null?void 0:t.assets)==null?void 0:n.metadata)||!1),errorPolicy:"all",variables:{ids:r}});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!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.steps.forEach(s=>{var o,l,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((l=s.option.defaultVariant)!=null&&l.asset&&U.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&U.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(d=>{d.asset&&U.cacheAsset(d.asset),d.thumbnail&&U.cacheAsset(d.thumbnail),d.material&&U.cacheMaterial(d.material)}),$t.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},oc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},Ga=async(r,t)=>{const e=r.map(o=>$t.get({id:o,options:t})),a=r.filter((o,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=sc(a,t),i=a.map(o=>$t.set({id:o,options:t},oc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},lc=async(r,t)=>(await Ga([r],t))[0],cc=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:N(),panelId:t.name,name:t.name,title:t.title,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})),dc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):cc(t.panels)};class Ac{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return b.getShadowGraphqlClient().mutate({...e,mutation:es})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ci(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 26.38.0-beta.67ad5dcf-77a2-51da-a7de-ffed9137f36a"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,t.bearerAuthenticationToken&&Qn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return U}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!wi())throw new Error("Application key required to use Flow Service.");return new Rr}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=Ur(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(a){return console.error(a),!1}}async authenticateBundleFromLocalStorage(t){var n,i;const e=M.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:_t.Owner});const a=M.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const s=a.get(t),l=(M.getMap("partnerCustomerIds")||new Map).get(s);if(l&&await this.authenticateCustomerId(l)){const d=(i=(n=this.customer)==null?void 0:n.bundleStakeholders)==null?void 0:i.find(A=>{var u;return((u=A.bundle)==null?void 0:u.id)===t});if(d)return Promise.resolve({success:!0,stakeholderType:d.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var d,A,u,h,g,m;const e=b.getShadowGraphqlClient(),a=await e.query({query:gs,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 n=a.data.transactions[0];if(!((A=(d=n.product)==null?void 0:d.partner)==null?void 0:A.id))throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=M.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:_t.Owner});const o=M.getMap("transactionCustomerIds");if(o!=null&&o.has(t)){const p=o.get(t);if(p&&await this.authenticateCustomerId(p)){const C=((h=(u=this.customer)==null?void 0:u.bundleStakeholders)==null?void 0:h.find(y=>{var v,S;return(S=(v=y.bundle)==null?void 0:v.transactions)==null?void 0:S.some(E=>E.id===t)}))||((m=(g=this.customer)==null?void 0:g.stakeholders)==null?void 0:m.find(y=>{var v;return((v=y.transaction)==null?void 0:v.id)===t}));if(C)return Promise.resolve({success:!0,stakeholderType:C.type})}}const c=(await e.query({query:ms,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=M.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),M.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await b.getShadowGraphqlClient().query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var a,n;const e=(n=(a=this.customer)==null?void 0:a.stakeholders)==null?void 0:n.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=b.getShadowGraphqlClient(),n=(await e.query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:tc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!l)throw new Error("Unable to create customer.");return this.storeCustomer(l),this.customer=l,{customer:l,isAuthenticated:!1}}this.storeCustomer(n);const i=await this.authenticateCustomerId(n.id);return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async authenticateCustomerId(t){var o;const e=b.getShadowGraphqlClient(),a=M.getMap("customerTokens");if(!(a!=null&&a.has(t)))return!1;const n=a.get(t);if(!n)return!1;const s=(o=(await e.mutate({mutation:ec,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data)==null?void 0:o.customerAuthenticate;return s?(this.storeCustomer(s),_a(n),this.customer=s,!0):!1}async generateVerificationCode(t){await b.getShadowGraphqlClient().mutate({mutation:ac,variables:{emailAddress:t}})}async verifyCode(t,e){var i,s;const n=(i=(await b.getShadowGraphqlClient().mutate({mutation:nc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data)==null?void 0:i.customerVerifyCode;if(n!=null&&n.loginToken){if(!((s=n.partner)!=null&&s.id))throw new Error(`Unable to find customer: ${t}`);const o=M.getMap("customerTokens")||new Map;return o.set(n.id,n.loginToken),M.setMap("customerTokens",o),this.storeCustomer(n),_a(n.loginToken),this.customer={...n,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 b.getShadowGraphqlClient().query({query:rc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){var c,d,A,u,h;const i=(A=(await b.getShadowGraphqlClient().mutate({mutation:Vo(((d=(c=a==null?void 0:a.graphql)==null?void 0:c.productCollection)==null?void 0:d.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((g,m)=>({key:g[0],value:g[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:A.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=M.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),M.setMap("bundlePartnerIds",s);const o=M.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),M.setMap("bundleOwnerIds",o);const l=new Ke(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(h=(u=a==null?void 0:a.graphql)==null?void 0:u.productCollection)==null?void 0:h.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){var p,f,C,y,v,S,E,B,I,x,F;const i=M.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),l=((p=Object.entries(localStorage).find(([k,Q])=>k.startsWith("CognitoIdentityServiceProvider")&&k.endsWith("idToken")))==null?void 0:p[0])||"",c=localStorage.getItem(l),d={};c&&!Ie(c)&&(d.Authorization=`Bearer ${c}`);const A={bundleOwnerId:s,...d,...(f=n==null?void 0:n.graphql)==null?void 0:f.additionalHeaders},u=await b.getShadowGraphqlClient().query({query:Ro(((y=(C=n==null?void 0:n.graphql)==null?void 0:C.productCollection)==null?void 0:y.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:A}});if(!((v=u.data)!=null&&v.bundles)||((S=u.data)==null?void 0:S.bundles.length)===0||!((E=u.data)!=null&&E.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const h=(B=u.data)==null?void 0:B.bundles[0],g=M.getMap("bundlePartnerIds")||new Map;g.set(h.id,h.partner.id),M.setMap("bundlePartnerIds",g);const m=new Ke(this,h,e,a,s,{additionalHeaders:(I=n==null?void 0:n.graphql)==null?void 0:I.additionalHeaders,eagerFetchProducts:(F=(x=n==null?void 0:n.graphql)==null?void 0:x.productCollection)==null?void 0:F.eagerFetchProducts,existingGlobalPropertyState:u.data.globalPropertyState,readonly:n==null?void 0:n.readonly});return await m.getInitializationPromise(),m}async duplicateBundle(t,e,a,n){var p,f,C,y,v,S,E,B;const i=(p=M.getMap("bundleOwnerIds"))==null?void 0:p.get(t),o=((f=Object.entries(localStorage).find(([I,x])=>I.startsWith("CognitoIdentityServiceProvider")&&I.endsWith("idToken")))==null?void 0:f[0])||"",l=localStorage.getItem(o),c={};l&&!Ie(l)&&(c.Authorization=`Bearer ${l}`);const d={bundleOwnerId:i,...c,...(C=n==null?void 0:n.graphql)==null?void 0:C.additionalHeaders},u=(S=(await b.getShadowGraphqlClient().mutate({mutation:zo(((v=(y=n==null?void 0:n.graphql)==null?void 0:y.productCollection)==null?void 0:v.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:d},fetchPolicy:"no-cache"})).data)==null?void 0:S.bundleDuplicate;if(!(u!=null&&u.id))throw new Error("Unable to duplicate bundle");const h=M.getMap("bundlePartnerIds")||new Map;h.set(u.id,u.partner.id),M.setMap("bundlePartnerIds",h);const g=M.getMap("bundleOwnerIds")||new Map;g.set(u.id,u.bundleOwnerId),M.setMap("bundleOwnerIds",g);const m=new Ke(this,u,void 0,void 0,u.bundleOwnerId,{eagerFetchProducts:(B=(E=n==null?void 0:n.graphql)==null?void 0:E.productCollection)==null?void 0:B.eagerFetchProducts,existingGlobalPropertyState:u.globalPropertyState});return await m.getInitializationPromise(),m}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 b.getShadowGraphqlClient().query({query:tl(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 b.getShadowGraphqlClient().query({query:Oo,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||[],n=M.getMap("bundlePartnerIds")||new Map;return a.forEach(s=>{var o,l;(o=s.bundle)!=null&&o.id&&((l=s.bundle.partner)!=null&&l.id)&&n.set(s.bundle.id,s.bundle.partner.id)}),M.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];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new ht("No options provided!");const a=b.getShadowGraphqlClient(),n=async S=>{var x,F,k;if(S.length===0)return[];const E=S.map(Q=>Q.option.transactionId),B=await a.query({query:ts,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),I=B.data.transactions;if(I.length!==S.length){const Q=((F=(x=B.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Not all transactions were found: ${Q}`)}return!this.activeIntegration&&((k=I[0].integrationProduct)!=null&&k.integration)&&(this.activeIntegration=Promise.resolve(I[0].integrationProduct.integration)),I.map((Q,ot)=>{var R;return{transaction:Q,workflowId:Q.workflowId,readOnly:((R=S.find(et=>et.option.transactionId===Q.id))==null?void 0:R.option.readOnly)??!1,index:S[ot].index}})},i=async S=>{var I,x,F;if(S.length===0)return[];const E=await a.mutate({mutation:Zi,variables:{inputs:S.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})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),B=(I=E.data)==null?void 0:I.transactionCreateMany;if(!B||B.length===0){const k=((F=(x=E.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Failed to create transactions: ${k}`)}return B.map((k,Q)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:S[Q].index}))},s=t.map((S,E)=>({option:S,index:E})),o=s.filter(S=>S.option.type==="transaction"),l=s.filter(S=>S.option.type==="integration"||S.option.type==="external"),c=ja(o,10),d=ja(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(S=>S.workflowId))],h=await Ga(u,e),g=new Map(h.map(S=>[S.id,S])),m=M.getMap("transactionOwnerIds")||new Map,p=A.map(async S=>{var et;const{transaction:E,workflowId:B,readOnly:I,index:x}=S,F=g.get(B),k=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const Q=m.get(E.id)||void 0,ot=new ic({onMutate:()=>({context:{transactionOwnerId:Q,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Q,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})}),R={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:(et=k==null?void 0:k.workflowConfiguration)==null?void 0:et.singleVariantsRenderable,stateMutationFunc:I?async()=>{throw new V("State mutation is forbidden in read only mode!")}:async H=>this.updateTransactionState({...H,context:{transactionOwnerId:Q,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),graphQlClient:()=>ot,readOnly:I,workflow:F,isReloadedTransaction:k.type==="transaction"};if(k.type==="transaction"&&E.workflowState){const H=JSON.parse(E.workflowState);R.layouts=Object.values(H.layouts||{}).map(yt=>yt.layout),await da(H),R.reloadedState=H}else if(!I&&k.workflowState){const H=JSON.parse(k.workflowState);R.layouts=Object.values(H.layouts||{}).map(yt=>yt.layout),await da(H),R.reloadedState=H}else R.layouts=dc(R.transaction,R.workflow);return R.renderableContextService=new kl(R.layouts),R.delayWorkflowStateSync=!0,{experienceOptions:R,index:x,options:k}}),f=await Promise.all(p);M.setMap("transactionOwnerIds",m);const y=f.sort((S,E)=>S.index-E.index).map(async S=>{const{experienceOptions:E,options:B}=S,I=new Dr(this,E);return await I.getWorkflowManager().getInitializationPromise(),B.type!=="transaction"&&this.customer&&await I.attachCustomerDetails({email:this.customer.emailAddress}),I}),v=await Promise.all(y);return v.forEach(S=>S.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),v}storeCustomer(t){const e=M.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),M.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){var s,o;const i=(s=(await b.getShadowGraphqlClient().query({query:is(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProducts;if(!i||i.length===0||!((o=i[0])!=null&&o.id))throw new Error("Integration product not found.");return new pa(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await b.getShadowGraphqlClient().query({query:ss(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:o.integrationProductFromExternalIds;if(!(s!=null&&s.id))throw new Error("Integration product not found.");return new pa(s)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(M.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await b.getShadowGraphqlClient().query({query:rs,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 b.getShadowGraphqlClient().mutate({mutation:ys,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 Ur=async(r,t)=>(await b.getShadowGraphqlClient().query({query:fs,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,uc=async r=>{const e=await b.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},hc=async(r,t)=>{var a;return(a=(await b.getShadowGraphqlClient().query({query:ps,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},gc=async r=>{var e,a,n;return(n=(a=(e=(await b.getShadowGraphqlClient().query({query:ws,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},mc=async r=>{var e,a,n;return(n=(a=(e=(await b.getShadowGraphqlClient().query({query:Cs,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function Lr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const o=r,l=Math.max(t.width/e.width,t.height/e.height);o.zoom=Math.max(l,r.zoom);const c=e.width*o.zoom,d=e.height*o.zoom;return o.x=fe(r.x,t.width-c,0),o.y=fe(r.y,t.height-d,0),o}const s=r;return s.x=fe(s.x,-n,t.width),s.y=fe(s.y,-i,t.height),s}function fe(r,t,e){return Math.min(Math.max(r,t),e)}class Vr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=yn(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 i=!1;for(let s=0;s<n.currentFrameSources.length;s++){const o=n.currentFrameSources[s],l=await ce(o),c=this.frameData?this.frameData[s]:void 0;wn(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[s]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Ft.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=Qe(this.imageData.svg,this.imageData.colors||{},!1);return Me(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 i=this.frameData.map((s,o)=>{const l=(e[o]-this.offsets[o].x)/this.offsets[o].zoom,c=(a[o]-this.offsets[o].y)/this.offsets[o].zoom,d=e[o]-l*t[o],A=a[o]-c*t[o];return{x:d,y:A,zoom:this.imageData.width*t[o]/this.imageData.width}});this.updateOffsets(i,n),this.onZoomChangeListeners.forEach(s=>s(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new V("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(t[o].x===s.x&&t[o].y===s.y&&t[o].zoom===s.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=Lr(t[o],s,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,i){if(!a||a.length===0||a.some(o=>!o))throw new V("Frame data not set. This is a bug");if(!this.workflowManager)throw new V("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,l)=>{s(new $([new ro(o,e,t[l]),new io(o,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Da(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class pc{updateRecipient(t,e,a,n,i,s,o,l,c,d){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(){}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 zr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(zr||{});class Gr extends nt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Vr(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ut.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 n;if(await ut.selectImage(this.step,t,this.manager,a),e){const i=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.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(Pe.BackgroundRemover)}async canRemoveBackground(){var t,e,a,n;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((n=(a=this.frameService)==null?void 0:a.getImageData())!=null&&n.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 U.removeBackgroundFromAsset(e);t&&await ut.selectImage(this.step,a,this.manager,!1);const n=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ut.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?ut.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await st(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ut.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(){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 U.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 U.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 n;const e=((n=this.getFrameStepStorage())==null?void 0:n.framePatternData)||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const fc=w.gql`
|
|
2402
|
+
`;class ic{constructor(t,e=b.getShadowGraphqlClient.bind(b)){this.options=t,this.client=e}query(t){var a,n;const e=(a=this.options)!=null&&a.onQuery?(n=this.options)==null?void 0:n.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){var a,n;const e=(a=this.options)!=null&&a.onMutate?(n=this.options)==null?void 0:n.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}const sc=async(r,t)=>{var n;const e=await b.getShadowGraphqlClient().query({query:hs(((n=t==null?void 0:t.assets)==null?void 0:n.metadata)||!1),errorPolicy:"all",variables:{ids:r}});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!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.steps.forEach(s=>{var o,l,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((l=s.option.defaultVariant)!=null&&l.asset&&U.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&U.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(d=>{d.asset&&U.cacheAsset(d.asset),d.thumbnail&&U.cacheAsset(d.thumbnail),d.material&&U.cacheMaterial(d.material)}),$t.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},oc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},Ga=async(r,t)=>{const e=r.map(o=>$t.get({id:o,options:t})),a=r.filter((o,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=sc(a,t),i=a.map(o=>$t.set({id:o,options:t},oc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},lc=async(r,t)=>(await Ga([r],t))[0],cc=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:N(),panelId:t.name,name:t.name,title:t.title,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})),dc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):cc(t.panels)};class Ac{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return b.getShadowGraphqlClient().mutate({...e,mutation:es})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ci(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 26.38.0-beta.d98620d3-59a9-5edf-b33f-1e6356cd6536"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,t.bearerAuthenticationToken&&Qn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return U}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!wi())throw new Error("Application key required to use Flow Service.");return new Rr}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=Ur(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(a){return console.error(a),!1}}async authenticateBundleFromLocalStorage(t){var n,i;const e=M.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:_t.Owner});const a=M.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const s=a.get(t),l=(M.getMap("partnerCustomerIds")||new Map).get(s);if(l&&await this.authenticateCustomerId(l)){const d=(i=(n=this.customer)==null?void 0:n.bundleStakeholders)==null?void 0:i.find(A=>{var u;return((u=A.bundle)==null?void 0:u.id)===t});if(d)return Promise.resolve({success:!0,stakeholderType:d.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var d,A,u,h,g,m;const e=b.getShadowGraphqlClient(),a=await e.query({query:gs,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 n=a.data.transactions[0];if(!((A=(d=n.product)==null?void 0:d.partner)==null?void 0:A.id))throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=M.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:_t.Owner});const o=M.getMap("transactionCustomerIds");if(o!=null&&o.has(t)){const p=o.get(t);if(p&&await this.authenticateCustomerId(p)){const C=((h=(u=this.customer)==null?void 0:u.bundleStakeholders)==null?void 0:h.find(y=>{var v,S;return(S=(v=y.bundle)==null?void 0:v.transactions)==null?void 0:S.some(E=>E.id===t)}))||((m=(g=this.customer)==null?void 0:g.stakeholders)==null?void 0:m.find(y=>{var v;return((v=y.transaction)==null?void 0:v.id)===t}));if(C)return Promise.resolve({success:!0,stakeholderType:C.type})}}const c=(await e.query({query:ms,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=M.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),M.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await b.getShadowGraphqlClient().query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var a,n;const e=(n=(a=this.customer)==null?void 0:a.stakeholders)==null?void 0:n.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=b.getShadowGraphqlClient(),n=(await e.query({query:cn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:tc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!l)throw new Error("Unable to create customer.");return this.storeCustomer(l),this.customer=l,{customer:l,isAuthenticated:!1}}this.storeCustomer(n);const i=await this.authenticateCustomerId(n.id);return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async authenticateCustomerId(t){var o;const e=b.getShadowGraphqlClient(),a=M.getMap("customerTokens");if(!(a!=null&&a.has(t)))return!1;const n=a.get(t);if(!n)return!1;const s=(o=(await e.mutate({mutation:ec,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:n}})).data)==null?void 0:o.customerAuthenticate;return s?(this.storeCustomer(s),_a(n),this.customer=s,!0):!1}async generateVerificationCode(t){await b.getShadowGraphqlClient().mutate({mutation:ac,variables:{emailAddress:t}})}async verifyCode(t,e){var i,s;const n=(i=(await b.getShadowGraphqlClient().mutate({mutation:nc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data)==null?void 0:i.customerVerifyCode;if(n!=null&&n.loginToken){if(!((s=n.partner)!=null&&s.id))throw new Error(`Unable to find customer: ${t}`);const o=M.getMap("customerTokens")||new Map;return o.set(n.id,n.loginToken),M.setMap("customerTokens",o),this.storeCustomer(n),_a(n.loginToken),this.customer={...n,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 b.getShadowGraphqlClient().query({query:rc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){var c,d,A,u,h;const i=(A=(await b.getShadowGraphqlClient().mutate({mutation:Vo(((d=(c=a==null?void 0:a.graphql)==null?void 0:c.productCollection)==null?void 0:d.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((g,m)=>({key:g[0],value:g[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:A.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=M.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),M.setMap("bundlePartnerIds",s);const o=M.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),M.setMap("bundleOwnerIds",o);const l=new Ke(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(h=(u=a==null?void 0:a.graphql)==null?void 0:u.productCollection)==null?void 0:h.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){var p,f,C,y,v,S,E,B,I,x,F;const i=M.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),l=((p=Object.entries(localStorage).find(([k,Q])=>k.startsWith("CognitoIdentityServiceProvider")&&k.endsWith("idToken")))==null?void 0:p[0])||"",c=localStorage.getItem(l),d={};c&&!Ie(c)&&(d.Authorization=`Bearer ${c}`);const A={bundleOwnerId:s,...d,...(f=n==null?void 0:n.graphql)==null?void 0:f.additionalHeaders},u=await b.getShadowGraphqlClient().query({query:Ro(((y=(C=n==null?void 0:n.graphql)==null?void 0:C.productCollection)==null?void 0:y.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:A}});if(!((v=u.data)!=null&&v.bundles)||((S=u.data)==null?void 0:S.bundles.length)===0||!((E=u.data)!=null&&E.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const h=(B=u.data)==null?void 0:B.bundles[0],g=M.getMap("bundlePartnerIds")||new Map;g.set(h.id,h.partner.id),M.setMap("bundlePartnerIds",g);const m=new Ke(this,h,e,a,s,{additionalHeaders:(I=n==null?void 0:n.graphql)==null?void 0:I.additionalHeaders,eagerFetchProducts:(F=(x=n==null?void 0:n.graphql)==null?void 0:x.productCollection)==null?void 0:F.eagerFetchProducts,existingGlobalPropertyState:u.data.globalPropertyState,readonly:n==null?void 0:n.readonly});return await m.getInitializationPromise(),m}async duplicateBundle(t,e,a,n){var p,f,C,y,v,S,E,B;const i=(p=M.getMap("bundleOwnerIds"))==null?void 0:p.get(t),o=((f=Object.entries(localStorage).find(([I,x])=>I.startsWith("CognitoIdentityServiceProvider")&&I.endsWith("idToken")))==null?void 0:f[0])||"",l=localStorage.getItem(o),c={};l&&!Ie(l)&&(c.Authorization=`Bearer ${l}`);const d={bundleOwnerId:i,...c,...(C=n==null?void 0:n.graphql)==null?void 0:C.additionalHeaders},u=(S=(await b.getShadowGraphqlClient().mutate({mutation:zo(((v=(y=n==null?void 0:n.graphql)==null?void 0:y.productCollection)==null?void 0:v.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:d},fetchPolicy:"no-cache"})).data)==null?void 0:S.bundleDuplicate;if(!(u!=null&&u.id))throw new Error("Unable to duplicate bundle");const h=M.getMap("bundlePartnerIds")||new Map;h.set(u.id,u.partner.id),M.setMap("bundlePartnerIds",h);const g=M.getMap("bundleOwnerIds")||new Map;g.set(u.id,u.bundleOwnerId),M.setMap("bundleOwnerIds",g);const m=new Ke(this,u,void 0,void 0,u.bundleOwnerId,{eagerFetchProducts:(B=(E=n==null?void 0:n.graphql)==null?void 0:E.productCollection)==null?void 0:B.eagerFetchProducts,existingGlobalPropertyState:u.globalPropertyState});return await m.getInitializationPromise(),m}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 b.getShadowGraphqlClient().query({query:tl(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 b.getShadowGraphqlClient().query({query:Oo,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||[],n=M.getMap("bundlePartnerIds")||new Map;return a.forEach(s=>{var o,l;(o=s.bundle)!=null&&o.id&&((l=s.bundle.partner)!=null&&l.id)&&n.set(s.bundle.id,s.bundle.partner.id)}),M.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];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new ht("No options provided!");const a=b.getShadowGraphqlClient(),n=async S=>{var x,F,k;if(S.length===0)return[];const E=S.map(Q=>Q.option.transactionId),B=await a.query({query:ts,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),I=B.data.transactions;if(I.length!==S.length){const Q=((F=(x=B.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Not all transactions were found: ${Q}`)}return!this.activeIntegration&&((k=I[0].integrationProduct)!=null&&k.integration)&&(this.activeIntegration=Promise.resolve(I[0].integrationProduct.integration)),I.map((Q,ot)=>{var R;return{transaction:Q,workflowId:Q.workflowId,readOnly:((R=S.find(et=>et.option.transactionId===Q.id))==null?void 0:R.option.readOnly)??!1,index:S[ot].index}})},i=async S=>{var I,x,F;if(S.length===0)return[];const E=await a.mutate({mutation:Zi,variables:{inputs:S.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})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),B=(I=E.data)==null?void 0:I.transactionCreateMany;if(!B||B.length===0){const k=((F=(x=E.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Failed to create transactions: ${k}`)}return B.map((k,Q)=>({transaction:k,workflowId:k.workflowId,readOnly:!1,index:S[Q].index}))},s=t.map((S,E)=>({option:S,index:E})),o=s.filter(S=>S.option.type==="transaction"),l=s.filter(S=>S.option.type==="integration"||S.option.type==="external"),c=ja(o,10),d=ja(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(S=>S.workflowId))],h=await Ga(u,e),g=new Map(h.map(S=>[S.id,S])),m=M.getMap("transactionOwnerIds")||new Map,p=A.map(async S=>{var et;const{transaction:E,workflowId:B,readOnly:I,index:x}=S,F=g.get(B),k=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const Q=m.get(E.id)||void 0,ot=new ic({onMutate:()=>({context:{transactionOwnerId:Q,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:Q,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})}),R={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:(et=k==null?void 0:k.workflowConfiguration)==null?void 0:et.singleVariantsRenderable,stateMutationFunc:I?async()=>{throw new V("State mutation is forbidden in read only mode!")}:async H=>this.updateTransactionState({...H,context:{transactionOwnerId:Q,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),graphQlClient:()=>ot,readOnly:I,workflow:F,isReloadedTransaction:k.type==="transaction"};if(k.type==="transaction"&&E.workflowState){const H=JSON.parse(E.workflowState);R.layouts=Object.values(H.layouts||{}).map(yt=>yt.layout),await da(H),R.reloadedState=H}else if(!I&&k.workflowState){const H=JSON.parse(k.workflowState);R.layouts=Object.values(H.layouts||{}).map(yt=>yt.layout),await da(H),R.reloadedState=H}else R.layouts=dc(R.transaction,R.workflow);return R.renderableContextService=new kl(R.layouts),R.delayWorkflowStateSync=!0,{experienceOptions:R,index:x,options:k}}),f=await Promise.all(p);M.setMap("transactionOwnerIds",m);const y=f.sort((S,E)=>S.index-E.index).map(async S=>{const{experienceOptions:E,options:B}=S,I=new Dr(this,E);return await I.getWorkflowManager().getInitializationPromise(),B.type!=="transaction"&&this.customer&&await I.attachCustomerDetails({email:this.customer.emailAddress}),I}),v=await Promise.all(y);return v.forEach(S=>S.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),v}storeCustomer(t){const e=M.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),M.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){var s,o;const i=(s=(await b.getShadowGraphqlClient().query({query:is(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProducts;if(!i||i.length===0||!((o=i[0])!=null&&o.id))throw new Error("Integration product not found.");return new pa(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await b.getShadowGraphqlClient().query({query:ss(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:o.integrationProductFromExternalIds;if(!(s!=null&&s.id))throw new Error("Integration product not found.");return new pa(s)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(M.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await b.getShadowGraphqlClient().query({query:rs,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 b.getShadowGraphqlClient().mutate({mutation:ys,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 Ur=async(r,t)=>(await b.getShadowGraphqlClient().query({query:fs,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,uc=async r=>{const e=await b.getShadowGraphqlClient().query({query:ns,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},hc=async(r,t)=>{var a;return(a=(await b.getShadowGraphqlClient().query({query:ps,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},gc=async r=>{var e,a,n;return(n=(a=(e=(await b.getShadowGraphqlClient().query({query:ws,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},mc=async r=>{var e,a,n;return(n=(a=(e=(await b.getShadowGraphqlClient().query({query:Cs,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function Lr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const o=r,l=Math.max(t.width/e.width,t.height/e.height);o.zoom=Math.max(l,r.zoom);const c=e.width*o.zoom,d=e.height*o.zoom;return o.x=fe(r.x,t.width-c,0),o.y=fe(r.y,t.height-d,0),o}const s=r;return s.x=fe(s.x,-n,t.width),s.y=fe(s.y,-i,t.height),s}function fe(r,t,e){return Math.min(Math.max(r,t),e)}class Vr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=yn(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 i=!1;for(let s=0;s<n.currentFrameSources.length;s++){const o=n.currentFrameSources[s],l=await ce(o),c=this.frameData?this.frameData[s]:void 0;wn(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[s]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Ft.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=Qe(this.imageData.svg,this.imageData.colors||{},!1);return Me(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 i=this.frameData.map((s,o)=>{const l=(e[o]-this.offsets[o].x)/this.offsets[o].zoom,c=(a[o]-this.offsets[o].y)/this.offsets[o].zoom,d=e[o]-l*t[o],A=a[o]-c*t[o];return{x:d,y:A,zoom:this.imageData.width*t[o]/this.imageData.width}});this.updateOffsets(i,n),this.onZoomChangeListeners.forEach(s=>s(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new V("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(t[o].x===s.x&&t[o].y===s.y&&t[o].zoom===s.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=Lr(t[o],s,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,i){if(!a||a.length===0||a.some(o=>!o))throw new V("Frame data not set. This is a bug");if(!this.workflowManager)throw new V("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,l)=>{s(new $([new ro(o,e,t[l]),new io(o,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=Da(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class pc{updateRecipient(t,e,a,n,i,s,o,l,c,d){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(){}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 zr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(zr||{});class Gr extends nt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Vr(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ut.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 n;if(await ut.selectImage(this.step,t,this.manager,a),e){const i=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.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(Pe.BackgroundRemover)}async canRemoveBackground(){var t,e,a,n;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((n=(a=this.frameService)==null?void 0:a.getImageData())!=null&&n.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 U.removeBackgroundFromAsset(e);t&&await ut.selectImage(this.step,a,this.manager,!1);const n=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ut.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?ut.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await st(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ut.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(){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 U.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 U.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 n;const e=((n=this.getFrameStepStorage())==null?void 0:n.framePatternData)||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const fc=w.gql`
|
|
2403
2403
|
query GetLoggedInCustomer($email: String!) {
|
|
2404
2404
|
customer(emailAddress: $email) {
|
|
2405
2405
|
id
|