@spiffcommerce/core 29.1.2 → 29.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -14,6 +14,12 @@ 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.2.0] - 25-08-2025
18
+
19
+ ## Added
20
+
21
+ - Added the function `TextGlobalPropertyHandle.isTemplatingEnabled(): boolean`. Use this to determine whether you should display any templating tools.
22
+
17
23
  ## [29.1.2] - 25-08-2025
18
24
 
19
25
  ## Changed
package/dist/index.d.ts CHANGED
@@ -1454,6 +1454,11 @@ declare class FileUploadGlobalPropertyHandle extends GlobalPropertyHandle {
1454
1454
  }
1455
1455
  declare class TextGlobalPropertyHandle extends GlobalPropertyHandle {
1456
1456
  constructor(bundle: Bundle$1, property: GlobalPropertyConfigurationAspect);
1457
+ /**
1458
+ * If this returns false, you should not display any templating tools.
1459
+ * Note: Templates will currently still be rendered, regardless of what this function returns.
1460
+ */
1461
+ isTemplatingEnabled(): boolean;
1457
1462
  /**
1458
1463
  * Gets the current text
1459
1464
  */
@@ -2897,13 +2902,17 @@ interface GlobalPropertyConfigurationAspect {
2897
2902
  data?: GlobalPropertyConfigurationAspectData;
2898
2903
  }
2899
2904
  interface GlobalPropertyConfigurationAspectData {
2900
- fileUpload: GlobalPropertyConfigurationAspectFileUploadData;
2905
+ fileUpload?: GlobalPropertyConfigurationAspectFileUploadData;
2906
+ text?: GlobalPropertyConfigurationAspectTextData;
2901
2907
  }
2902
2908
  interface GlobalPropertyConfigurationAspectFileUploadData {
2903
2909
  colorPickerEnabled?: boolean;
2904
2910
  pmsPickerEnabled?: boolean;
2905
2911
  colorOptionId?: string;
2906
2912
  }
2913
+ interface GlobalPropertyConfigurationAspectTextData {
2914
+ templatingEnabled?: boolean;
2915
+ }
2907
2916
  interface GlobalPropertyConfigurationAspectCondition {
2908
2917
  targetAspectName?: string;
2909
2918
  action: AspectConditionAction;
package/dist/index.js CHANGED
@@ -1613,6 +1613,9 @@
1613
1613
  pmsPickerEnabled
1614
1614
  colorOptionId
1615
1615
  }
1616
+ text {
1617
+ templatingEnabled
1618
+ }
1616
1619
  }
1617
1620
  }
1618
1621
  }
@@ -2275,7 +2278,7 @@
2275
2278
  />
2276
2279
  </svg>
