@spiffcommerce/core 29.0.1 → 29.0.3
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/CHANGELOG.md +13 -0
- package/dist/index.d.ts +12 -0
- package/dist/index.js +7 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +22 -2
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -14,6 +14,19 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
14
14
|
- `Fixed` for any bug fixes.
|
|
15
15
|
- `Security` in case of vulnerabilities.
|
|
16
16
|
|
|
17
|
+
## [29.0.3] - 14-08-2025
|
|
18
|
+
|
|
19
|
+
## Added
|
|
20
|
+
|
|
21
|
+
- `getDispatchStartDate` method to `ProductCollection`.
|
|
22
|
+
- `getDispatchEndDate` method to `ProductCollection`.
|
|
23
|
+
|
|
24
|
+
## [29.0.2] - 08-08-2025
|
|
25
|
+
|
|
26
|
+
## Fixed
|
|
27
|
+
|
|
28
|
+
- `getExportedStepData` now returns only steps with properties as per original behavior.
|
|
29
|
+
|
|
17
30
|
## [29.0.1] - 07-08-2025
|
|
18
31
|
|
|
19
32
|
## Fixed
|
package/dist/index.d.ts
CHANGED
|
@@ -1591,6 +1591,16 @@ declare class ProductCollection {
|
|
|
1591
1591
|
* The description of the collection.
|
|
1592
1592
|
*/
|
|
1593
1593
|
getDescription(): string;
|
|
1594
|
+
/**
|
|
1595
|
+
* The start date of the dispatch.
|
|
1596
|
+
* @returns The start date of the dispatch or undefined if not set.
|
|
1597
|
+
*/
|
|
1598
|
+
getDispatchStartDate(): Date | undefined;
|
|
1599
|
+
/**
|
|
1600
|
+
* The end date of the dispatch.
|
|
1601
|
+
* @returns The end date of the dispatch or undefined if not set.
|
|
1602
|
+
*/
|
|
1603
|
+
getDispatchEndDate(): Date | undefined;
|
|
1594
1604
|
/**
|
|
1595
1605
|
* The image of the collection.
|
|
1596
1606
|
*/
|
|
@@ -4179,6 +4189,8 @@ type ProductCollectionResource = {
|
|
|
4179
4189
|
productCollectionProductsFeed?: ProductCollectionProductsFeedResource;
|
|
4180
4190
|
name: string;
|
|
4181
4191
|
description?: string;
|
|
4192
|
+
dispatchStartDate?: string;
|
|
4193
|
+
dispatchEndDate?: string;
|
|
4182
4194
|
image?: Asset;
|
|
4183
4195
|
transformCollection?: TransformCollection;
|
|
4184
4196
|
};
|
package/dist/index.js
CHANGED
|
@@ -1575,6 +1575,8 @@
|
|
|
1575
1575
|
id
|
|
1576
1576
|
name
|
|
1577
1577
|
description
|
|
1578
|
+
dispatchStartDate
|
|
1579
|
+
dispatchEndDate
|
|
1578
1580
|
image {
|
|
1579
1581
|
key
|
|
1580
1582
|
name
|
|
@@ -2027,6 +2029,8 @@
|
|
|
2027
2029
|
id
|
|
2028
2030
|
name
|
|
2029
2031
|
description
|
|
2032
|
+
dispatchStartDate
|
|
2033
|
+
dispatchEndDate
|
|
2030
2034
|
image {
|
|
2031
2035
|
key
|
|
2032
2036
|
name
|
|
@@ -2238,7 +2242,7 @@
|
|
|
2238
2242
|
id
|
|
2239
2243
|
}
|
|
2240
2244
|
}
|
|
2241
|
-
`;var xr=(r=>(r.QuantityChanged="QuantityChanged",r.PriceBreakChanged="PriceBreakChanged",r))(xr||{});class Fr{constructor(t,e){var n;if(this.cachedStepHandles=new Map,this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=vn(async()=>{await Ee.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async i=>new Promise((s,o)=>{try{i.toBlob(l=>{if(l){const c=URL.createObjectURL(l);s(c)}})}catch(l){o(l)}}),!e.workflow)throw new Error("No Workflow ID provided.");this.client=t;const a=e.layouts;this.commandContext=new er,this.commandContext.initialize(a,e.reloadedState),this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Sl(this,t,e.workflow,((n=e.product.profanities)==null?void 0:n.map(i=>i.word))||[],a,this.commandContext,i=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(i)},e.graphQlClient,e.transaction,e.product,e.previewService,e.renderableContextService,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(i=>{const s=i.traversableScenes.map(o=>{const l=o.renderableSteps.map(c=>c.stepName);return{id:o.name,title:o.title,renderableSteps:l,workflowScene:o}});this.renderableScenes=s,this.renderableSceneCallbacks.forEach(o=>o(s))}),this.currentPriceBreak=this.priceBreakToBeApplied()}async attachAddress(t,e,a,n,i,s){await this.graphQlClient().mutate({mutation:Fl,variables:{transactionId:this.getWorkflowManager().getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:i||void 0,postCode:s||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:kl,variables:{transactionId:this.getWorkflowManager().getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){var C,w;const a=this.workflowManager.getWorkflow(),n=(C=a==null?void 0:a.finalizeStepConfig)==null?void 0:C.lookAtAnimation;if(t){if(!n)throw new Error("Failed to generate cart preview image!");return await((w=this.workflowManager.getPreviewService())==null?void 0:w.renderSceneScreenshot(e??512,n))||""}let i=2048;e&&e<=2048&&(i=e);const s=pt(i,i),o=this.commandContext.getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=o.find(S=>{var y;return((y=S.layoutState)==null?void 0:y.layout.panelId)===(c==null?void 0:c.name)})||o[0],A=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},u=this.commandContext.getLayoutById(d.layoutState.layout.id),h=s.getContext("2d");if(!h)throw new Te("Failed to obtain 2D context for preview image creation");const g=Ve(u.layoutState.layout,u.layoutState.elements,{renderingConfiguration:{purpose:Tt.Print,region:{left:A.x,top:A.y,width:A.width,height:A.height},templatingContext:this.workflowManager.getTemplatingContext()}}),m=Mn(g);await(await ya.Pith.from(h,m,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:pt,createImage:se,DOMParser:Ea(),fetch})).render();const f=await this.getCanvasObjectURLAsync(s);return s.toDataURL(f)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find(i=>i.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const n=we.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,n),n}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>vt(e.getRaw(),this.getWorkflowManager().getStepSelections())))}getScenes(){return this.getWorkflowManager().getWorkflow().stepGroups.map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let a=0;return Object.values(e).forEach(n=>{a+=n.selections.reduce((i,s)=>i+(s.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getWorkflowManager().getProduct().basePrice||0,e);if(t){const n=this.getAdditionalProductPriceSubunits(e)||0;return a+n}return a}getAdditionalProductPriceSubunits(t){var a;const e=this.getWorkflowManager().getTransaction().integrationProduct;if((a=e==null?void 0:e.additionalIntegrationProduct)!=null&&a.product){const n=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(n,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),n=t*a;return Math.ceil(n)}priceBreakToBeApplied(){const t=(this.getWorkflowManager().getProduct().priceBreaks||[]).sort((n,i)=>-(n.minQty-i.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((n,i)=>n+i.getQuantity(),0);for(const n of t)if(n.minQty<=a)return n.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){var t;return(((t=this.bundle)==null?void 0:t.getWorkflowExperiences())||[]).filter(e=>e.getWorkflowManager().getTransaction().id!==this.getWorkflowManager().getTransaction().id&&e.getWorkflowManager().getProduct().id===this.getWorkflowManager().getProduct().id)}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const n=await t.getGlobalProperties(),i=a==null?void 0:a.map(c=>c.getId()),s=this.getSteps().filter(c=>i===void 0||i.includes(c.getId())),o=e.getSteps(),l=c=>n.find(d=>d.getRawProperty().name===c.aspectName);s.forEach(c=>{const d=new Set,A=c.getRaw().globalPropertyAspectConfigurations;A!==void 0&&(A.forEach(u=>d.add(JSON.stringify(u))),o.forEach(u=>{const h=u.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const m=l(g),p=d.has(JSON.stringify(g));if(p&&(m==null?void 0:m.getType())==="Option"){const f=u.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(p&&(m==null?void 0:m.getType())==="Text"){const f=u.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return we.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter(e=>e.type===t).map(e=>we.get(this.getWorkflowManager(),e))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find(a=>a.name===t.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map(a=>this.getWorkflowManager().getWorkflow().steps.find(n=>n.stepName===a)).filter(a=>this.stepHasHandle(a)).map(a=>we.get(this.getWorkflowManager(),a))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){var n,i,s;const a=(s=(i=(n=(await this.graphQlClient().mutate({mutation:xl,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data)==null?void 0:n.transactionAddStakeholder)==null?void 0:i.stakeholders)==null?void 0:s.find(o=>{var l;return((l=o.customer)==null?void 0:l.emailAddress)===t.emailAddress});if(a!=null&&a.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const o=N.getMap("transactionCustomerIds")||new Map;o.set(this.getWorkflowManager().getTransaction().id,a.customer.id),N.setMap("transactionCustomerIds",o)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){if(!this.getCommandContext().getState())throw new z("State undefined!");const n={title:await(async()=>{var l;if(t)return t;const i=this.getWorkflowManager().getTransaction().id,o=(l=(await Ee.getSavedDesigns()).find(c=>c.transactionId===i))==null?void 0:l.title;return o||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await Ee.addDesign(n),n}async copy(){var s;const t=Et(this.getCommandContext().getState());if(!t)throw new z("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflowManager().getWorkflow(),n=(s=this.getWorkflowManager().getTransaction().integrationProduct)==null?void 0:s.id;if(!n)throw new z("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:n,workflowId:a.id,workflowState:e})}async onDesignFinished(t,e=!0){const a=this.workflowManager.getTransaction();return a.completed?(await this.graphQlClient().mutate({mutation:ps,variables:{transactionId:a.id}}),{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:a.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""}):Dr(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),()=>this.commandContext.getState(),this.workflowManager.getProduct(),a,this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),n=>e?this.createPreviewImage(n,1024):Promise.resolve(void 0),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==I.SilentIllustration&&t.type!==I.ProductOverlay}getExportedStepData(){const t=this.getWorkflowManager().getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),n=[];return t.steps.forEach(i=>{var d;const s=i.stepName,o=e[s],l=(d=a[s])==null?void 0:d.selections[0],c={stepId:s,title:i.stepTitle,properties:[]};if(l&&Tl(i,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!o){n.push(c);return}switch(i.type){case I.Frame:{const A=i.data,u=o;u.image&&A.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case I.Illustration:{const A=i.data,u=o;if(u&&u.colors&&u.colors.length>0&&A.displayColorsOnFinishStep){const h=u.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:h,priceModifier:0})}}break;case I.Module:{const A=i.data,u=o;u&&u.text&&A.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case I.Text:{const A=i.data,u=o;u&&u.text&&A.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0}),u&&u.color&&A.displayColorOnFinishStep&&c.properties.push({type:"color",value:u.color,priceModifier:0})}}n.push(c)}),n}getQuantity(){return this.getWorkflowManager().getTransaction().quantity||1}async setQuantity(t){if(t<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getWorkflowManager().getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getWorkflowManager().getTransaction();await this.graphQlClient().mutate({mutation:ds,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const a=this.eventCallbacks.get(t)||[];a.push(e),this.eventCallbacks.set(t,a)}removeEventListener(t,e){const a=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,a.filter(n=>n!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const Ml=r=>{if([I.Question,I.Frame,I.Illustration,I.Material,I.Model,I.Picture,I.Shape,I.Text].includes(r.type)){const e=r.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Tl=(r,t)=>{if(!Ml(r))return!1;if(r.option&&(r.option.variants||[]).length>1){const e=t[r.stepName];return!!(e&&e.selections.length>0)}return!1},Nl=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],Ql=async(r,t,e)=>{const a=t.data,n=e.data.baseUrl,i=a.assetUrl.replace("localhost","localstack"),s=n.slice(0,4)==="http"?"":"https://",o=new URL(s+n);o.searchParams.append("video",Za(JSON.stringify([{href:i}]))),o.pathname=o.pathname+(o.pathname.slice(-1)==="/"?"":"/");const l=o.toString(),d=`data:image/svg+xml;base64,${Za(await yn.toString(l,{type:"svg"}))}`,A=h=>{const g=r.find(p=>p.panelId===h.panelId);if(!g)throw new Y(h);const m=Q();return new q({id:m,src:d,type:k.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},g)},u=e.data.regions;try{return u.map(A)}catch(h){return console.error(h),[]}},Rl=async(r,t,e,a)=>{const n=e.data,i=n.assetUrl,s=await ua(i);try{const o=lo(n,a.option);o&&(t[a.stepName]={selectedVariants:[o]});const l=async c=>{var m;const d=await nr(c,(m=o==null?void 0:o.asset)==null?void 0:m.fileLink),A=await Ae(d),u=Q(),h=r.find(p=>p.panelId===c.panelId);if(!h)throw new Y(c);const g=Fa(s,A,{scale:n.scale,left:n.x,top:n.y},a.data.forceImageCover);return[new q({id:u,path:A.path,type:k.Frame,forceImageCover:a.data.forceImageCover,x:c.left,y:c.top,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,rotation:c.rotation,scaleX:c.width/A.width,scaleY:c.height/A.height,pattern:{id:`${u}-pattern`,src:s.src,x:g.x,y:g.y,width:s.width,height:s.height,rotation:0,scaleX:g.zoom,scaleY:g.zoom,svg:s.svg,colors:s.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(o){return console.error(o),[]}},Ol=async(r,t,e,a)=>{var y,E;const n=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const s=((y=i.variants)==null?void 0:y.find(b=>b.id===n.illustrationVariantId))||de(i);if(!s)return console.error(`No variant with ID: ${n.illustrationVariantId}`),[];if(!s.asset)return console.error(`No asset for variant with ID: ${n.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=(E=s.asset)==null?void 0:E.fileLink;if(!o)return console.error(`No asset link for variant with ID: ${n.illustrationVariantId}`),[];const l=await et(o,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],A=(d==null?void 0:d.length)>0?d[0]:"",g=ct().parseFromString(A,"image/svg+xml").firstElementChild;if(!g)return console.error("Failed to read SVG."),[];Oe(g);const m={};Rt(g,b=>{Nl.includes(b.tagName)&&!b.attributes.getNamedItem("fill")&&b.setAttribute("fill","#000000");const P=b.attributes.getNamedItem("fill");if(P&&P.value!=="none"){const F=P.value,T=`spiff-fill-${F.replace(/\W/g,"")}`;b.classList.add(T),m[T]={browserValue:F}}const x=b.attributes.getNamedItem("stroke");if(x&&x.value!=="none"){const F=x.value,T=`spiff-stroke-${F.replace(/\W/g,"")}`;b.classList.add(T),m[T]={browserValue:F}}});const f=wt().serializeToString(g),C=n.colors;if(C){for(const[b,P]of Object.entries(m))for(const x of Object.keys(C))if(P.browserValue===x){m[b]={browserValue:C[x]};break}}const w=b=>{const P=r.find(F=>F.panelId===b.panelId);if(!P)throw new Y(b);const x=Q();return new q({colors:m,id:x,svg:f,type:k.Illustration,y:b.top,x:b.left,rotation:b.rotation,width:b.width,height:b.height,layer:b.layer,layerIndex:b.layerIndex,immutable:b.immutable},P)},S=a.data.regions;try{return S.map(w)}catch(b){return console.error(b),[]}},$l=async(r,t,e)=>{const a=await hr(e.data.module),n=t.data,i=(o,l)=>{const c=r.find(A=>A.panelId===l.panelId);if(!c)throw new Y(l);const d=Q();return new q({colors:{},id:d,svg:o,type:k.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},s=e.data.regions;try{return s.map(o=>i(a.svgPrint(n.text,o),o))}catch(o){return console.error(o),[]}},Ul=async(r,t,e,a)=>{var d,A;const n=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const s=((d=i.variants)==null?void 0:d.find(u=>u.id===n.pictureVariantId))||de(i);if(!s)return console.error(`No variant with ID: ${n.pictureVariantId}`),[];if(!s.asset)return console.error(`No asset for variant with ID: ${n.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=(A=s.asset)==null?void 0:A.fileLink;if(!o)return console.error(`No asset link for variant with ID: ${n.pictureVariantId}`),[];const l=u=>{const h=r.find(m=>m.panelId===u.panelId);if(!h)throw new Y(u);const g=Q();return new q({id:g,src:o,type:k.Image,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable,preserveAspectRatio:"none"},h)},c=a.data.regions;try{return c.map(l)}catch(u){return console.error(u),[]}},Ll=async(r,t,e,a)=>{var c;const n=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const s=((c=i.variants)==null?void 0:c.find(d=>d.id===n.colorVariantId))||de(i);if(!s)return console.error(`No variant with ID: ${n.colorVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=d=>{const A=r.find(p=>p.panelId===d.panelId);if(!A)throw new Y(d);const u=`
|
|
2245
|
+
`;var xr=(r=>(r.QuantityChanged="QuantityChanged",r.PriceBreakChanged="PriceBreakChanged",r))(xr||{});class Fr{constructor(t,e){var n;if(this.cachedStepHandles=new Map,this.currentPriceBreak=1,this.renderableScenes=[],this.renderableSceneCallbacks=[],this.eventCallbacks=new Map,this.debouncedSavedDesignUpdate=vn(async()=>{await Ee.getSavedDesignByTransaction(this.getWorkflowManager().getTransaction().id)&&this.save()},2500),this.getCanvasObjectURLAsync=async i=>new Promise((s,o)=>{try{i.toBlob(l=>{if(l){const c=URL.createObjectURL(l);s(c)}})}catch(l){o(l)}}),!e.workflow)throw new Error("No Workflow ID provided.");this.client=t;const a=e.layouts;this.commandContext=new er,this.commandContext.initialize(a,e.reloadedState),this.isReadOnly=e.transaction.isOrdered||!!e.readOnly,this.graphQlClient=e.graphQlClient,this.workflowManager=new Sl(this,t,e.workflow,((n=e.product.profanities)==null?void 0:n.map(i=>i.word))||[],a,this.commandContext,i=>{try{this.debouncedSavedDesignUpdate()}catch{console.error("Failed to update saved design details.")}return e.stateMutationFunc(i)},e.graphQlClient,e.transaction,e.product,e.previewService,e.renderableContextService,e.reloadedState,e.readOnly,e.modelContainer,e.isReloadedTransaction,e.singleVariantsRenderable,e.delayWorkflowStateSync),this.workflowManager.addSelectionCallback(i=>{const s=i.traversableScenes.map(o=>{const l=o.renderableSteps.map(c=>c.stepName);return{id:o.name,title:o.title,renderableSteps:l,workflowScene:o}});this.renderableScenes=s,this.renderableSceneCallbacks.forEach(o=>o(s))}),this.currentPriceBreak=this.priceBreakToBeApplied()}async attachAddress(t,e,a,n,i,s){await this.graphQlClient().mutate({mutation:Fl,variables:{transactionId:this.getWorkflowManager().getTransaction().id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:i||void 0,postCode:s||void 0}})}async attachOrganization(t){await this.graphQlClient().mutate({mutation:kl,variables:{transactionId:this.getWorkflowManager().getTransaction().id,organizationName:t}})}getBundle(){return this.bundle}setBundle(t){this.bundle=t}getClient(){return this.client}getIsReadOnly(){return this.isReadOnly}getCommandContext(){return this.commandContext}getWorkflowManager(){return this.workflowManager}async createPreviewImage(t,e){var C,w;const a=this.workflowManager.getWorkflow(),n=(C=a==null?void 0:a.finalizeStepConfig)==null?void 0:C.lookAtAnimation;if(t){if(!n)throw new Error("Failed to generate cart preview image!");return await((w=this.workflowManager.getPreviewService())==null?void 0:w.renderSceneScreenshot(e??512,n))||""}let i=2048;e&&e<=2048&&(i=e);const s=pt(i,i),o=this.commandContext.getAllLayouts(),l=a.defaultPreviewPanelIndex||0,c=a.panels[l],d=o.find(S=>{var y;return((y=S.layoutState)==null?void 0:y.layout.panelId)===(c==null?void 0:c.name)})||o[0],A=d.layoutState.layout.previewRegion?{x:d.layoutState.layout.previewRegion.left,y:d.layoutState.layout.previewRegion.top,width:d.layoutState.layout.previewRegion.width,height:d.layoutState.layout.previewRegion.height}:{x:0,y:0,width:d.layoutState.layout.width,height:d.layoutState.layout.height},u=this.commandContext.getLayoutById(d.layoutState.layout.id),h=s.getContext("2d");if(!h)throw new Te("Failed to obtain 2D context for preview image creation");const g=Ve(u.layoutState.layout,u.layoutState.elements,{renderingConfiguration:{purpose:Tt.Print,region:{left:A.x,top:A.y,width:A.width,height:A.height},templatingContext:this.workflowManager.getTemplatingContext()}}),m=Mn(g);await(await ya.Pith.from(h,m,{anonymousCrossOrigin:!0,ignoreDimensions:!1,createCanvas:pt,createImage:se,DOMParser:Ea(),fetch})).render();const f=await this.getCanvasObjectURLAsync(s);return s.toDataURL(f)}getStepById(t){const e=this.getWorkflowManager().getWorkflow().steps.find(i=>i.stepName===t);if(!e||!this.stepHasHandle(e))return;const a=this.cachedStepHandles.get(e.stepName);if(a)return a;const n=we.get(this.getWorkflowManager(),e);return this.cachedStepHandles.set(e.stepName,n),n}getSteps(){return this.getScenes().flatMap(t=>this.getStepsByScene(t))}getStepsConditionallyActive(){return this.getScenes().flatMap(t=>this.getStepsByScene(t).filter(e=>vt(e.getRaw(),this.getWorkflowManager().getStepSelections())))}getScenes(){return this.getWorkflowManager().getWorkflow().stepGroups.map(e=>({id:e.id,name:e.name,stepIds:e.stepNames}))}getSelectionPriceSubunits(t){const e=this.getWorkflowManager().getWorkflowSelections();let a=0;return Object.values(e).forEach(n=>{a+=n.selections.reduce((i,s)=>i+(s.priceModifier||0),0)}),this.getPriceSubUnitsAfterPriceBreaks(a,t)}getBasePriceSubunits(t,e){const a=this.getPriceSubUnitsAfterPriceBreaks(this.getWorkflowManager().getProduct().basePrice||0,e);if(t){const n=this.getAdditionalProductPriceSubunits(e)||0;return a+n}return a}getAdditionalProductPriceSubunits(t){var a;const e=this.getWorkflowManager().getTransaction().integrationProduct;if((a=e==null?void 0:e.additionalIntegrationProduct)!=null&&a.product){const n=e.additionalIntegrationProduct.product.basePrice||0;return this.getPriceSubUnitsAfterPriceBreaks(n,t)}}getTotalPriceSubunits(t){return this.getBasePriceSubunits(!1,t)+this.getSelectionPriceSubunits(t)}getPriceSubUnitsAfterPriceBreaks(t,e){const a=e?1:this.priceBreakToBeApplied(),n=t*a;return Math.ceil(n)}priceBreakToBeApplied(){const t=(this.getWorkflowManager().getProduct().priceBreaks||[]).sort((n,i)=>-(n.minQty-i.minQty)),a=[...this.getMatchingExperiencesFromBundle(),this].reduce((n,i)=>n+i.getQuantity(),0);for(const n of t)if(n.minQty<=a)return n.percentage;return 1}checkForPriceBreakChanges(){const t=this.priceBreakToBeApplied();this.currentPriceBreak!==t&&(this.updatePriceBreak(t),this.getMatchingExperiencesFromBundle().forEach(e=>e.updatePriceBreak(t)))}getMatchingExperiencesFromBundle(){var t;return(((t=this.bundle)==null?void 0:t.getWorkflowExperiences())||[]).filter(e=>e.getWorkflowManager().getTransaction().id!==this.getWorkflowManager().getTransaction().id&&e.getWorkflowManager().getProduct().id===this.getWorkflowManager().getProduct().id)}updatePriceBreak(t){this.currentPriceBreak=t,this.callEvent("PriceBreakChanged")}async copySelectionsViaGlobalConfiguration(t,e,a){const n=await t.getGlobalProperties(),i=a==null?void 0:a.map(c=>c.getId()),s=this.getSteps().filter(c=>i===void 0||i.includes(c.getId())),o=e.getSteps(),l=c=>n.find(d=>d.getRawProperty().name===c.aspectName);s.forEach(c=>{const d=new Set,A=c.getRaw().globalPropertyAspectConfigurations;A!==void 0&&(A.forEach(u=>d.add(JSON.stringify(u))),o.forEach(u=>{const h=u.getRaw().globalPropertyAspectConfigurations;h!==void 0&&h.forEach(g=>{const m=l(g),p=d.has(JSON.stringify(g));if(p&&(m==null?void 0:m.getType())==="Option"){const f=u.getCurrentVariant();if(!f)return;c.selectVariant(f),d.delete(JSON.stringify(g))}else if(p&&(m==null?void 0:m.getType())==="Text"){const f=u.getText();c.setText(f),d.delete(JSON.stringify(g))}})}))})}getStepByName(t){const e=this.getWorkflowManager().getWorkflow().steps.find(a=>a.stepTitle===t);if(!(!e||!this.stepHasHandle(e)))return we.get(this.getWorkflowManager(),e)}getStepsByType(t){return this.getWorkflowManager().getWorkflow().steps.filter(e=>e.type===t).map(e=>we.get(this.getWorkflowManager(),e))}getStepsByScene(t){if(!this.getWorkflowManager().getWorkflow().stepGroups.find(a=>a.name===t.name))throw new Error("Given scene is not present on workflow! Be careful when persisting scenes that you only use them with the relevant workflow.");return t.stepIds.map(a=>this.getWorkflowManager().getWorkflow().steps.find(n=>n.stepName===a)).filter(a=>this.stepHasHandle(a)).map(a=>we.get(this.getWorkflowManager(),a))}async attachCustomerDetails(t){return this.assignCustomerDetails({emailAddress:t.email})}async assignCustomerDetails(t){var n,i,s;const a=(s=(i=(n=(await this.graphQlClient().mutate({mutation:xl,variables:{id:this.getWorkflowManager().getTransaction().id,details:t,type:"Owner"}})).data)==null?void 0:n.transactionAddStakeholder)==null?void 0:i.stakeholders)==null?void 0:s.find(o=>{var l;return((l=o.customer)==null?void 0:l.emailAddress)===t.emailAddress});if(a!=null&&a.customer){this.getWorkflowManager().setTransactionCustomer(a.customer);const o=N.getMap("transactionCustomerIds")||new Map;o.set(this.getWorkflowManager().getTransaction().id,a.customer.id),N.setMap("transactionCustomerIds",o)}}attachRenderableSceneListener(t){this.renderableSceneCallbacks.push(t),t(this.renderableScenes)}detachRenderableSceneListener(t){this.renderableSceneCallbacks=this.renderableSceneCallbacks.filter(e=>e!==t)}async save(t){if(!this.getCommandContext().getState())throw new z("State undefined!");const n={title:await(async()=>{var l;if(t)return t;const i=this.getWorkflowManager().getTransaction().id,o=(l=(await Ee.getSavedDesigns()).find(c=>c.transactionId===i))==null?void 0:l.title;return o||"My design"})(),thumbnail:await this.createPreviewImage(!1,256),transactionId:this.getWorkflowManager().getTransaction().id,productId:this.getWorkflowManager().getProduct().id,integrationProductId:this.getWorkflowManager().getTransaction().integrationProduct.id,workflowName:this.getWorkflowManager().getWorkflow().name,workflowId:this.getWorkflowManager().getWorkflow().id,lastEdited:new Date};return await Ee.addDesign(n),n}async copy(){var s;const t=Et(this.getCommandContext().getState());if(!t)throw new z("Internal state is undefined! Cannot copy experience!");const e=JSON.stringify(t.transaction),a=this.getWorkflowManager().getWorkflow(),n=(s=this.getWorkflowManager().getTransaction().integrationProduct)==null?void 0:s.id;if(!n)throw new z("Integration product id is undefined!");return await this.getClient().getWorkflowExperience({type:"integration",integrationProductId:n,workflowId:a.id,workflowState:e})}async onDesignFinished(t,e=!0){const a=this.workflowManager.getTransaction();return a.completed?(await this.graphQlClient().mutate({mutation:ps,variables:{transactionId:a.id}}),{event:"",exportedData:{},lineItemImageUrl:"",optionsCost:0,transactionId:a.id,workflowViewerLink:"",workflowViewerReadOnlyLink:""}):Dr(this.workflowManager,this.workflowManager.getWorkflow(),this.workflowManager.getLayouts(),()=>this.commandContext.getState(),this.workflowManager.getProduct(),a,this.workflowManager.getWorkflowSelections(),this.workflowManager.getWorkflow().name,t||(()=>{}),n=>e?this.createPreviewImage(n,1024):Promise.resolve(void 0),this.workflowManager.getWorkflowMetadata())}stepHasHandle(t){return t.type!==I.SilentIllustration&&t.type!==I.ProductOverlay}getExportedStepData(){const t=this.getWorkflowManager().getWorkflow(),e=this.getWorkflowManager().getWorkflowMetadata(),a=this.getWorkflowManager().getWorkflowSelections(),n=[];return t.steps.forEach(i=>{var d;const s=i.stepName,o=e[s],l=(d=a[s])==null?void 0:d.selections[0],c={stepId:s,title:i.stepTitle,properties:[]};if(l&&Tl(i,a)&&c.properties.push({type:"selection",value:l.name,priceModifier:l.priceModifier}),!o){n.push(c);return}switch(i.type){case I.Frame:{const A=i.data,u=o;u.image&&A.displayImageOnFinishStep&&c.properties.push({type:"image",value:u.image,priceModifier:0})}break;case I.Illustration:{const A=i.data,u=o;if(u&&u.colors&&u.colors.length>0&&A.displayColorsOnFinishStep){const h=u.colors.join(", ").toUpperCase();c.properties.push({type:"color",value:h,priceModifier:0})}}break;case I.Module:{const A=i.data,u=o;u&&u.text&&A.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0})}break;case I.Text:{const A=i.data,u=o;u&&u.text&&A.displayTextOnFinishStep&&c.properties.push({type:"text",value:u.text,priceModifier:0}),u&&u.color&&A.displayColorOnFinishStep&&c.properties.push({type:"color",value:u.color,priceModifier:0})}}n.push(c)}),n.filter(i=>i.properties&&i.properties.length>0)}getQuantity(){return this.getWorkflowManager().getTransaction().quantity||1}async setQuantity(t){if(t<1)throw new RangeError("WorkflowExperience quantity must be greater than zero.");if(this.isReadOnly)throw new Error("Cannot update quantity on a read-only WorkflowExperience");this.getWorkflowManager().getTransaction().quantity=t,this.callEvent("QuantityChanged"),this.checkForPriceBreakChanges();const e=this.getWorkflowManager().getTransaction();await this.graphQlClient().mutate({mutation:ds,variables:{id:e.id,quantity:t}})}addEventListener(t,e){const a=this.eventCallbacks.get(t)||[];a.push(e),this.eventCallbacks.set(t,a)}removeEventListener(t,e){const a=this.eventCallbacks.get(t)||[];this.eventCallbacks.set(t,a.filter(n=>n!==e))}callEvent(t){(this.eventCallbacks.get(t)||[]).forEach(e=>e(this))}}const Ml=r=>{if([I.Question,I.Frame,I.Illustration,I.Material,I.Model,I.Picture,I.Shape,I.Text].includes(r.type)){const e=r.data;return!!e.displaySelectionOnFinishStep||!!e.displaySelectionsOnFinishStep}return!1},Tl=(r,t)=>{if(!Ml(r))return!1;if(r.option&&(r.option.variants||[]).length>1){const e=t[r.stepName];return!!(e&&e.selections.length>0)}return!1},Nl=["altGlyph","circle","ellipse","path","polygon","polyline","rect","text","textPath","tref","tspan"],Ql=async(r,t,e)=>{const a=t.data,n=e.data.baseUrl,i=a.assetUrl.replace("localhost","localstack"),s=n.slice(0,4)==="http"?"":"https://",o=new URL(s+n);o.searchParams.append("video",Za(JSON.stringify([{href:i}]))),o.pathname=o.pathname+(o.pathname.slice(-1)==="/"?"":"/");const l=o.toString(),d=`data:image/svg+xml;base64,${Za(await yn.toString(l,{type:"svg"}))}`,A=h=>{const g=r.find(p=>p.panelId===h.panelId);if(!g)throw new Y(h);const m=Q();return new q({id:m,src:d,type:k.Image,y:h.top,x:h.left,width:h.width,height:h.height,rotation:0},g)},u=e.data.regions;try{return u.map(A)}catch(h){return console.error(h),[]}},Rl=async(r,t,e,a)=>{const n=e.data,i=n.assetUrl,s=await ua(i);try{const o=lo(n,a.option);o&&(t[a.stepName]={selectedVariants:[o]});const l=async c=>{var m;const d=await nr(c,(m=o==null?void 0:o.asset)==null?void 0:m.fileLink),A=await Ae(d),u=Q(),h=r.find(p=>p.panelId===c.panelId);if(!h)throw new Y(c);const g=Fa(s,A,{scale:n.scale,left:n.x,top:n.y},a.data.forceImageCover);return[new q({id:u,path:A.path,type:k.Frame,forceImageCover:a.data.forceImageCover,x:c.left,y:c.top,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,rotation:c.rotation,scaleX:c.width/A.width,scaleY:c.height/A.height,pattern:{id:`${u}-pattern`,src:s.src,x:g.x,y:g.y,width:s.width,height:s.height,rotation:0,scaleX:g.zoom,scaleY:g.zoom,svg:s.svg,colors:s.colors}},h)]};return(await Promise.all(a.data.regions.map(c=>l(c)))).flat()}catch(o){return console.error(o),[]}},Ol=async(r,t,e,a)=>{var y,E;const n=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const s=((y=i.variants)==null?void 0:y.find(b=>b.id===n.illustrationVariantId))||de(i);if(!s)return console.error(`No variant with ID: ${n.illustrationVariantId}`),[];if(!s.asset)return console.error(`No asset for variant with ID: ${n.illustrationVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=(E=s.asset)==null?void 0:E.fileLink;if(!o)return console.error(`No asset link for variant with ID: ${n.illustrationVariantId}`),[];const l=await et(o,!0),c=/<svg.*?<\/svg>/s,d=l.match(c)||[],A=(d==null?void 0:d.length)>0?d[0]:"",g=ct().parseFromString(A,"image/svg+xml").firstElementChild;if(!g)return console.error("Failed to read SVG."),[];Oe(g);const m={};Rt(g,b=>{Nl.includes(b.tagName)&&!b.attributes.getNamedItem("fill")&&b.setAttribute("fill","#000000");const P=b.attributes.getNamedItem("fill");if(P&&P.value!=="none"){const F=P.value,T=`spiff-fill-${F.replace(/\W/g,"")}`;b.classList.add(T),m[T]={browserValue:F}}const x=b.attributes.getNamedItem("stroke");if(x&&x.value!=="none"){const F=x.value,T=`spiff-stroke-${F.replace(/\W/g,"")}`;b.classList.add(T),m[T]={browserValue:F}}});const f=wt().serializeToString(g),C=n.colors;if(C){for(const[b,P]of Object.entries(m))for(const x of Object.keys(C))if(P.browserValue===x){m[b]={browserValue:C[x]};break}}const w=b=>{const P=r.find(F=>F.panelId===b.panelId);if(!P)throw new Y(b);const x=Q();return new q({colors:m,id:x,svg:f,type:k.Illustration,y:b.top,x:b.left,rotation:b.rotation,width:b.width,height:b.height,layer:b.layer,layerIndex:b.layerIndex,immutable:b.immutable},P)},S=a.data.regions;try{return S.map(w)}catch(b){return console.error(b),[]}},$l=async(r,t,e)=>{const a=await hr(e.data.module),n=t.data,i=(o,l)=>{const c=r.find(A=>A.panelId===l.panelId);if(!c)throw new Y(l);const d=Q();return new q({colors:{},id:d,svg:o,type:k.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex},c)},s=e.data.regions;try{return s.map(o=>i(a.svgPrint(n.text,o),o))}catch(o){return console.error(o),[]}},Ul=async(r,t,e,a)=>{var d,A;const n=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const s=((d=i.variants)==null?void 0:d.find(u=>u.id===n.pictureVariantId))||de(i);if(!s)return console.error(`No variant with ID: ${n.pictureVariantId}`),[];if(!s.asset)return console.error(`No asset for variant with ID: ${n.pictureVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=(A=s.asset)==null?void 0:A.fileLink;if(!o)return console.error(`No asset link for variant with ID: ${n.pictureVariantId}`),[];const l=u=>{const h=r.find(m=>m.panelId===u.panelId);if(!h)throw new Y(u);const g=Q();return new q({id:g,src:o,type:k.Image,y:u.top,x:u.left,rotation:u.rotation,width:u.width,height:u.height,layer:u.layer,layerIndex:u.layerIndex,immutable:u.immutable,preserveAspectRatio:"none"},h)},c=a.data.regions;try{return c.map(l)}catch(u){return console.error(u),[]}},Ll=async(r,t,e,a)=>{var c;const n=e.data,i=a.option;if(!i)return console.error(`No option for step ${a.stepName}.`),[];const s=((c=i.variants)==null?void 0:c.find(d=>d.id===n.colorVariantId))||de(i);if(!s)return console.error(`No variant with ID: ${n.colorVariantId}`),[];t[a.stepName]={selectedVariants:[s]};const o=d=>{const A=r.find(p=>p.panelId===d.panelId);if(!A)throw new Y(d);const u=`
|
|
2242
2246
|
<svg
|
|
2243
2247
|
xmlns="http://www.w3.org/2000/svg"
|
|
2244
2248
|
xmlnsXlink="http://www.w3.org/1999/xlink"
|
|
@@ -2270,7 +2274,7 @@
|
|
|
2270
2274
|
}
|
|
2271
2275
|
}
|
|
2272
2276
|
}
|
|
2273
|
-
`;class nc{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:ac,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 Nr=new nc;var Qr=(r=>(r.Default="Default",r.Name="Name",r.Price="Price",r))(Qr||{});class za{constructor(t){this.fullFetched=!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 Ht(t))}async fetchProducts(t){if(this.fullFetched)return this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new Ht(a));const e=await B.getShadowGraphqlClient().query({query:Jo,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 Ht(a))}async filterProducts(t,e,a,n){var l,c;const i=await B.getShadowGraphqlClient().query({query:Ko,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){if(this.fullFetched){const d=await(a?this.filterProducts(a):this.fetchProducts());return{total:d.length,items:d.slice(t,t+e)}}const o=new AbortController,{signal:l}=o,c=B.getShadowGraphqlClient().watchQuery({query:_o,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:"cache-first",returnPartialData:!0,context:{fetchOptions:{signal:l}}});return new Promise(d=>{let A=!1;const u=c.subscribe({next(h){var m,p,f,C,w,S;if(A||h.partial&&(!h.data.productCollections||h.data.productCollections.length===0||!((m=h.data.productCollections[0].productCollectionProductsFeed)!=null&&m.items)||((p=h.data.productCollections[0].productCollectionProductsFeed)==null?void 0:p.items.length)===0))return;o.abort(),A=!0,u.unsubscribe();const g=((C=(f=h.data.productCollections)==null?void 0:f[0].productCollectionProductsFeed)==null?void 0:C.items.filter(y=>!!y.product).map(y=>new Ht(Et(y))))||[];d({items:g,total:((S=(w=h.data.productCollections)==null?void 0:w[0].productCollectionProductsFeed)==null?void 0:S.total)??0})},error(){A||(A=!0,u.unsubscribe(),d({items:[],total:0}))}})})}getTransformCollection(){if(this.collection.transformCollection)return new Rr(this.collection.transformCollection)}getResource(){return this.collection}}class Ht{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 Mt(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 Mt(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 Mt(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 Nr.requestKeysForEntity(this.product.id,t)}}class Mt{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class Rr{constructor(t){this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(t=>new Or(t))}}class Or{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 rc=v.gql`
|
|
2277
|
+
`;class nc{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:ac,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 Nr=new nc;var Qr=(r=>(r.Default="Default",r.Name="Name",r.Price="Price",r))(Qr||{});class za{constructor(t){this.fullFetched=!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||""}getDispatchStartDate(){if(this.collection.dispatchStartDate)return new Date(this.collection.dispatchStartDate)}getDispatchEndDate(){if(this.collection.dispatchEndDate)return new Date(this.collection.dispatchEndDate)}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 Ht(t))}async fetchProducts(t){if(this.fullFetched)return this.collection.productCollectionProducts.filter(a=>!!a.product).map(a=>new Ht(a));const e=await B.getShadowGraphqlClient().query({query:Jo,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 Ht(a))}async filterProducts(t,e,a,n){var l,c;const i=await B.getShadowGraphqlClient().query({query:Ko,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){if(this.fullFetched){const d=await(a?this.filterProducts(a):this.fetchProducts());return{total:d.length,items:d.slice(t,t+e)}}const o=new AbortController,{signal:l}=o,c=B.getShadowGraphqlClient().watchQuery({query:_o,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:"cache-first",returnPartialData:!0,context:{fetchOptions:{signal:l}}});return new Promise(d=>{let A=!1;const u=c.subscribe({next(h){var m,p,f,C,w,S;if(A||h.partial&&(!h.data.productCollections||h.data.productCollections.length===0||!((m=h.data.productCollections[0].productCollectionProductsFeed)!=null&&m.items)||((p=h.data.productCollections[0].productCollectionProductsFeed)==null?void 0:p.items.length)===0))return;o.abort(),A=!0,u.unsubscribe();const g=((C=(f=h.data.productCollections)==null?void 0:f[0].productCollectionProductsFeed)==null?void 0:C.items.filter(y=>!!y.product).map(y=>new Ht(Et(y))))||[];d({items:g,total:((S=(w=h.data.productCollections)==null?void 0:w[0].productCollectionProductsFeed)==null?void 0:S.total)??0})},error(){A||(A=!0,u.unsubscribe(),d({items:[],total:0}))}})})}getTransformCollection(){if(this.collection.transformCollection)return new Rr(this.collection.transformCollection)}getResource(){return this.collection}}class Ht{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 Mt(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 Mt(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 Mt(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 Nr.requestKeysForEntity(this.product.id,t)}}class Mt{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class Rr{constructor(t){this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(t=>new Or(t))}}class Or{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 rc=v.gql`
|
|
2274
2278
|
${he(!1)}
|
|
2275
2279
|
query GetProductCollections($ids: [String!]!) {
|
|
2276
2280
|
productCollections(ids: $ids) {
|
|
@@ -2435,7 +2439,7 @@
|
|
|
2435
2439
|
}
|
|
2436
2440
|
}
|
|
2437
2441
|
}
|
|
2438
|
-
`;class pc{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??{}}})}}class fc{init(t,e,a){this.cognitoClient=new me.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){var a;const e=await((a=this.cognitoClient)==null?void 0:a.send(new me.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}})));(e==null?void 0:e.ChallengeName)==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){var n;return await((n=this.cognitoClient)==null?void 0:n.send(new me.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}})))}async refreshTokens(){var a;const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await((a=this.cognitoClient)==null?void 0:a.send(new me.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}})))}}const Wt=new fc;class Vr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return ci(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ja.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t,a=Ja.code(e);if((a==null?void 0:a.code)==="CLP")return"USD0,0"}}const An=new Vr;class zr{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,An.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,An.getPrecisionForCurrency(e))}}const Cc=async(r,t)=>{var n;const e=await B.getShadowGraphqlClient().query({query:Ss(((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)}),Ot.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},wc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},Wa=async(r,t)=>{const e=r.map(o=>Ot.get({id:o,options:t})),a=r.filter((o,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=Cc(a,t),i=a.map(o=>Ot.set({id:o,options:t},wc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},yc=async(r,t)=>(await Wa([r],t))[0],Sc=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:Q(),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})),vc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):Sc(t.panels)};class Ec{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return B.getShadowGraphqlClient().mutate({...e,mutation:cs})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ii(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 29.0.1"),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,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Qn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!Pi())throw new Error("Application key required to use Flow Service.");return new $r}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await B.getShadowGraphqlClient().query({query:xs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:s,rateTo:o}=i.data.currencyConversion;return new zr(s,o,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Gr(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=N.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const a=N.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const s=a.get(t);if((N.getMap("partnerCustomerIds")||new Map).get(s)&&await this.reloadLoggedInCustomer()){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:vs,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=N.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const o=N.getMap("transactionCustomerIds");if(o!=null&&o.has(t)&&o.get(t)&&await this.reloadLoggedInCustomer()){const C=((h=(u=this.customer)==null?void 0:u.bundleStakeholders)==null?void 0:h.find(w=>{var S,y;return(y=(S=w.bundle)==null?void 0:S.transactions)==null?void 0:y.some(E=>E.id===t)}))||((m=(g=this.customer)==null?void 0:g.stakeholders)==null?void 0:m.find(w=>{var S;return((S=w.transaction)==null?void 0:S.id)===t}));if(C)return Promise.resolve({success:!0,stakeholderType:C.type})}const c=(await e.query({query:Es,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=N.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),N.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await B.getShadowGraphqlClient().query({query:ye,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:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:hc,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.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),i=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l!=null&&l.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const o=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return o.id?(this.customer=o,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await B.getShadowGraphqlClient().mutate({mutation:gc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n!=null&&n.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const s=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!s.id)throw new Error("Failed to get customer.");return this.customer=s,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,i=!(a!=null&&a.AccessToken)||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||i){const s=await Wt.refreshTokens();if(s!=null&&s.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){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:mc,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:Xo(((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=N.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),N.setMap("bundlePartnerIds",s);const o=N.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),N.setMap("bundleOwnerIds",o);const l=new ta(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 g,m,p,f,C,w,S,y,E,b,P;const i=N.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),o={};try{const x=await this.loggedInBearerToken();o.Authorization=`Bearer ${x}`}catch{const M=((g=Object.entries(localStorage).find(([Z,R])=>Z.startsWith("CognitoIdentityServiceProvider")&&Z.endsWith("idToken")))==null?void 0:g[0])||"",T=localStorage.getItem(M);T&&!_t(T)&&(o.Authorization=`Bearer ${T}`)}const l={bundleOwnerId:s,...o,...(m=n==null?void 0:n.graphql)==null?void 0:m.additionalHeaders},c=await B.getShadowGraphqlClient().query({query:Ho(((f=(p=n==null?void 0:n.graphql)==null?void 0:p.productCollection)==null?void 0:f.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!((C=c.data)!=null&&C.bundles)||((w=c.data)==null?void 0:w.bundles.length)===0||!((S=c.data)!=null&&S.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const d=(y=c.data)==null?void 0:y.bundles[0],A=N.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),N.setMap("bundlePartnerIds",A);const u=new ta(this,d,e,a,s,{additionalHeaders:(E=n==null?void 0:n.graphql)==null?void 0:E.additionalHeaders,eagerFetchProducts:(P=(b=n==null?void 0:n.graphql)==null?void 0:b.productCollection)==null?void 0:P.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:n==null?void 0:n.readonly});await u.getInitializationPromise();const h=c.data.globalPropertyState;return h&&u.applyGlobalPropertyState(h),u}async duplicateBundle(t,e,a,n){var u,h,g,m,p,f;const i=(u=N.getMap("bundleOwnerIds"))==null?void 0:u.get(t),s={};try{const C=await this.loggedInBearerToken();s.Authorization=`Bearer ${C}`}catch{const S=((h=Object.entries(localStorage).find(([E,b])=>E.startsWith("CognitoIdentityServiceProvider")&&E.endsWith("idToken")))==null?void 0:h[0])||"",y=localStorage.getItem(S);y&&!_t(y)&&(s.Authorization=`Bearer ${y}`)}const o={bundleOwnerId:i,...s,...(g=n==null?void 0:n.graphql)==null?void 0:g.additionalHeaders},c=(f=(await B.getShadowGraphqlClient().mutate({mutation:Zo(((p=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:p.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data)==null?void 0:f.bundleDuplicate;if(!(c!=null&&c.id))throw new Error("Unable to duplicate bundle");const d=N.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),N.setMap("bundlePartnerIds",d);const A=N.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),N.setMap("bundleOwnerIds",A),async()=>{var w,S;const C=new ta(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:(S=(w=n==null?void 0:n.graphql)==null?void 0:w.productCollection)==null?void 0:S.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});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 B.getShadowGraphqlClient().query({query:Al(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:Yo,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=N.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)}),N.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 y=>{var x,F,M;if(y.length===0)return[];const E=y.map(T=>T.option.transactionId),b=await a.query({query:ls,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),P=b.data.transactions;if(P.length!==y.length){const T=((F=(x=b.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Not all transactions were found: ${T}`)}return!this.activeIntegration&&((M=P[0].integrationProduct)!=null&&M.integration)&&(this.activeIntegration=Promise.resolve(P[0].integrationProduct.integration)),P.map((T,Z)=>{var R;return{transaction:T,workflowId:T.workflowId,readOnly:((R=y.find(at=>at.option.transactionId===T.id))==null?void 0:R.option.readOnly)??!1,index:y[Z].index}})},i=async y=>{var P,x,F;if(y.length===0)return[];const E=await a.mutate({mutation:os,variables:{inputs:y.map(M=>({integrationProductId:M.option.type==="integration"?M.option.integrationProductId:void 0,externalIntegrationId:M.option.type==="external"?M.option.externalIntegrationId:void 0,externalProductId:M.option.type==="external"?M.option.externalProductId:void 0,workflowId:M.option.workflowId,designName:M.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),b=(P=E.data)==null?void 0:P.transactionCreateMany;if(!b||b.length===0){const M=((F=(x=E.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Failed to create transactions: ${M}`)}return b.map((M,T)=>({transaction:M,workflowId:M.workflowId,readOnly:!1,index:y[T].index}))},s=t.map((y,E)=>({option:y,index:E})),o=s.filter(y=>y.option.type==="transaction"),l=s.filter(y=>y.option.type==="integration"||y.option.type==="external"),c=Ya(o,10),d=Ya(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(y=>y.workflowId))],h=await Wa(u,e),g=new Map(h.map(y=>[y.id,y])),m=N.getMap("transactionOwnerIds")||new Map,p=A.map(async y=>{var at;const{transaction:E,workflowId:b,readOnly:P,index:x}=y,F=g.get(b),M=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const T=m.get(E.id)||void 0,Z=new pc({onMutate:()=>({context:{transactionOwnerId:T,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:T,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})}),R={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:(at=M==null?void 0:M.workflowConfiguration)==null?void 0:at.singleVariantsRenderable,stateMutationFunc:P?async()=>{throw new z("State mutation is forbidden in read only mode!")}:async tt=>this.updateTransactionState({...tt,context:{transactionOwnerId:T,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),graphQlClient:()=>Z,readOnly:P,workflow:F,isReloadedTransaction:M.type==="transaction"};if(!P&&M.workflowState){const tt=JSON.parse(M.workflowState);R.layouts=Object.values(tt.layouts||{}).map(Ut=>Ut.layout),await ir(tt),R.reloadedState=tt}else R.layouts=vc(R.transaction,R.workflow);return R.renderableContextService=new ql(R.layouts),R.delayWorkflowStateSync=!0,{experienceOptions:R,index:x,options:M}}),f=await Promise.all(p);N.setMap("transactionOwnerIds",m);const w=f.sort((y,E)=>y.index-E.index).map(async y=>{const{experienceOptions:E,options:b}=y,P=new Fr(this,E);return await P.getWorkflowManager().getInitializationPromise(),b.type!=="transaction"&&this.customer&&await P.attachCustomerDetails({email:this.customer.emailAddress}),P}),S=await Promise.all(w);return S.forEach(y=>y.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),S}storeCustomer(t){const e=N.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),N.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){var s,o;const i=(s=(await B.getShadowGraphqlClient().query({query:hs(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 Ca(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await B.getShadowGraphqlClient().query({query:gs(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 Ca(s)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(N.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await B.getShadowGraphqlClient().query({query:us,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:Ds,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 Gr=async(r,t)=>(await B.getShadowGraphqlClient().query({query:Bs,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,bc=async r=>{const e=await B.getShadowGraphqlClient().query({query:As,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Bc=async(r,t)=>{var a;return(a=(await B.getShadowGraphqlClient().query({query:bs,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},Ic=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Ps,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},Pc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Is,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function qr(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=Se(r.x,t.width-c,0),o.y=Se(r.y,t.height-d,0),o}const s=r;return s.x=Se(s.x,-n,t.width),s.y=Se(s.y,-i,t.height),s}function Se(r,t,e){return Math.min(Math.max(r,t),e)}class Wr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=vn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let s=0;s<n.currentFrameSources.length;s++){const o=n.currentFrameSources[s],l=await Ae(o),c=this.frameData?this.frameData[s]:void 0;Sn(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=$e(this.imageData.svg,this.imageData.colors||{},!1);return Re(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 z("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]=qr(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 z("Frame data not set. This is a bug");if(!this.workflowManager)throw new z("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,l)=>{s(new $([new go(o,e,t[l]),new mo(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]=Fa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Dc{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 jr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(jr||{});class Hr extends rt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Wr(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(ke.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 ot(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 xc=v.gql`
|
|
2442
|
+
`;class pc{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??{}}})}}class fc{init(t,e,a){this.cognitoClient=new me.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){var a;const e=await((a=this.cognitoClient)==null?void 0:a.send(new me.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}})));(e==null?void 0:e.ChallengeName)==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){var n;return await((n=this.cognitoClient)==null?void 0:n.send(new me.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}})))}async refreshTokens(){var a;const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await((a=this.cognitoClient)==null?void 0:a.send(new me.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}})))}}const Wt=new fc;class Vr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return ci(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ja.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t,a=Ja.code(e);if((a==null?void 0:a.code)==="CLP")return"USD0,0"}}const An=new Vr;class zr{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,An.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,An.getPrecisionForCurrency(e))}}const Cc=async(r,t)=>{var n;const e=await B.getShadowGraphqlClient().query({query:Ss(((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)}),Ot.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},wc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},Wa=async(r,t)=>{const e=r.map(o=>Ot.get({id:o,options:t})),a=r.filter((o,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=Cc(a,t),i=a.map(o=>Ot.set({id:o,options:t},wc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},yc=async(r,t)=>(await Wa([r],t))[0],Sc=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:Q(),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})),vc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):Sc(t.panels)};class Ec{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return B.getShadowGraphqlClient().mutate({...e,mutation:cs})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ii(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 29.0.3"),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,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Qn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!Pi())throw new Error("Application key required to use Flow Service.");return new $r}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await B.getShadowGraphqlClient().query({query:xs,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:s,rateTo:o}=i.data.currencyConversion;return new zr(s,o,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Gr(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=N.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const a=N.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const s=a.get(t);if((N.getMap("partnerCustomerIds")||new Map).get(s)&&await this.reloadLoggedInCustomer()){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:vs,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=N.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const o=N.getMap("transactionCustomerIds");if(o!=null&&o.has(t)&&o.get(t)&&await this.reloadLoggedInCustomer()){const C=((h=(u=this.customer)==null?void 0:u.bundleStakeholders)==null?void 0:h.find(w=>{var S,y;return(y=(S=w.bundle)==null?void 0:S.transactions)==null?void 0:y.some(E=>E.id===t)}))||((m=(g=this.customer)==null?void 0:g.stakeholders)==null?void 0:m.find(w=>{var S;return((S=w.transaction)==null?void 0:S.id)===t}));if(C)return Promise.resolve({success:!0,stakeholderType:C.type})}const c=(await e.query({query:Es,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=N.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),N.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await B.getShadowGraphqlClient().query({query:ye,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:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:hc,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.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),i=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l!=null&&l.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const o=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return o.id?(this.customer=o,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await B.getShadowGraphqlClient().mutate({mutation:gc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n!=null&&n.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const s=(await B.getShadowGraphqlClient().query({query:ye,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!s.id)throw new Error("Failed to get customer.");return this.customer=s,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,i=!(a!=null&&a.AccessToken)||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||i){const s=await Wt.refreshTokens();if(s!=null&&s.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){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:mc,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:Xo(((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=N.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),N.setMap("bundlePartnerIds",s);const o=N.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),N.setMap("bundleOwnerIds",o);const l=new ta(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 g,m,p,f,C,w,S,y,E,b,P;const i=N.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),o={};try{const x=await this.loggedInBearerToken();o.Authorization=`Bearer ${x}`}catch{const M=((g=Object.entries(localStorage).find(([Z,R])=>Z.startsWith("CognitoIdentityServiceProvider")&&Z.endsWith("idToken")))==null?void 0:g[0])||"",T=localStorage.getItem(M);T&&!_t(T)&&(o.Authorization=`Bearer ${T}`)}const l={bundleOwnerId:s,...o,...(m=n==null?void 0:n.graphql)==null?void 0:m.additionalHeaders},c=await B.getShadowGraphqlClient().query({query:Ho(((f=(p=n==null?void 0:n.graphql)==null?void 0:p.productCollection)==null?void 0:f.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!((C=c.data)!=null&&C.bundles)||((w=c.data)==null?void 0:w.bundles.length)===0||!((S=c.data)!=null&&S.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const d=(y=c.data)==null?void 0:y.bundles[0],A=N.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),N.setMap("bundlePartnerIds",A);const u=new ta(this,d,e,a,s,{additionalHeaders:(E=n==null?void 0:n.graphql)==null?void 0:E.additionalHeaders,eagerFetchProducts:(P=(b=n==null?void 0:n.graphql)==null?void 0:b.productCollection)==null?void 0:P.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:n==null?void 0:n.readonly});await u.getInitializationPromise();const h=c.data.globalPropertyState;return h&&u.applyGlobalPropertyState(h),u}async duplicateBundle(t,e,a,n){var u,h,g,m,p,f;const i=(u=N.getMap("bundleOwnerIds"))==null?void 0:u.get(t),s={};try{const C=await this.loggedInBearerToken();s.Authorization=`Bearer ${C}`}catch{const S=((h=Object.entries(localStorage).find(([E,b])=>E.startsWith("CognitoIdentityServiceProvider")&&E.endsWith("idToken")))==null?void 0:h[0])||"",y=localStorage.getItem(S);y&&!_t(y)&&(s.Authorization=`Bearer ${y}`)}const o={bundleOwnerId:i,...s,...(g=n==null?void 0:n.graphql)==null?void 0:g.additionalHeaders},c=(f=(await B.getShadowGraphqlClient().mutate({mutation:Zo(((p=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:p.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data)==null?void 0:f.bundleDuplicate;if(!(c!=null&&c.id))throw new Error("Unable to duplicate bundle");const d=N.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),N.setMap("bundlePartnerIds",d);const A=N.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),N.setMap("bundleOwnerIds",A),async()=>{var w,S;const C=new ta(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:(S=(w=n==null?void 0:n.graphql)==null?void 0:w.productCollection)==null?void 0:S.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});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 B.getShadowGraphqlClient().query({query:Al(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:Yo,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=N.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)}),N.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 y=>{var x,F,M;if(y.length===0)return[];const E=y.map(T=>T.option.transactionId),b=await a.query({query:ls,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),P=b.data.transactions;if(P.length!==y.length){const T=((F=(x=b.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Not all transactions were found: ${T}`)}return!this.activeIntegration&&((M=P[0].integrationProduct)!=null&&M.integration)&&(this.activeIntegration=Promise.resolve(P[0].integrationProduct.integration)),P.map((T,Z)=>{var R;return{transaction:T,workflowId:T.workflowId,readOnly:((R=y.find(at=>at.option.transactionId===T.id))==null?void 0:R.option.readOnly)??!1,index:y[Z].index}})},i=async y=>{var P,x,F;if(y.length===0)return[];const E=await a.mutate({mutation:os,variables:{inputs:y.map(M=>({integrationProductId:M.option.type==="integration"?M.option.integrationProductId:void 0,externalIntegrationId:M.option.type==="external"?M.option.externalIntegrationId:void 0,externalProductId:M.option.type==="external"?M.option.externalProductId:void 0,workflowId:M.option.workflowId,designName:M.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),b=(P=E.data)==null?void 0:P.transactionCreateMany;if(!b||b.length===0){const M=((F=(x=E.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Failed to create transactions: ${M}`)}return b.map((M,T)=>({transaction:M,workflowId:M.workflowId,readOnly:!1,index:y[T].index}))},s=t.map((y,E)=>({option:y,index:E})),o=s.filter(y=>y.option.type==="transaction"),l=s.filter(y=>y.option.type==="integration"||y.option.type==="external"),c=Ya(o,10),d=Ya(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(y=>y.workflowId))],h=await Wa(u,e),g=new Map(h.map(y=>[y.id,y])),m=N.getMap("transactionOwnerIds")||new Map,p=A.map(async y=>{var at;const{transaction:E,workflowId:b,readOnly:P,index:x}=y,F=g.get(b),M=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const T=m.get(E.id)||void 0,Z=new pc({onMutate:()=>({context:{transactionOwnerId:T,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:T,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})}),R={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:(at=M==null?void 0:M.workflowConfiguration)==null?void 0:at.singleVariantsRenderable,stateMutationFunc:P?async()=>{throw new z("State mutation is forbidden in read only mode!")}:async tt=>this.updateTransactionState({...tt,context:{transactionOwnerId:T,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),graphQlClient:()=>Z,readOnly:P,workflow:F,isReloadedTransaction:M.type==="transaction"};if(!P&&M.workflowState){const tt=JSON.parse(M.workflowState);R.layouts=Object.values(tt.layouts||{}).map(Ut=>Ut.layout),await ir(tt),R.reloadedState=tt}else R.layouts=vc(R.transaction,R.workflow);return R.renderableContextService=new ql(R.layouts),R.delayWorkflowStateSync=!0,{experienceOptions:R,index:x,options:M}}),f=await Promise.all(p);N.setMap("transactionOwnerIds",m);const w=f.sort((y,E)=>y.index-E.index).map(async y=>{const{experienceOptions:E,options:b}=y,P=new Fr(this,E);return await P.getWorkflowManager().getInitializationPromise(),b.type!=="transaction"&&this.customer&&await P.attachCustomerDetails({email:this.customer.emailAddress}),P}),S=await Promise.all(w);return S.forEach(y=>y.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),S}storeCustomer(t){const e=N.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),N.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){var s,o;const i=(s=(await B.getShadowGraphqlClient().query({query:hs(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 Ca(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await B.getShadowGraphqlClient().query({query:gs(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 Ca(s)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(N.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await B.getShadowGraphqlClient().query({query:us,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:Ds,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 Gr=async(r,t)=>(await B.getShadowGraphqlClient().query({query:Bs,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,bc=async r=>{const e=await B.getShadowGraphqlClient().query({query:As,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Bc=async(r,t)=>{var a;return(a=(await B.getShadowGraphqlClient().query({query:bs,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},Ic=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Ps,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},Pc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Is,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function qr(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=Se(r.x,t.width-c,0),o.y=Se(r.y,t.height-d,0),o}const s=r;return s.x=Se(s.x,-n,t.width),s.y=Se(s.y,-i,t.height),s}function Se(r,t,e){return Math.min(Math.max(r,t),e)}class Wr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=vn(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let s=0;s<n.currentFrameSources.length;s++){const o=n.currentFrameSources[s],l=await Ae(o),c=this.frameData?this.frameData[s]:void 0;Sn(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=$e(this.imageData.svg,this.imageData.colors||{},!1);return Re(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 z("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]=qr(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 z("Frame data not set. This is a bug");if(!this.workflowManager)throw new z("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,l)=>{s(new $([new go(o,e,t[l]),new mo(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]=Fa(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Dc{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 jr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(jr||{});class Hr extends rt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Wr(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(ke.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 ot(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 xc=v.gql`
|
|
2439
2443
|
query GetLoggedInCustomer($email: String!) {
|
|
2440
2444
|
customer(emailAddress: $email) {
|
|
2441
2445
|
id
|