2277
2280
  `,g={"spiff-fill-shape":{browserValue:s.color||"#000000"}},m=Q();return new q({colors:g,id:m,svg:u,type:k.Illustration,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable},A)},l=a.data.regions;try{return l.map(o)}catch(d){return console.error(d),[]}},Gl=async(r,t,e)=>{const a=[],i=(()=>{var c,d;return t.type===I.ProductOverlay?e||((c=t.data.asset)==null?void 0:c.fileLink)||"":((d=t.data.asset)==null?void 0:d.fileLink)||""})(),o=(()=>i.endsWith(".jpeg")||i.endsWith(".jpg")||i.endsWith(".png")?k.Image:(i.endsWith(".svg"),k.Illustration))(),l=t.data.regions;if(o==="image")try{l.forEach(c=>{const d=r.find(u=>u.panelId===c.panelId);if(!d)throw new Y(c);const A={id:Q(),src:i,type:o,y:c.top,x:c.left,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,productOverlay:t.type===I.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:c.rotation,excludeFromExport:t.data.excludeFromPrint,preserveAspectRatio:"none"};a.push(new q(A,d))})}catch(c){console.error(c)}else{const c=await et(i,!0),d=A=>{const u=/<svg.*?<\/svg>/s,h=A.match(u)||[],g=(h==null?void 0:h.length)>0?h[0]:"",f=ct().parseFromString(g,"image/svg+xml").firstElementChild;if(!f)throw new St("Failed to read SVG.");return $e(f),wt().serializeToString(f)};l.forEach(A=>{const u=r.find(g=>g.panelId===A.panelId);if(!u)throw new Y(A);const h={id:Q(),src:i,asset_key:i,svg:d(c),colors:{},type:o,y:A.top,x:A.left,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,scaleX:1,scaleY:1,rotation:A.rotation,productOverlay:t.type===I.ProductOverlay?!0:void 0,excludeFromExport:t.data.excludeFromPrint};a.push(new q(h,u))})}return a},ql=async(r,t,e,a)=>{const n=[],i=e.data,s=30,o=p=>p.vertical?"center":p.textAlign||"center",l=()=>{var w;const p=a.option;if(!p)return;const f=((w=p.variants)==null?void 0:w.find(S=>S.id===i.fontVariantId))||Ae(p);if(!f||!f.asset)return;t[a.stepName]={selectedVariants:[f]};const C=f.asset.fileLink;if(C)return C},d=await(async()=>{const p=l();if(!p)return;const f=await It(p);return{assetUrl:p,name:f.names.fullName.en}})(),A=(a.data.replaceableText?a.data.replaceableText.replace("{{}}",i.text):i.text)||"",u=De(A,{vertical:a.data.vertical,uppercase:a.data.uppercase}),h=async p=>{const f=p.colorOption;if(!f)return;const C=H.getDefaultVariant(f);return C==null?void 0:C.color},g=i.color||await h(a.data),m=a.data.regions;for(const p of m){const f=r.find(w=>w.panelId===p.panelId);if(!f)continue;const C={stepName:e.name,id:Q(),align:o(a.data),curved:a.data.curved,fill:i.color||g||"#000000",fontData:d,fontSize:a.data.size||s,height:p.height,layer:p.layer,layerIndex:p.layerIndex,paths:a.data.paths,rotation:p.rotation,text:u,type:k.Textbox,vertical:a.data.vertical,verticalAlign:a.data.verticalAlign||"middle",width:p.width,x:p.left,y:p.top};if(d){const[w,S]=Kt(a.data.size||s,d,p,[De(u,{vertical:a.data.vertical,uppercase:a.data.uppercase})],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});n.push(new q({...C,fontSize:w,text:C.curved?C.text:(S||[]).join(`
2278
- `)},f))}else n.push(new q(C,f))}return n},Wl=(r,t)=>r.conditions?r.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const n=a.selectedVariants;return e.requiredVariantSelections.some(i=>n.find(s=>s.id===i)!==void 0)}return!1}):!0,Tr=async(r,t,e,a)=>{const n=[],i={};for(const s of r){const o=t.steps.find(l=>l.stepName===s.name);if(o)switch(o.type){case I.DigitalContent:n.push(...await Ol(e,s,o));break;case I.Frame:case I.Photo:n.push(...await $l(e,i,s,o));break;case I.Illustration:n.push(...await Ul(e,i,s,o));break;case I.Module:n.push(...await Ll(e,s,o));break;case I.Picture:n.push(...await Vl(e,i,s,o));break;case I.Shape:n.push(...await zl(e,i,s,o));break;case I.Text:n.push(...await ql(e,i,s,o));break}}for(const s of t.steps)s.type!==I.SilentIllustration&&s.type!==I.ProductOverlay||Wl(s,i)&&n.push(...await Gl(e,s,a));return n};class jl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Jl(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Hl=()=>new Promise((r,t)=>{try{const a=pt().getContext("webgl2");r(!!a)}catch{r(!1)}}),Yl=Hl();class Jl{constructor(t,e,a,n,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Da(2),this.id=t,this.name=e,this.service=a,this.panelSize=n,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=Et(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new Kl(this.getID(),a,await Yl,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class Kl extends Pa{constructor(t,e,a,n,i,s){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=n,this.layouts=i,this.getWorkflowManager=s}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,n=e/t.height,i=Math.min(a,n);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){var h,g;const t=this.layouts.find(m=>m.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,n=t.layoutState.layout.height,i=a===1||n===1?{width:1,height:1}:this.getDynamicTextureResolution(),s=i.width,o=i.height;let l,c;if(this.nonPOTSupport){const m=s/o;a/n<m?(l=s,c=n*(s/a)):(l=a*(o/n),c=o);const f=this.resizeFit({width:l,height:c});l=f.width,c=f.height}else l=i.width,c=i.height;const d=ze(t.layoutState.layout,e,{renderingConfiguration:{purpose:Tt.ThreeD,templatingContext:(g=(h=this.getWorkflowManager)==null?void 0:h.call(this))==null?void 0:g.getTemplatingContext()}}),A=Tn(d),u=await Sa.Pith.from(this.ctx,A,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:pt,createImage:oe,DOMParser:ba(),fetch});u.resize(l,c),await u.render(),this.onRender()}}const _l=(r,t)=>{const e=[];return r.forEach(a=>{const n=t.steps.find(i=>i.stepName===a.stepName);(n==null?void 0:n.type)===I.Text&&a.stepAspectType==="Text"&&e.push({name:n.stepName,data:{text:a.value}})}),e},Xl=async(r,t,e,a)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};n=new $(e.map(l=>new Na(l))).apply(n);const s=await Tr(r,t,e,a);return new $(s).apply(n)};class Zl{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){var e;if(!((e=this.bundle.getProductCollection())!=null&&e.getResource().globalPropertyConfiguration))return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(a=>this.getHandle(a)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const n=e.aspects.find(i=>i.name===a.targetAspectName);return n?a.requiredVariantSelections.some(i=>i===n.value):!1})}async createHandle(t){switch(t.type){case V.FileUpload:return new Nr(this.bundle,t).initialize();case V.ColorOption:return new Ca(this.bundle,t,t.entityId?await H.getOption(t.entityId):void 0);case V.Option:{const e=t.entityId?await H.getOption(t.entityId):void 0;return(e==null?void 0:e.type)==="Color"?new Ca(this.bundle,t,e):new za(this.bundle,t,e)}case V.Text:return new Qr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Ge{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(n=>n.getStepsConditionallyActive().filter(i=>{var s;return i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:(s=i.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name})}))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Nr extends Ge{constructor(t,e){super(t,e)}async initialize(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorOptionId&&(this.colorOption=await H.getOption((n=(a=this.property.data)==null?void 0:a.fileUpload)==null?void 0:n.colorOptionId)),await this.loadImageData(),this}async loadImageData(){var e;const t=await this.getImage();if(t!=null&&t.fileLink)if(t!=null&&t.fileLink.endsWith(".svg")){const a=await et(t==null?void 0:t.fileLink),n=await Ma(t==null?void 0:t.fileLink),i=n.width,s=n.height,o=await ot(a),l=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);(e=l==null?void 0:l.colors)==null||e.forEach(d=>{o.colors[d.key]={browserValue:d.browserValue,pmsValue:d.pmsValue}});const c={src:t==null?void 0:t.fileLink,width:i,height:s,aspect:i/s,svg:o.svg,colors:o.colors};dt.set(t==null?void 0:t.fileLink,c),this.imageData=c}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Me.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await U.removeBackgroundFromAsset(e),s={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,s):a.setAspectStorage(this.property.name,s)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return U.getLocalOrFromServer(t)}async getImageWithColors(){var t,e;return await this.loadImageData(),(t=this.imageData)!=null&&t.svg?Oe(Ue(this.imageData.svg,this.imageData.colors??{},!1)):(e=this.imageData)==null?void 0:e.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.originalAssetKey)return U.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.backgroundRemovedAssetKey)return U.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){var t;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.useOriginalAsset)??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if((n==null?void 0:n.useOriginalAsset)===t)return;const i={...n,useOriginalAsset:t},s=t?n==null?void 0:n.originalAssetKey:n==null?void 0:n.backgroundRemovedAssetKey,o=[a.setAspect(this.property.name,s||"",i)];if(t)o.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};o.push(l())}o.push(this.loadImageData()),await Promise.all(o),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await U.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const i=new Map(n.colors.map(s=>[s.key,{browserValue:s.browserValue,pmsValue:s.pmsValue}])??[]);this.getSharedSteps(t).forEach(s=>{s.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorPickerEnabled?((n=(a=this.colorOption)==null?void 0:a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})))??[]:[]}getCurrentColors(){var t;return(t=this.imageData)==null?void 0:t.colors}isColorPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.colorPickerEnabled)??!1}isPmsPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.pmsPickerEnabled)??!1}async getOriginalColors(){var e;return(e=this.imageData)!=null&&e.svg?(await ot(this.imageData.svg)).colors:void 0}async changeColors(t){var i;if(!((i=this.imageData)!=null&&i.svg))return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(s=>{s.changeColors(a)});const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([s,o])=>({key:s,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const s=this.getSharedSteps(e).map(o=>{const l=o;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(s)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{var s;if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;((s=n.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name}))&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Qr extends Ge{constructor(t,e){super(t,e)}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(n)}}class za extends Ge{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){var e,a;const t=(a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.find(n=>{var i,s;return n.id===((s=(i=this.optionResource)==null?void 0:i.defaultVariant)==null?void 0:s.id)});t&&await this.selectVariant(new it(t))}getCurrentVariant(){var e,a;if(!this.optionResource)return;const t=this.getStateValue();if(t){const n=(a=this.optionResource.variants)==null?void 0:a.find(i=>i.id===t);return n?new it(n):void 0}else{const n=(e=this.optionResource.variants)==null?void 0:e.find(i=>{var s,o;return i.id===((o=(s=this.optionResource)==null?void 0:s.defaultVariant)==null?void 0:o.id)});return n?new it(n):void 0}}getAvailableVariants(){var e,a;return(((a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.filter(n=>n.enabled))||[]).map(n=>new it(n))}getAllVariants(){var e;return(((e=this.optionResource)==null?void 0:e.variants)||[]).map(a=>new it(a))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){var n,i;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(i=(n=this.optionResource)==null?void 0:n.variants)==null?void 0:i.find(s=>s.id===e);return a?this.applyVariantSelection(new it(a),t):Promise.resolve()}async applyVariantSelection(t,e){const n=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(n)}}class Ca extends za{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyColorVariant(t,void 0,e)])}async applyGlobalState(t){var i,s,o;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(s=(i=this.optionResource)==null?void 0:i.variants)==null?void 0:s.find(l=>l.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new it(a),t);const n=(o=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:o.customColor;n&&this.setCustomColor(n)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(s=>{switch(s.getType()){case I.Shape:return s.selectVariant(t);case I.Text:return s.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case I.Illustration:return s.setColor((a==null?void 0:a.toString())||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){var t,e;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.customColor)||((e=this.getCurrentVariant())==null?void 0:e.getColor())||"#ffffff"}}const tc=(r,t,e,a)=>r.flatMap(n=>n.getSteps()).filter(n=>n.getGlobalPropertyAspects(t).includes(e)&&n.getType()===a),ec=(r,t,e)=>{const n=tc(r,t,e,I.Illustration).map(i=>{var l;const s=(l=i.getCurrentVariant())==null?void 0:l.getAssetResource(),o=i.getColors();return!(s!=null&&s.assetConfiguration)||!o?0:Object.getOwnPropertyNames(o).length});return Math.max(...n)};class ac{constructor(t,e,a,n,i){this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const s=i==null?void 0:i.existingGlobalPropertyState;this.initPromise=s?Promise.resolve(s).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=s}):this.createGlobalPropertyState().then(o=>{console.log("Setting global property state to new state."),this.globalPropertyState=o}),this.onGlobalPropertyStateChange=n}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=Et(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){var a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e))==null?void 0:a.storage}async setAspect(t,e,a,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);const s=Et(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(l=>l.name===t);if(o.length>0)if(n){const l=o.find(c=>c.channel===n);if(l)l.value=e,l.type=i.type,l.channel=n,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(n===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n})}}else{const l=o[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(s,this.globalPropertyState)}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(o=>o.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=Et(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(o=>o.name===t);if(s.length>0)if(a){const o=s.find(l=>l.channel===a);o&&(o.storage=e!==null?e:void 0,o.type=n.type)}else{const o=s[0];o.storage=e!==null?e:void 0,o.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async updateGlobalPropertyState(){var e,a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await B.getShadowGraphqlClient().mutate({mutation:Wo,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(n=>{let i=n.type&&n.storage?{}:void 0;if(i)switch(n.type){case V.FileUpload:{i.fileUpload=n.storage;break}case V.Option:{i.option=n.storage;break}case V.ColorOption:{i=n.storage;break}}return{name:n.name,value:n.value,type:n.type,storage:i,channel:n.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((a=t.data)!=null&&a.globalPropertyStateUpdate)this.globalPropertyState=t.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){var e,a;const t=await B.getShadowGraphqlClient().mutate({mutation:qo,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((a=t.data)!=null&&a.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class nc{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){var s;if(!this.state||!((s=t==null?void 0:t.getWorkflowManager())!=null&&s.getModelContainer()))return;const e=this.state.transactions.find(o=>o.transactionId===t.getWorkflowManager().getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const n=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=n.position,i.rotation=n.rotation,i.scale=n.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(s=>s.transactionId===n);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:n,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){var l,c;if(!((l=t==null?void 0:t.getWorkflowManager())!=null&&l.getModelContainer())||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,n=this.state.transactions.find(d=>d.transactionId===a),i=(c=n==null?void 0:n.transforms)==null?void 0:c[e];if(!i)return;const s=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),o=t.getWorkflowManager().getModelContainer();o.position=s.position,o.rotation=s.rotation,o.scale=s.scale,n.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const rc=v.gql`
2281
+ `)},f))}else n.push(new q(C,f))}return n},Wl=(r,t)=>r.conditions?r.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const n=a.selectedVariants;return e.requiredVariantSelections.some(i=>n.find(s=>s.id===i)!==void 0)}return!1}):!0,Tr=async(r,t,e,a)=>{const n=[],i={};for(const s of r){const o=t.steps.find(l=>l.stepName===s.name);if(o)switch(o.type){case I.DigitalContent:n.push(...await Ol(e,s,o));break;case I.Frame:case I.Photo:n.push(...await $l(e,i,s,o));break;case I.Illustration:n.push(...await Ul(e,i,s,o));break;case I.Module:n.push(...await Ll(e,s,o));break;case I.Picture:n.push(...await Vl(e,i,s,o));break;case I.Shape:n.push(...await zl(e,i,s,o));break;case I.Text:n.push(...await ql(e,i,s,o));break}}for(const s of t.steps)s.type!==I.SilentIllustration&&s.type!==I.ProductOverlay||Wl(s,i)&&n.push(...await Gl(e,s,a));return n};class jl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Jl(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Hl=()=>new Promise((r,t)=>{try{const a=pt().getContext("webgl2");r(!!a)}catch{r(!1)}}),Yl=Hl();class Jl{constructor(t,e,a,n,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Da(2),this.id=t,this.name=e,this.service=a,this.panelSize=n,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=Et(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new Kl(this.getID(),a,await Yl,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class Kl extends Pa{constructor(t,e,a,n,i,s){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=n,this.layouts=i,this.getWorkflowManager=s}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,n=e/t.height,i=Math.min(a,n);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){var h,g;const t=this.layouts.find(m=>m.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,n=t.layoutState.layout.height,i=a===1||n===1?{width:1,height:1}:this.getDynamicTextureResolution(),s=i.width,o=i.height;let l,c;if(this.nonPOTSupport){const m=s/o;a/n<m?(l=s,c=n*(s/a)):(l=a*(o/n),c=o);const f=this.resizeFit({width:l,height:c});l=f.width,c=f.height}else l=i.width,c=i.height;const d=ze(t.layoutState.layout,e,{renderingConfiguration:{purpose:Tt.ThreeD,templatingContext:(g=(h=this.getWorkflowManager)==null?void 0:h.call(this))==null?void 0:g.getTemplatingContext()}}),A=Tn(d),u=await Sa.Pith.from(this.ctx,A,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:pt,createImage:oe,DOMParser:ba(),fetch});u.resize(l,c),await u.render(),this.onRender()}}const _l=(r,t)=>{const e=[];return r.forEach(a=>{const n=t.steps.find(i=>i.stepName===a.stepName);(n==null?void 0:n.type)===I.Text&&a.stepAspectType==="Text"&&e.push({name:n.stepName,data:{text:a.value}})}),e},Xl=async(r,t,e,a)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};n=new $(e.map(l=>new Na(l))).apply(n);const s=await Tr(r,t,e,a);return new $(s).apply(n)};class Zl{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){var e;if(!((e=this.bundle.getProductCollection())!=null&&e.getResource().globalPropertyConfiguration))return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(a=>this.getHandle(a)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const n=e.aspects.find(i=>i.name===a.targetAspectName);return n?a.requiredVariantSelections.some(i=>i===n.value):!1})}async createHandle(t){switch(t.type){case V.FileUpload:return new Nr(this.bundle,t).initialize();case V.ColorOption:return new Ca(this.bundle,t,t.entityId?await H.getOption(t.entityId):void 0);case V.Option:{const e=t.entityId?await H.getOption(t.entityId):void 0;return(e==null?void 0:e.type)==="Color"?new Ca(this.bundle,t,e):new za(this.bundle,t,e)}case V.Text:return new Qr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Ge{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(n=>n.getStepsConditionallyActive().filter(i=>{var s;return i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:(s=i.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name})}))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Nr extends Ge{constructor(t,e){super(t,e)}async initialize(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorOptionId&&(this.colorOption=await H.getOption((n=(a=this.property.data)==null?void 0:a.fileUpload)==null?void 0:n.colorOptionId)),await this.loadImageData(),this}async loadImageData(){var e;const t=await this.getImage();if(t!=null&&t.fileLink)if(t!=null&&t.fileLink.endsWith(".svg")){const a=await et(t==null?void 0:t.fileLink),n=await Ma(t==null?void 0:t.fileLink),i=n.width,s=n.height,o=await ot(a),l=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);(e=l==null?void 0:l.colors)==null||e.forEach(d=>{o.colors[d.key]={browserValue:d.browserValue,pmsValue:d.pmsValue}});const c={src:t==null?void 0:t.fileLink,width:i,height:s,aspect:i/s,svg:o.svg,colors:o.colors};dt.set(t==null?void 0:t.fileLink,c),this.imageData=c}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Me.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await U.removeBackgroundFromAsset(e),s={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,s):a.setAspectStorage(this.property.name,s)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return U.getLocalOrFromServer(t)}async getImageWithColors(){var t,e;return await this.loadImageData(),(t=this.imageData)!=null&&t.svg?Oe(Ue(this.imageData.svg,this.imageData.colors??{},!1)):(e=this.imageData)==null?void 0:e.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.originalAssetKey)return U.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.backgroundRemovedAssetKey)return U.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){var t;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.useOriginalAsset)??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if((n==null?void 0:n.useOriginalAsset)===t)return;const i={...n,useOriginalAsset:t},s=t?n==null?void 0:n.originalAssetKey:n==null?void 0:n.backgroundRemovedAssetKey,o=[a.setAspect(this.property.name,s||"",i)];if(t)o.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};o.push(l())}o.push(this.loadImageData()),await Promise.all(o),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await U.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const i=new Map(n.colors.map(s=>[s.key,{browserValue:s.browserValue,pmsValue:s.pmsValue}])??[]);this.getSharedSteps(t).forEach(s=>{s.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorPickerEnabled?((n=(a=this.colorOption)==null?void 0:a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})))??[]:[]}getCurrentColors(){var t;return(t=this.imageData)==null?void 0:t.colors}isColorPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.colorPickerEnabled)??!1}isPmsPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.pmsPickerEnabled)??!1}async getOriginalColors(){var e;return(e=this.imageData)!=null&&e.svg?(await ot(this.imageData.svg)).colors:void 0}async changeColors(t){var i;if(!((i=this.imageData)!=null&&i.svg))return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(s=>{s.changeColors(a)});const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([s,o])=>({key:s,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const s=this.getSharedSteps(e).map(o=>{const l=o;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(s)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{var s;if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;((s=n.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name}))&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Qr extends Ge{constructor(t,e){super(t,e)}isTemplatingEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.text)==null?void 0:e.templatingEnabled)||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(n)}}class za extends Ge{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){var e,a;const t=(a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.find(n=>{var i,s;return n.id===((s=(i=this.optionResource)==null?void 0:i.defaultVariant)==null?void 0:s.id)});t&&await this.selectVariant(new it(t))}getCurrentVariant(){var e,a;if(!this.optionResource)return;const t=this.getStateValue();if(t){const n=(a=this.optionResource.variants)==null?void 0:a.find(i=>i.id===t);return n?new it(n):void 0}else{const n=(e=this.optionResource.variants)==null?void 0:e.find(i=>{var s,o;return i.id===((o=(s=this.optionResource)==null?void 0:s.defaultVariant)==null?void 0:o.id)});return n?new it(n):void 0}}getAvailableVariants(){var e,a;return(((a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.filter(n=>n.enabled))||[]).map(n=>new it(n))}getAllVariants(){var e;return(((e=this.optionResource)==null?void 0:e.variants)||[]).map(a=>new it(a))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){var n,i;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(i=(n=this.optionResource)==null?void 0:n.variants)==null?void 0:i.find(s=>s.id===e);return a?this.applyVariantSelection(new it(a),t):Promise.resolve()}async applyVariantSelection(t,e){const n=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(n)}}class Ca extends za{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyColorVariant(t,void 0,e)])}async applyGlobalState(t){var i,s,o;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(s=(i=this.optionResource)==null?void 0:i.variants)==null?void 0:s.find(l=>l.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new it(a),t);const n=(o=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:o.customColor;n&&this.setCustomColor(n)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(s=>{switch(s.getType()){case I.Shape:return s.selectVariant(t);case I.Text:return s.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case I.Illustration:return s.setColor((a==null?void 0:a.toString())||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){var t,e;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.customColor)||((e=this.getCurrentVariant())==null?void 0:e.getColor())||"#ffffff"}}const tc=(r,t,e,a)=>r.flatMap(n=>n.getSteps()).filter(n=>n.getGlobalPropertyAspects(t).includes(e)&&n.getType()===a),ec=(r,t,e)=>{const n=tc(r,t,e,I.Illustration).map(i=>{var l;const s=(l=i.getCurrentVariant())==null?void 0:l.getAssetResource(),o=i.getColors();return!(s!=null&&s.assetConfiguration)||!o?0:Object.getOwnPropertyNames(o).length});return Math.max(...n)};class ac{constructor(t,e,a,n,i){this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const s=i==null?void 0:i.existingGlobalPropertyState;this.initPromise=s?Promise.resolve(s).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=s}):this.createGlobalPropertyState().then(o=>{console.log("Setting global property state to new state."),this.globalPropertyState=o}),this.onGlobalPropertyStateChange=n}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=Et(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){var a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e))==null?void 0:a.storage}async setAspect(t,e,a,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);const s=Et(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(l=>l.name===t);if(o.length>0)if(n){const l=o.find(c=>c.channel===n);if(l)l.value=e,l.type=i.type,l.channel=n,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(n===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n})}}else{const l=o[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(s,this.globalPropertyState)}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(o=>o.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=Et(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(o=>o.name===t);if(s.length>0)if(a){const o=s.find(l=>l.channel===a);o&&(o.storage=e!==null?e:void 0,o.type=n.type)}else{const o=s[0];o.storage=e!==null?e:void 0,o.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async updateGlobalPropertyState(){var e,a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await B.getShadowGraphqlClient().mutate({mutation:Wo,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(n=>{let i=n.type&&n.storage?{}:void 0;if(i)switch(n.type){case V.FileUpload:{i.fileUpload=n.storage;break}case V.Option:{i.option=n.storage;break}case V.ColorOption:{i=n.storage;break}}return{name:n.name,value:n.value,type:n.type,storage:i,channel:n.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((a=t.data)!=null&&a.globalPropertyStateUpdate)this.globalPropertyState=t.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){var e,a;const t=await B.getShadowGraphqlClient().mutate({mutation:qo,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((a=t.data)!=null&&a.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class nc{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){var s;if(!this.state||!((s=t==null?void 0:t.getWorkflowManager())!=null&&s.getModelContainer()))return;const e=this.state.transactions.find(o=>o.transactionId===t.getWorkflowManager().getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const n=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=n.position,i.rotation=n.rotation,i.scale=n.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(s=>s.transactionId===n);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:n,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){var l,c;if(!((l=t==null?void 0:t.getWorkflowManager())!=null&&l.getModelContainer())||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,n=this.state.transactions.find(d=>d.transactionId===a),i=(c=n==null?void 0:n.transforms)==null?void 0:c[e];if(!i)return;const s=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),o=t.getWorkflowManager().getModelContainer();o.position=s.position,o.rotation=s.rotation,o.scale=s.scale,n.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const rc=v.gql`
2279
2282
  query GetManyMetafields($entityIds: [String!]!) {
2280
2283
  metafieldsMany(entityIds: $entityIds) {
2281
2284
  id
@@ -2451,7 +2454,7 @@
2451
2454
  }
2452
2455
  }
2453
2456
  }
2454
- `;class Cc{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 wc{init(t,e,a){this.cognitoClient=new pe.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 pe.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 i;const n=await((i=this.cognitoClient)==null?void 0:i.send(new pe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}})));return(n==null?void 0:n.ChallengeName)==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}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 pe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}})))}}const Wt=new wc;class Gr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Ai(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ka.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t,a=Ka.code(e);if((a==null?void 0:a.code)==="CLP")return"USD0,0"}}const un=new Gr;class qr{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,un.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,un.getPrecisionForCurrency(e))}}const yc=async(r,t)=>{var n;const e=await B.getShadowGraphqlClient().query({query:Es(((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},Sc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},ja=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=yc(a,t),i=a.map(o=>Ot.set({id:o,options:t},Sc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},vc=async(r,t)=>(await ja([r],t))[0],Ec=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})),bc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):Ec(t.panels)};class Bc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return B.getShadowGraphqlClient().mutate({...e,mutation:As})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Di(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 29.1.2"),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&&Rn(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(!xi())throw new Error("Application key required to use Flow Service.");return new Lr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await B.getShadowGraphqlClient().query({query:ks,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:s,rateTo:o}=i.data.currencyConversion;return new qr(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=Wr(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:bs,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:Bs,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:Se,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:Se,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:mc,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:Se,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:pc,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:Se,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:fc,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:tl(((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 ea(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:Jo(((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 ea(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:el(((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 ea(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:hl(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:Ko,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:ds,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:cs,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=Ja(o,10),d=Ja(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(y=>y.workflowId))],h=await ja(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 Cc({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 or(tt),R.reloadedState=tt}else R.layouts=bc(R.transaction,R.workflow);return R.renderableContextService=new jl(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 Mr(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:ms(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 wa(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await B.getShadowGraphqlClient().query({query:ps(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 wa(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:gs,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:Fs,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 Wr=async(r,t)=>(await B.getShadowGraphqlClient().query({query:Ps,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,Ic=async r=>{const e=await B.getShadowGraphqlClient().query({query:hs,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Pc=async(r,t)=>{var a;return(a=(await B.getShadowGraphqlClient().query({query:Is,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},Dc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:xs,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},xc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Ds,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function jr(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=ve(r.x,t.width-c,0),o.y=ve(r.y,t.height-d,0),o}const s=r;return s.x=ve(s.x,-n,t.width),s.y=ve(s.y,-i,t.height),s}function ve(r,t,e){return Math.min(Math.max(r,t),e)}class Hr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=En(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 ue(o),c=this.frameData?this.frameData[s]:void 0;vn(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=Ue(this.imageData.svg,this.imageData.colors||{},!1);return Oe(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]=jr(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 po(o,e,t[l]),new fo(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]=ka(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Fc{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 Yr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(Yr||{});class Jr extends rt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Hr(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(Me.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 kc=v.gql`
2457
+ `;class Cc{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 wc{init(t,e,a){this.cognitoClient=new pe.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 pe.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 i;const n=await((i=this.cognitoClient)==null?void 0:i.send(new pe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}})));return(n==null?void 0:n.ChallengeName)==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}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 pe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}})))}}const Wt=new wc;class Gr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Ai(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ka.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t,a=Ka.code(e);if((a==null?void 0:a.code)==="CLP")return"USD0,0"}}const un=new Gr;class qr{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,un.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,un.getPrecisionForCurrency(e))}}const yc=async(r,t)=>{var n;const e=await B.getShadowGraphqlClient().query({query:Es(((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},Sc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},ja=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=yc(a,t),i=a.map(o=>Ot.set({id:o,options:t},Sc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},vc=async(r,t)=>(await ja([r],t))[0],Ec=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})),bc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):Ec(t.panels)};class Bc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return B.getShadowGraphqlClient().mutate({...e,mutation:As})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Di(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 29.2.0"),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&&Rn(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(!xi())throw new Error("Application key required to use Flow Service.");return new Lr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await B.getShadowGraphqlClient().query({query:ks,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:s,rateTo:o}=i.data.currencyConversion;return new qr(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=Wr(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:bs,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:Bs,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:Se,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:Se,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:mc,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:Se,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:pc,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:Se,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:fc,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:tl(((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 ea(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:Jo(((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 ea(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:el(((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 ea(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:hl(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:Ko,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:ds,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:cs,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=Ja(o,10),d=Ja(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(y=>y.workflowId))],h=await ja(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 Cc({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 or(tt),R.reloadedState=tt}else R.layouts=bc(R.transaction,R.workflow);return R.renderableContextService=new jl(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 Mr(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:ms(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 wa(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await B.getShadowGraphqlClient().query({query:ps(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 wa(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:gs,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:Fs,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 Wr=async(r,t)=>(await B.getShadowGraphqlClient().query({query:Ps,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,Ic=async r=>{const e=await B.getShadowGraphqlClient().query({query:hs,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Pc=async(r,t)=>{var a;return(a=(await B.getShadowGraphqlClient().query({query:Is,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},Dc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:xs,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},xc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Ds,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function jr(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=ve(r.x,t.width-c,0),o.y=ve(r.y,t.height-d,0),o}const s=r;return s.x=ve(s.x,-n,t.width),s.y=ve(s.y,-i,t.height),s}function ve(r,t,e){return Math.min(Math.max(r,t),e)}class Hr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=En(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 ue(o),c=this.frameData?this.frameData[s]:void 0;vn(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=Ue(this.imageData.svg,this.imageData.colors||{},!1);return Oe(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]=jr(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 po(o,e,t[l]),new fo(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]=ka(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Fc{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 Yr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(Yr||{});class Jr extends rt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Hr(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(Me.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 kc=v.gql`
2455
2458
  query GetLoggedInCustomer($email: String!) {
2456
2459
  customer(emailAddress: $email) {
2457
2460
  id