@spiffcommerce/core 26.1.1 → 26.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +3 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
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
|
+
## [26.1.2] - 30-10-2024
|
|
18
|
+
|
|
19
|
+
### Fixed
|
|
20
|
+
|
|
21
|
+
- The ProductCollection class will no longer request the products it contains if they are already present in the cache.
|
|
22
|
+
|
|
17
23
|
## [26.1.1] - 30-10-2024
|
|
18
24
|
|
|
19
25
|
### Changed
|
package/dist/index.js
CHANGED
|
@@ -3223,7 +3223,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
|
|
|
3223
3223
|
/>
|
|
3224
3224
|
</svg>
|
|
3225
3225
|
`,h={"spiff-fill-shape":{browserValue:s.color||"#000000"}},C=R();return new O({colors:h,id:C,svg:d,type:k.Illustration,y:l.top,x:l.left,rotation:l.rotation,width:l.width,height:l.height,layer:l.layer,layerIndex:l.layerIndex,immutable:l.immutable},g)},r=A.data.regions;try{return r.map(o)}catch(l){return console.error(l),[]}},ar=async(n,t,e)=>{const A=[],i=(()=>{var c,l;return t.type===M.ProductOverlay?e||((c=t.data.asset)==null?void 0:c.fileLink)||"":((l=t.data.asset)==null?void 0:l.fileLink)||""})(),o=(()=>i.endsWith(".jpeg")||i.endsWith(".jpg")||i.endsWith(".png")?k.Image:(i.endsWith(".svg"),k.Illustration))(),r=t.data.regions;if(o==="image")try{r.forEach(c=>{const l=n.find(d=>d.panelId===c.panelId);if(!l)throw new W(c);const g={id:R(),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===M.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:c.rotation,excludeFromExport:t.data.excludeFromPrint,preserveAspectRatio:"none"};A.push(new O(g,l))})}catch(c){console.error(c)}else{const c=await _(i,!0),l=g=>{const d=/<svg.*?<\/svg>/s,B=g.match(d)||[],h=(B==null?void 0:B.length)>0?B[0]:"",u=wt().parseFromString(h,"image/svg+xml").firstElementChild;if(!u)throw new It("Failed to read SVG.");return Me(u),$t().serializeToString(u)};r.forEach(g=>{const d=n.find(h=>h.panelId===g.panelId);if(!d)throw new W(g);const B={id:R(),src:i,asset_key:i,svg:l(c),colors:{},type:o,y:g.top,x:g.left,width:g.width,height:g.height,layer:g.layer,layerIndex:g.layerIndex,scaleX:1,scaleY:1,rotation:g.rotation,productOverlay:t.type===M.ProductOverlay?!0:void 0,excludeFromExport:t.data.excludeFromPrint};A.push(new O(B,d))})}return A},nr=async(n,t,e,A)=>{const a=[],i=e.data,s=30,o=w=>w.vertical?"center":w.textAlign||"center",r=()=>{var m;const w=A.option;if(!w)return;const u=((m=w.variants)==null?void 0:m.find(f=>f.id===i.fontVariantId))||ae(w);if(!u||!u.asset)return;t[A.stepName]={selectedVariants:[u]};const E=u.asset.fileLink;if(E)return E},l=await(async()=>{const w=r();if(!w)return;const u=await kt(w);return{assetUrl:w,name:u.names.fullName.en}})(),g=(A.data.replaceableText?A.data.replaceableText.replace("{{}}",i.text):i.text)||"",d=we(g,{vertical:A.data.vertical,uppercase:A.data.uppercase}),B=async w=>{const u=w.colorOption;if(!u)return;const E=$.getDefaultVariant(u);return E==null?void 0:E.color},h=i.color||await B(A.data),C=A.data.regions;for(const w of C){const u=n.find(m=>m.panelId===w.panelId);if(!u)continue;const E={stepName:e.name,id:R(),align:o(A.data),curved:A.data.curved,fill:i.color||h||"#000000",fontData:l,fontSize:A.data.size||s,height:w.height,layer:w.layer,layerIndex:w.layerIndex,paths:A.data.paths,rotation:w.rotation,text:d,type:k.Textbox,vertical:A.data.vertical,verticalAlign:A.data.verticalAlign||"middle",width:w.width,x:w.left,y:w.top};if(l){const[m,f]=Ot(A.data.size||s,l,w,[we(d,{vertical:A.data.vertical,uppercase:A.data.uppercase})],{size:A.data.size,minSize:A.data.minSize,maxSize:A.data.maxSize});a.push(new O({...E,fontSize:m,text:E.curved?E.text:(f||[]).join(`
|
|
3226
|
-
`)},u))}else a.push(new O(E,u))}return a},ir=(n,t)=>n.conditions?n.conditions.every(e=>{const A=t[e.targetStepName];if(A&&A.selectedVariants){const a=A.selectedVariants;return e.requiredVariantSelections.some(i=>a.find(s=>s.id===i)!==void 0)}return!1}):!0,In=async(n,t,e,A)=>{const a=[],i={};for(const s of n){const o=t.steps.find(r=>r.stepName===s.name);if(o)switch(o.type){case M.DigitalContent:a.push(...await Zo(e,s,o));break;case M.Frame:case M.Photo:a.push(...await $o(e,i,s,o));break;case M.Illustration:a.push(...await _o(e,i,s,o));break;case M.Module:a.push(...await tr(e,s,o));break;case M.Picture:a.push(...await er(e,i,s,o));break;case M.Shape:a.push(...await Ar(e,i,s,o));break;case M.Text:a.push(...await nr(e,i,s,o));break}}for(const s of t.steps)s.type!==M.SilentIllustration&&s.type!==M.ProductOverlay||ir(s,i)&&a.push(...await ar(e,s,A));return a};class sr{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(A=>e.set(A.id,new cr(A.id,A.name,this,{width:A.width,height:A.height}))),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}}const or=()=>new Promise((n,t)=>{try{const A=Bt().getContext("webgl2");n(!!A)}catch{n(!1)}}),rr=or();class cr{constructor(t,e,A,a){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new CA(2),this.id=t,this.name=e,this.service=A,this.panelSize=a}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=Mt(t);this.lastRequestedRenderArguments=e;const A=this.getStaticContext();if(!A){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new lr(this.getID(),A,await rr,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e))}}class lr extends hA{constructor(t,e,A,a,i){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=A,this.onRender=a,this.layouts=i}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,a=e/t.height,i=Math.min(A,a);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){const t=this.layouts.find(B=>B.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],A=t.layoutState.layout.width,a=t.layoutState.layout.height,i=A===1||a===1?{width:1,height:1}:this.getDynamicTextureResolution(),s=i.width,o=i.height;let r,c;if(this.nonPOTSupport){const B=s/o;A/a<B?(r=s,c=a*(s/A)):(r=A*(o/a),c=o);const C=this.resizeFit({width:r,height:c});r=C.width,c=C.height}else r=i.width,c=i.height;const l=Se(t.layoutState.layout,e,{renderingConfiguration:{purpose:xt.ThreeD}}),g=Ca(l),d=await oA.Pith.from(this.ctx,g,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:Bt,createImage:te,DOMParser:dA(),fetch});d.resize(r,c),await d.render(),this.onRender()}}const gr=(n,t)=>{const e=[];return n.forEach(A=>{const a=t.steps.find(i=>i.stepName===A.stepName);(a==null?void 0:a.type)===M.Text&&A.stepAspectType==="Text"&&e.push({name:a.stepName,data:{text:A.value}})}),e},dr=async(n,t,e,A)=>{let a={serializableWorkflow:{steps:[]},layouts:{}};a=new U(e.map(r=>new pA(r))).apply(a);const s=await In(n,t,e,A);return new U(s).apply(a)};class Br{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[];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 a=e.aspects.find(i=>i.name===A.targetAspectName);return a?A.requiredVariantSelections.some(i=>i===a.value):!1})}async createHandle(t){switch(t.type){case nt.FileUpload:return new Fn(this.bundle,t);case nt.ColorOption:return new iA(this.bundle,t,t.entityId?await $.getOption(t.entityId):void 0);case nt.Option:{const e=t.entityId?await $.getOption(t.entityId):void 0;return(e==null?void 0:e.type)==="Color"?new iA(this.bundle,t,e):new NA(this.bundle,t,e)}case nt.Text:return new yn(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Pe{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(a=>a.getStepsConditionallyActive().filter(i=>{var s;return i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:(s=i.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var r,c;return o.globalPropertyConfigurationId===((c=(r=this.bundle.getProductCollection())==null?void 0:r.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name})}))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Fn extends Pe{constructor(t,e){super(t,e)}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)])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(fe.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(),a=await G.removeBackgroundFromAsset(e),s={...A.getAspectStorage(this.property.name),backgroundRemovedAssetKey:a.key,useOriginalAsset:!t},r=[t?A.setAspect(this.property.name,a.key,s):A.setAspectStorage(this.property.name,s)];return t&&r.push(this.applyImageSelection(a,void 0,!1,!1)),await Promise.all(r),this.updateSharedStepStorage(s),a}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return G.getLocalOrFromServer(t)}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.originalAssetKey)return G.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.backgroundRemovedAssetKey)return G.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(),a=A.getAspectStorage(this.property.name);if((a==null?void 0:a.useOriginalAsset)===t)return;const i={...a,useOriginalAsset:t},s=t?a==null?void 0:a.originalAssetKey:a==null?void 0:a.backgroundRemovedAssetKey,o=[A.setAspect(this.property.name,s||"",i)];if(t)o.push(this.applyImageSelection(e,void 0,!1,!1));else{const r=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(r())}this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const A=await G.getLocalOrFromServer(e);if(!A)return;const a=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await this.applyImageSelection(A,t,!1,!0),a?this.updateSharedStepStorage({...a}):(this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e}))}async applyImageSelection(t,e,A=!0,a=!0){const s=this.getSharedSteps(e).map(o=>{const r=o;if(r.getFrameService())return r.selectImage(t,A,a)});await Promise.all(s)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(A=>A.getSteps().forEach(a=>{var s;if(a.getOverrideGlobalPropertyConfiguration(this.property.type))return;((s=a.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var r,c;return o.globalPropertyConfigurationId===((c=(r=this.bundle.getProductCollection())==null?void 0:r.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name}))&&A.getWorkflowManager().updateStorage(a.getId(),{framePatternData:t})}))}}class yn extends Pe{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 a=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(a)}}class NA extends Pe{constructor(t,e,A){super(t,e),this.optionResource=A}getCurrentVariant(){var e,A;if(!this.optionResource)return;const t=this.getStateValue();if(t){const a=(A=this.optionResource.variants)==null?void 0:A.find(i=>i.id===t);return a?new at(a):void 0}else{const a=(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 a?new at(a):void 0}}getAvailableVariants(){var e,A;return(((A=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:A.filter(a=>a.enabled))||[]).map(a=>new at(a))}getAllVariants(){var e;return(((e=this.optionResource)==null?void 0:e.variants)||[]).map(A=>new at(A))}async selectVariant(t){console.log(`Selecting variant ${t.getId()}`),await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId()),this.applyVariantSelection(t)])}async applyGlobalState(t){var a,i;const e=this.getStateValue();if(!e)return Promise.resolve();const A=(i=(a=this.optionResource)==null?void 0:a.variants)==null?void 0:i.find(s=>s.id===e);return A?(console.log(`Applying global state using variant ${A.id} for aspect ${e}`),this.applyVariantSelection(new at(A),t)):Promise.resolve()}async applyVariantSelection(t,e){const a=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(a)}}class iA extends NA{constructor(t,e,A){super(t,e,A)}async selectVariant(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId()),this.applyColorVariant(t)])}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(r=>r.id===e);if(!A)return Promise.resolve();await this.applyColorVariant(new at(A),t);const a=(o=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:o.customColor;a&&this.setCustomColor(a)}async applyColorVariant(t,e){const a=this.getSharedSteps(e).map(i=>{switch(i.getType()){case M.Shape:return i.selectVariant(t);case M.Text:return i.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()})}});await Promise.all(a)}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"}}class hr{constructor(t,e,A,a,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(()=>{this.globalPropertyState=s}):this.createGlobalPropertyState().then(o=>{this.globalPropertyState=o}),this.onGlobalPropertyStateChange=a}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=Mt(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find(A=>A.name===t);if(e)return e.value}getAspectStorage(t){var e;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(e=this.globalPropertyState.aspects.find(A=>A.name===t))==null?void 0:e.storage}async setAspect(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 a=this.configuration.aspects.find(o=>o.name===t);if(!a)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=Mt(this.globalPropertyState),s=this.globalPropertyState.aspects.find(o=>o.name===t);s?(s.value=e,s.type=a.type,A!==void 0&&(s.storage=A!==null?A:void 0)):this.globalPropertyState.aspects.push({name:t,value:e,type:a.type,storage:A!==null?A:void 0}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async setAspectStorage(t,e){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 A=this.configuration.aspects.find(s=>s.name===t);if(!A)throw new Error(`Failed to find configuration aspect with name: ${t}`);const a=Mt(this.globalPropertyState),i=this.globalPropertyState.aspects.find(s=>s.name===t);i?(i.storage=e!==null?e:void 0,i.type=A.type):this.globalPropertyState.aspects.push({name:t,value:"",type:A.type,storage:e!==null?e:void 0}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(a,this.globalPropertyState)}async updateGlobalPropertyState(){var e,A;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await F.getShadowGraphqlClient().mutate({mutation:wo,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(a=>{let i=a.type&&a.storage?{}:void 0;if(i)switch(a.type){case nt.FileUpload:{i.fileUpload=a.storage;break}case nt.Option:{i.option=a.storage;break}case nt.ColorOption:{i=a.storage;break}}return{name:a.name,value:a.value,type:a.type,storage:i}})},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 F.getShadowGraphqlClient().mutate({mutation:Co,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 Cr{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 a=this.flipTransform(A,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=a.position,i.rotation=a.rotation,i.scale=a.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,A){const a=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(s=>s.transactionId===a);i?(i.transforms||(i.transforms={}),i.transforms[e]=A):this.state.transactions.push({transactionId:a,activeTransform:e,transforms:{[e]:A}})}activateWorkflowExperienceTransform(t,e){var r,c;if(!((r=t==null?void 0:t.getWorkflowManager())!=null&&r.getModelContainer())||!this.state)return;const A=t.getWorkflowManager().getTransaction().id,a=this.state.transactions.find(l=>l.transactionId===A),i=(c=a==null?void 0:a.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,a.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 JSON.stringify(this.state)}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}}}class Mn{constructor(t){this.fullFetched=!1,this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getDescription(){return this.collection.description||""}getImage(){return this.collection.image}getProducts(){if(!this.collection.productCollectionProducts)throw new Error("Failed to find products on collection. Ensure you fetch them first!");return this.collection.productCollectionProducts.map(t=>new he(t))}async fetchProducts(t){if(this.fullFetched)return this.collection.productCollectionProducts.map(A=>new he(A));const e=await F.getShadowGraphqlClient().query({query:fo,variables:{id:this.getId(),productIds:t},errorPolicy:"all"});return t||(this.fullFetched=!0),this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.map(A=>new he(A))}async filterProducts(t){var i,s;const e=await F.getShadowGraphqlClient().query({query:Qo,errorPolicy:"all",variables:{id:this.getId(),filters:{link:"And",metafields:t}}});if(!((i=e.data)!=null&&i.productCollections)||((s=e.data)==null?void 0:s.productCollections.length)===0)throw new Error("Failed to filter product collection products.");const A=this.getProducts(),a=e.data.productCollections[0].productCollectionProducts.map(o=>o.product.id);return A.filter(o=>a.includes(o.getId()))}getTransformCollection(){if(this.collection.transformCollection)return new Sn(this.collection.transformCollection)}getResource(){return this.collection}}class he{constructor(t){this.product=t.product,this.productResource=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t,e){const a=(this.product.integrationProducts||[]).find(i=>{var c,l,g;const s=(c=i.integration)==null?void 0:c.type,o=((l=i.integration)==null?void 0:l.type)===t,r=e?((g=i.integration)==null?void 0:g.externalIntegrationId)===e:!0;return s&&o&&r});if(!a)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return a}getCurrentIntegration(){const e=(this.product.integrationProducts||[]).find(A=>{var a;return(a=A.integration)==null?void 0:a.isCurrent});if(!e)throw new Error(`Product: ${this.productResource.id} is not linked to this current integration. This is generally due to a configuration error.`);return e}getDefaultWorkflow(){const t=this.product.workflows;if(t===void 0)throw new ct("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(t.length===0)throw new ct("Called getDefaultWorkflow() but no workflows on requested product. Ensure at least 1 workflow is assigned to this product.");const e=this.productResource.workflowId;if(e){const A=t.find(a=>a.workflowName===e);if(A)return new St(A)}if(t.length===1)return console.warn("Called getDefaultWorkflow() but no default was configured. There is only one workflow available so we will fall back to using this!"),new St(t[0]);throw new ct("Called getDefaultWorkflow() but no default workflow is configured for the requested product. Multiple workflows exist so we can't assume!")}getAllWorkflows(){if((this.product.workflows||[]).length===0)throw new ct("No workflows on configured product. Ensure at least 1 workflow is assigned to this product.");return this.product.workflows.sort((e,A)=>(e.index??0)-(A.index??0)).map(e=>new St(e))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(t){var a,i,s,o;const e=this.product.basePrice||0;if(!t)return e;if(!t.integrationType&&!t.externalId&&!t.integrationId)throw new Error("You must provide at least one of the following fields on the includeAdditionalProduct object: integrationType, externalId, integrationId");let A;return t.integrationId?A=(a=this.product.integrationProducts)==null?void 0:a.find(r=>{var c;return((c=r.integration)==null?void 0:c.id)===t.integrationId}):t.externalId?A=(i=this.product.integrationProducts)==null?void 0:i.find(r=>{var c;return((c=r.integration)==null?void 0:c.externalIntegrationId)===t.externalId}):A=(s=this.product.integrationProducts)==null?void 0:s.find(r=>{var c;return((c=r.integration)==null?void 0:c.type)===t.integrationType}),(o=A==null?void 0:A.additionalIntegrationProduct)!=null&&o.product?e+(A.additionalIntegrationProduct.product.basePrice||0):e}}class St{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class Sn{constructor(t){this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(t=>new xn(t))}}class xn{constructor(t){this.transform=t}getId(){return this.transform.id}getName(){return this.transform.name}get(){return{position:this.transform.position,rotation:this.transform.rotation,scale:this.transform.scale}}}class Oe{constructor(t,e,A,a,i,s){var o,r,c;this.eventListeners=new Map,this.workflowExperiences=[],this.client=t,this.id=e.id,this.name=e.name||"",this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(((o=e.metadata)==null?void 0:o.map(l=>[l.key,l.value]))||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Cr(e.bundleStateData),this.globalPropertyStateManager=new hr(this.id,this.ownerId,(r=this.productCollection)==null?void 0:r.globalPropertyConfiguration,this.checkConditionalHandlesChanged.bind(this),s),this.globalPropertyHandleService=new Br(this),this.setPreviewService(A),this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(((c=e.transactions)==null?void 0:c.map(l=>l.id))||[],{...a,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]),this.initializationPromise.catch(l=>{console.error(`Bundle initialization failed: ${l}`)})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const A=this.eventListeners.get(t)||[],a=A.indexOf(e);a>-1&&A.splice(a,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){var t;return!!((t=this.productCollection)!=null&&t.globalPropertyConfiguration)}getGlobalPropertyConfiguration(){var t;return(t=this.productCollection)==null?void 0:t.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(A=>A.getType()===nt.Option).map(A=>{var a;return((a=A.getCurrentVariant())==null?void 0:a.getPrice())||0}).reduce((A,a)=>A+a,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new Mn(this.productCollection):void 0}async addWorkflowExperience(t){t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const A of e)await A.applyGlobalState([t])}async addWorkflowExperiences(t){const e=t.map(o=>o.getWorkflowManager().getTransaction().id),A=e.map(o=>this.workflowExperiences.find(r=>r.getWorkflowManager().getTransaction().id===o));if(A.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+A.filter(o=>!!o).map(o=>o==null?void 0:o.getWorkflowManager().getTransaction().id).join(", "));const a=N.getMap("transactionOwnerIds")||new Map,i=e.map(o=>a.get(o));await F.getShadowGraphqlClient().mutate({mutation:yo,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...t);const s=async()=>{for(const r of t)r.setBundle(this),await this.injectExperienceIntoPreviewService(r);await Promise.all(t.map(r=>r.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const r of o)await r.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),s()]),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges())}async appendWorkflowExperience(t,e=!0){const A=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===A))throw new Error("Unable to add transaction to bundle - Already Exists!");const s=(N.getMap("transactionOwnerIds")||new Map).get(A);await F.getShadowGraphqlClient().mutate({mutation:Fo,variables:{id:this.id,transactionId:A},context:{bundleOwnerId:this.ownerId,transactionOwnerId:s}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(A=>A.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,A=!0){if(t>-1){const a=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);a.setBundle(void 0),this.previewService&&a.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await F.getShadowGraphqlClient().mutate({mutation:Mo,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,s])=>({key:i,value:s})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),A&&(this.workflowExperiences.splice(t,1),this.workflowExperiences.forEach(i=>i.checkForPriceBreakChanges()),a.checkForPriceBreakChanges(),await this.updateTransactionOrder())}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(a=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===a.id));if(e.some(a=>a===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((a,i)=>e[i]===-1).map(a=>a.id).join(", "));const A=t.map(a=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===a.id),1)[0]);A.forEach(a=>a.setBundle(void 0)),[...this.workflowExperiences,...A].forEach(a=>a.checkForPriceBreakChanges()),this.previewService&&A.forEach(a=>a.getWorkflowManager().ejectFromPreviewService()),t.forEach(a=>this.bundleStateManager.removeStateForTransaction(a.id)),await F.getShadowGraphqlClient().mutate({mutation:So,variables:{id:this.id,transactionIds:t.map(a=>a.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,i])=>({key:a,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const A=await this.getGlobalProperties();await Promise.all(A.map(a=>a.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const A=this.workflowExperiences[t];if(A.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,A.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const a=await this.getGlobalProperties();await Promise.all(a.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const A=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=A,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){var i;const A=await F.getShadowGraphqlClient().mutate({mutation:xo,variables:{id:this.id,details:t,type:e||jt.Owner},context:{bundleOwnerId:this.ownerId}});if(!((i=A.data)!=null&&i.bundleAddStakeholder))throw new Error("Bundle not found!");const a=A.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async removeStakeholder(t){var A;if(!((A=(await F.getShadowGraphqlClient().mutate({mutation:Yo,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data)!=null&&A.bundleRemoveStakeholder))throw new Error("Bundle not found!")}async updateStakeholders(t){var a;const e=await F.getShadowGraphqlClient().mutate({mutation:Po,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!((a=e.data)!=null&&a.bundleUpdateStakeholders))throw new Error("Bundle not found!");const A=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(A)}async getAllStakeholders(){const t=await F.getShadowGraphqlClient().query({query:_A,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await F.getShadowGraphqlClient().query({query:_A,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){if(this.completed)return await F.getShadowGraphqlClient().mutate({mutation:Ro,variables:{bundleId:this.id}}),{bundleId:this.id,items:[],bundleOwnerId:this.ownerId};const A=await Vo(this.workflowExperiences.map(a=>({workflowManager:a.getWorkflowManager(),workflow:a.getWorkflowManager().getWorkflow(),layouts:a.getWorkflowManager().getLayouts(),getReducerState:()=>a.getCommandContext().getState(),product:a.getWorkflowManager().getProduct(),transaction:a.getWorkflowManager().getTransaction(),workflowSelections:a.getWorkflowManager().getWorkflowSelections(),designName:a.getWorkflowManager().getWorkflow().name,workflowMetadata:a.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(a,i)=>{const s=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===i);return s?e(s):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,items:A,bundleOwnerId:this.ownerId}}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,A){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,A),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignProductCollection(t){var A,a;const e=await F.getShadowGraphqlClient().mutate({mutation:No(((A=this.globalPropertyStateManager.getBundleOptions())==null?void 0:A.eagerFetchProducts)??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});(a=e.data)!=null&&a.bundleAssignProductCollection.productCollection&&(this.productCollection=e.data.bundleAssignProductCollection.productCollection,this.globalPropertyStateManager.setConfiguration(e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration))}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const a=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===a.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(A){console.error(`Unable to apply state to workflow experience: ${A}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const A=await this.client.getWorkflowExperiences(t.map(a=>({type:"transaction",transactionId:a})),e);if(A.forEach(a=>a.setBundle(this)),A.forEach(a=>a.checkForPriceBreakChanges()),this.workflowExperiences=A,this.previewService)for(const a of A)await this.injectExperienceIntoPreviewService(a)}async updateBundle(){var e;if(!((e=(await F.getShadowGraphqlClient().mutate({mutation:Io,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([A,a])=>({key:A,value:a})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}})).data)!=null&&e.bundleUpdate))throw new Error("Bundle not found!")}async updateTransactionOrder(){await F.getShadowGraphqlClient().mutate({mutation:vo,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async checkConditionalHandlesChanged(t,e){const A=await this.globalPropertyHandleService.getHandles(),a=this.globalPropertyHandleService.applyConditionsFromState(A,t),i=this.globalPropertyHandleService.applyConditionsFromState(A,e);if((()=>{if(a.length!==i.length)return!0;for(let o=0;o<a.length;o++)if(a[o].getName()!==i[o].getName())return!0;return!1})()){this.fireEvent("conditional-global-properties-changed",{globalProperties:i});const o=i.filter(r=>!a.includes(r));await Promise.all(o.map(r=>r.applyGlobalState()))}}fireEvent(t,e){(this.eventListeners.get(t)||[]).forEach(a=>a({bundle:this,event:t,data:e}))}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t){await F.getShadowGraphqlClient().mutate({mutation:Ho,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t}})}async reject(t){await F.getShadowGraphqlClient().mutate({mutation:bo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t}})}}const wr=p.gql`
|
|
3226
|
+
`)},u))}else a.push(new O(E,u))}return a},ir=(n,t)=>n.conditions?n.conditions.every(e=>{const A=t[e.targetStepName];if(A&&A.selectedVariants){const a=A.selectedVariants;return e.requiredVariantSelections.some(i=>a.find(s=>s.id===i)!==void 0)}return!1}):!0,In=async(n,t,e,A)=>{const a=[],i={};for(const s of n){const o=t.steps.find(r=>r.stepName===s.name);if(o)switch(o.type){case M.DigitalContent:a.push(...await Zo(e,s,o));break;case M.Frame:case M.Photo:a.push(...await $o(e,i,s,o));break;case M.Illustration:a.push(...await _o(e,i,s,o));break;case M.Module:a.push(...await tr(e,s,o));break;case M.Picture:a.push(...await er(e,i,s,o));break;case M.Shape:a.push(...await Ar(e,i,s,o));break;case M.Text:a.push(...await nr(e,i,s,o));break}}for(const s of t.steps)s.type!==M.SilentIllustration&&s.type!==M.ProductOverlay||ir(s,i)&&a.push(...await ar(e,s,A));return a};class sr{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(A=>e.set(A.id,new cr(A.id,A.name,this,{width:A.width,height:A.height}))),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}}const or=()=>new Promise((n,t)=>{try{const A=Bt().getContext("webgl2");n(!!A)}catch{n(!1)}}),rr=or();class cr{constructor(t,e,A,a){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new CA(2),this.id=t,this.name=e,this.service=A,this.panelSize=a}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=Mt(t);this.lastRequestedRenderArguments=e;const A=this.getStaticContext();if(!A){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new lr(this.getID(),A,await rr,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e))}}class lr extends hA{constructor(t,e,A,a,i){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=A,this.onRender=a,this.layouts=i}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,a=e/t.height,i=Math.min(A,a);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){const t=this.layouts.find(B=>B.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],A=t.layoutState.layout.width,a=t.layoutState.layout.height,i=A===1||a===1?{width:1,height:1}:this.getDynamicTextureResolution(),s=i.width,o=i.height;let r,c;if(this.nonPOTSupport){const B=s/o;A/a<B?(r=s,c=a*(s/A)):(r=A*(o/a),c=o);const C=this.resizeFit({width:r,height:c});r=C.width,c=C.height}else r=i.width,c=i.height;const l=Se(t.layoutState.layout,e,{renderingConfiguration:{purpose:xt.ThreeD}}),g=Ca(l),d=await oA.Pith.from(this.ctx,g,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:Bt,createImage:te,DOMParser:dA(),fetch});d.resize(r,c),await d.render(),this.onRender()}}const gr=(n,t)=>{const e=[];return n.forEach(A=>{const a=t.steps.find(i=>i.stepName===A.stepName);(a==null?void 0:a.type)===M.Text&&A.stepAspectType==="Text"&&e.push({name:a.stepName,data:{text:A.value}})}),e},dr=async(n,t,e,A)=>{let a={serializableWorkflow:{steps:[]},layouts:{}};a=new U(e.map(r=>new pA(r))).apply(a);const s=await In(n,t,e,A);return new U(s).apply(a)};class Br{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[];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 a=e.aspects.find(i=>i.name===A.targetAspectName);return a?A.requiredVariantSelections.some(i=>i===a.value):!1})}async createHandle(t){switch(t.type){case nt.FileUpload:return new Fn(this.bundle,t);case nt.ColorOption:return new iA(this.bundle,t,t.entityId?await $.getOption(t.entityId):void 0);case nt.Option:{const e=t.entityId?await $.getOption(t.entityId):void 0;return(e==null?void 0:e.type)==="Color"?new iA(this.bundle,t,e):new NA(this.bundle,t,e)}case nt.Text:return new yn(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Pe{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(a=>a.getStepsConditionallyActive().filter(i=>{var s;return i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:(s=i.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var r,c;return o.globalPropertyConfigurationId===((c=(r=this.bundle.getProductCollection())==null?void 0:r.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name})}))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Fn extends Pe{constructor(t,e){super(t,e)}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)])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(fe.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(),a=await G.removeBackgroundFromAsset(e),s={...A.getAspectStorage(this.property.name),backgroundRemovedAssetKey:a.key,useOriginalAsset:!t},r=[t?A.setAspect(this.property.name,a.key,s):A.setAspectStorage(this.property.name,s)];return t&&r.push(this.applyImageSelection(a,void 0,!1,!1)),await Promise.all(r),this.updateSharedStepStorage(s),a}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return G.getLocalOrFromServer(t)}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.originalAssetKey)return G.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.backgroundRemovedAssetKey)return G.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(),a=A.getAspectStorage(this.property.name);if((a==null?void 0:a.useOriginalAsset)===t)return;const i={...a,useOriginalAsset:t},s=t?a==null?void 0:a.originalAssetKey:a==null?void 0:a.backgroundRemovedAssetKey,o=[A.setAspect(this.property.name,s||"",i)];if(t)o.push(this.applyImageSelection(e,void 0,!1,!1));else{const r=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(r())}this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const A=await G.getLocalOrFromServer(e);if(!A)return;const a=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await this.applyImageSelection(A,t,!1,!0),a?this.updateSharedStepStorage({...a}):(this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e}))}async applyImageSelection(t,e,A=!0,a=!0){const s=this.getSharedSteps(e).map(o=>{const r=o;if(r.getFrameService())return r.selectImage(t,A,a)});await Promise.all(s)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(A=>A.getSteps().forEach(a=>{var s;if(a.getOverrideGlobalPropertyConfiguration(this.property.type))return;((s=a.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var r,c;return o.globalPropertyConfigurationId===((c=(r=this.bundle.getProductCollection())==null?void 0:r.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name}))&&A.getWorkflowManager().updateStorage(a.getId(),{framePatternData:t})}))}}class yn extends Pe{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 a=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(a)}}class NA extends Pe{constructor(t,e,A){super(t,e),this.optionResource=A}getCurrentVariant(){var e,A;if(!this.optionResource)return;const t=this.getStateValue();if(t){const a=(A=this.optionResource.variants)==null?void 0:A.find(i=>i.id===t);return a?new at(a):void 0}else{const a=(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 a?new at(a):void 0}}getAvailableVariants(){var e,A;return(((A=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:A.filter(a=>a.enabled))||[]).map(a=>new at(a))}getAllVariants(){var e;return(((e=this.optionResource)==null?void 0:e.variants)||[]).map(A=>new at(A))}async selectVariant(t){console.log(`Selecting variant ${t.getId()}`),await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId()),this.applyVariantSelection(t)])}async applyGlobalState(t){var a,i;const e=this.getStateValue();if(!e)return Promise.resolve();const A=(i=(a=this.optionResource)==null?void 0:a.variants)==null?void 0:i.find(s=>s.id===e);return A?(console.log(`Applying global state using variant ${A.id} for aspect ${e}`),this.applyVariantSelection(new at(A),t)):Promise.resolve()}async applyVariantSelection(t,e){const a=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(a)}}class iA extends NA{constructor(t,e,A){super(t,e,A)}async selectVariant(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId()),this.applyColorVariant(t)])}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(r=>r.id===e);if(!A)return Promise.resolve();await this.applyColorVariant(new at(A),t);const a=(o=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:o.customColor;a&&this.setCustomColor(a)}async applyColorVariant(t,e){const a=this.getSharedSteps(e).map(i=>{switch(i.getType()){case M.Shape:return i.selectVariant(t);case M.Text:return i.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()})}});await Promise.all(a)}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"}}class hr{constructor(t,e,A,a,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(()=>{this.globalPropertyState=s}):this.createGlobalPropertyState().then(o=>{this.globalPropertyState=o}),this.onGlobalPropertyStateChange=a}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=Mt(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspect(t){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const e=this.globalPropertyState.aspects.find(A=>A.name===t);if(e)return e.value}getAspectStorage(t){var e;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(e=this.globalPropertyState.aspects.find(A=>A.name===t))==null?void 0:e.storage}async setAspect(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 a=this.configuration.aspects.find(o=>o.name===t);if(!a)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=Mt(this.globalPropertyState),s=this.globalPropertyState.aspects.find(o=>o.name===t);s?(s.value=e,s.type=a.type,A!==void 0&&(s.storage=A!==null?A:void 0)):this.globalPropertyState.aspects.push({name:t,value:e,type:a.type,storage:A!==null?A:void 0}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async setAspectStorage(t,e){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 A=this.configuration.aspects.find(s=>s.name===t);if(!A)throw new Error(`Failed to find configuration aspect with name: ${t}`);const a=Mt(this.globalPropertyState),i=this.globalPropertyState.aspects.find(s=>s.name===t);i?(i.storage=e!==null?e:void 0,i.type=A.type):this.globalPropertyState.aspects.push({name:t,value:"",type:A.type,storage:e!==null?e:void 0}),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(a,this.globalPropertyState)}async updateGlobalPropertyState(){var e,A;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await F.getShadowGraphqlClient().mutate({mutation:wo,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(a=>{let i=a.type&&a.storage?{}:void 0;if(i)switch(a.type){case nt.FileUpload:{i.fileUpload=a.storage;break}case nt.Option:{i.option=a.storage;break}case nt.ColorOption:{i=a.storage;break}}return{name:a.name,value:a.value,type:a.type,storage:i}})},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 F.getShadowGraphqlClient().mutate({mutation:Co,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 Cr{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 a=this.flipTransform(A,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=a.position,i.rotation=a.rotation,i.scale=a.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,A){const a=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(s=>s.transactionId===a);i?(i.transforms||(i.transforms={}),i.transforms[e]=A):this.state.transactions.push({transactionId:a,activeTransform:e,transforms:{[e]:A}})}activateWorkflowExperienceTransform(t,e){var r,c;if(!((r=t==null?void 0:t.getWorkflowManager())!=null&&r.getModelContainer())||!this.state)return;const A=t.getWorkflowManager().getTransaction().id,a=this.state.transactions.find(l=>l.transactionId===A),i=(c=a==null?void 0:a.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,a.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 JSON.stringify(this.state)}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}}}class Mn{constructor(t){this.fullFetched=!1,this.collection=t;const e=this.collection.productCollectionProducts;e&&e.length>0&&(this.fullFetched=!0)}getId(){return this.collection.id}getName(){return this.collection.name}getDescription(){return this.collection.description||""}getImage(){return this.collection.image}getProducts(){if(!this.collection.productCollectionProducts)throw new Error("Failed to find products on collection. Ensure you fetch them first!");return this.collection.productCollectionProducts.map(t=>new he(t))}async fetchProducts(t){if(this.fullFetched)return this.collection.productCollectionProducts.map(A=>new he(A));const e=await F.getShadowGraphqlClient().query({query:fo,variables:{id:this.getId(),productIds:t},errorPolicy:"all"});return t||(this.fullFetched=!0),this.collection.productCollectionProducts=e.data.productCollections[0].productCollectionProducts||[],this.collection.productCollectionProducts.map(A=>new he(A))}async filterProducts(t){var i,s;const e=await F.getShadowGraphqlClient().query({query:Qo,errorPolicy:"all",variables:{id:this.getId(),filters:{link:"And",metafields:t}}});if(!((i=e.data)!=null&&i.productCollections)||((s=e.data)==null?void 0:s.productCollections.length)===0)throw new Error("Failed to filter product collection products.");const A=this.getProducts(),a=e.data.productCollections[0].productCollectionProducts.map(o=>o.product.id);return A.filter(o=>a.includes(o.getId()))}getTransformCollection(){if(this.collection.transformCollection)return new Sn(this.collection.transformCollection)}getResource(){return this.collection}}class he{constructor(t){this.product=t.product,this.productResource=t}getId(){return this.product.id}getName(){return this.product.name}getIntegrationByType(t,e){const a=(this.product.integrationProducts||[]).find(i=>{var c,l,g;const s=(c=i.integration)==null?void 0:c.type,o=((l=i.integration)==null?void 0:l.type)===t,r=e?((g=i.integration)==null?void 0:g.externalIntegrationId)===e:!0;return s&&o&&r});if(!a)throw new Error("Failed to find requested integration type on product. This is generally due to a configuration error");return a}getCurrentIntegration(){const e=(this.product.integrationProducts||[]).find(A=>{var a;return(a=A.integration)==null?void 0:a.isCurrent});if(!e)throw new Error(`Product: ${this.productResource.id} is not linked to this current integration. This is generally due to a configuration error.`);return e}getDefaultWorkflow(){const t=this.product.workflows;if(t===void 0)throw new ct("Called getDefaultWorkflow() before fetching collection products. Use collection.fetchProducts() first to ensure the data is available.");if(t.length===0)throw new ct("Called getDefaultWorkflow() but no workflows on requested product. Ensure at least 1 workflow is assigned to this product.");const e=this.productResource.workflowId;if(e){const A=t.find(a=>a.workflowName===e);if(A)return new St(A)}if(t.length===1)return console.warn("Called getDefaultWorkflow() but no default was configured. There is only one workflow available so we will fall back to using this!"),new St(t[0]);throw new ct("Called getDefaultWorkflow() but no default workflow is configured for the requested product. Multiple workflows exist so we can't assume!")}getAllWorkflows(){if((this.product.workflows||[]).length===0)throw new ct("No workflows on configured product. Ensure at least 1 workflow is assigned to this product.");return this.product.workflows.sort((e,A)=>(e.index??0)-(A.index??0)).map(e=>new St(e))}getIntegrations(){return this.product.integrationProducts||[]}getResource(){return this.product}getBasePrice(t){var a,i,s,o;const e=this.product.basePrice||0;if(!t)return e;if(!t.integrationType&&!t.externalId&&!t.integrationId)throw new Error("You must provide at least one of the following fields on the includeAdditionalProduct object: integrationType, externalId, integrationId");let A;return t.integrationId?A=(a=this.product.integrationProducts)==null?void 0:a.find(r=>{var c;return((c=r.integration)==null?void 0:c.id)===t.integrationId}):t.externalId?A=(i=this.product.integrationProducts)==null?void 0:i.find(r=>{var c;return((c=r.integration)==null?void 0:c.externalIntegrationId)===t.externalId}):A=(s=this.product.integrationProducts)==null?void 0:s.find(r=>{var c;return((c=r.integration)==null?void 0:c.type)===t.integrationType}),(o=A==null?void 0:A.additionalIntegrationProduct)!=null&&o.product?e+(A.additionalIntegrationProduct.product.basePrice||0):e}}class St{constructor(t){this.workflow=t}getId(){return this.workflow.workflowName}getName(){return this.workflow.friendlyName}getThumbnail(){return this.workflow.imageUrl}}class Sn{constructor(t){this.collection=t}getId(){return this.collection.id}getName(){return this.collection.name}getTransforms(){return this.collection.transforms.map(t=>new xn(t))}}class xn{constructor(t){this.transform=t}getId(){return this.transform.id}getName(){return this.transform.name}get(){return{position:this.transform.position,rotation:this.transform.rotation,scale:this.transform.scale}}}class Oe{constructor(t,e,A,a,i,s){var o,r,c;this.eventListeners=new Map,this.workflowExperiences=[],this.client=t,this.id=e.id,this.name=e.name||"",this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(((o=e.metadata)==null?void 0:o.map(l=>[l.key,l.value]))||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new Cr(e.bundleStateData),this.globalPropertyStateManager=new hr(this.id,this.ownerId,(r=this.productCollection)==null?void 0:r.globalPropertyConfiguration,this.checkConditionalHandlesChanged.bind(this),s),this.globalPropertyHandleService=new Br(this),this.setPreviewService(A),this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(((c=e.transactions)==null?void 0:c.map(l=>l.id))||[],{...a,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]),this.initializationPromise.catch(l=>{console.error(`Bundle initialization failed: ${l}`)})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventListeners.set(t,[...this.eventListeners.get(t)||[],e])}removeEventListener(t,e){const A=this.eventListeners.get(t)||[],a=A.indexOf(e);a>-1&&A.splice(a,1)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}setName(t){return this.name=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){var t;return!!((t=this.productCollection)!=null&&t.globalPropertyConfiguration)}getGlobalPropertyConfiguration(){var t;return(t=this.productCollection)==null?void 0:t.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(A=>A.getType()===nt.Option).map(A=>{var a;return((a=A.getCurrentVariant())==null?void 0:a.getPrice())||0}).reduce((A,a)=>A+a,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new Mn(this.productCollection):void 0}async addWorkflowExperience(t){t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const A of e)await A.applyGlobalState([t])}async addWorkflowExperiences(t){const e=t.map(o=>o.getWorkflowManager().getTransaction().id),A=e.map(o=>this.workflowExperiences.find(r=>r.getWorkflowManager().getTransaction().id===o));if(A.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+A.filter(o=>!!o).map(o=>o==null?void 0:o.getWorkflowManager().getTransaction().id).join(", "));const a=N.getMap("transactionOwnerIds")||new Map,i=e.map(o=>a.get(o));await F.getShadowGraphqlClient().mutate({mutation:yo,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...t);const s=async()=>{for(const r of t)r.setBundle(this),await this.injectExperienceIntoPreviewService(r);await Promise.all(t.map(r=>r.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const r of o)await r.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),s()]),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges())}async appendWorkflowExperience(t,e=!0){const A=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===A))throw new Error("Unable to add transaction to bundle - Already Exists!");const s=(N.getMap("transactionOwnerIds")||new Map).get(A);await F.getShadowGraphqlClient().mutate({mutation:Fo,variables:{id:this.id,transactionId:A},context:{bundleOwnerId:this.ownerId,transactionOwnerId:s}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction())}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(A=>A.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,A=!0){if(t>-1){const a=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);a.setBundle(void 0),this.previewService&&a.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await F.getShadowGraphqlClient().mutate({mutation:Mo,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,s])=>({key:i,value:s})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),A&&(this.workflowExperiences.splice(t,1),this.workflowExperiences.forEach(i=>i.checkForPriceBreakChanges()),a.checkForPriceBreakChanges(),await this.updateTransactionOrder())}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(a=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===a.id));if(e.some(a=>a===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((a,i)=>e[i]===-1).map(a=>a.id).join(", "));const A=t.map(a=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===a.id),1)[0]);A.forEach(a=>a.setBundle(void 0)),[...this.workflowExperiences,...A].forEach(a=>a.checkForPriceBreakChanges()),this.previewService&&A.forEach(a=>a.getWorkflowManager().ejectFromPreviewService()),t.forEach(a=>this.bundleStateManager.removeStateForTransaction(a.id)),await F.getShadowGraphqlClient().mutate({mutation:So,variables:{id:this.id,transactionIds:t.map(a=>a.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,i])=>({key:a,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const A=await this.getGlobalProperties();await Promise.all(A.map(a=>a.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const A=this.workflowExperiences[t];if(A.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,A.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const a=await this.getGlobalProperties();await Promise.all(a.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const A=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=A,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){var i;const A=await F.getShadowGraphqlClient().mutate({mutation:xo,variables:{id:this.id,details:t,type:e||jt.Owner},context:{bundleOwnerId:this.ownerId}});if(!((i=A.data)!=null&&i.bundleAddStakeholder))throw new Error("Bundle not found!");const a=A.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async removeStakeholder(t){var A;if(!((A=(await F.getShadowGraphqlClient().mutate({mutation:Yo,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data)!=null&&A.bundleRemoveStakeholder))throw new Error("Bundle not found!")}async updateStakeholders(t){var a;const e=await F.getShadowGraphqlClient().mutate({mutation:Po,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!((a=e.data)!=null&&a.bundleUpdateStakeholders))throw new Error("Bundle not found!");const A=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(A)}async getAllStakeholders(){const t=await F.getShadowGraphqlClient().query({query:_A,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await F.getShadowGraphqlClient().query({query:_A,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){if(this.completed)return await F.getShadowGraphqlClient().mutate({mutation:Ro,variables:{bundleId:this.id}}),{bundleId:this.id,items:[],bundleOwnerId:this.ownerId};const A=await Vo(this.workflowExperiences.map(a=>({workflowManager:a.getWorkflowManager(),workflow:a.getWorkflowManager().getWorkflow(),layouts:a.getWorkflowManager().getLayouts(),getReducerState:()=>a.getCommandContext().getState(),product:a.getWorkflowManager().getProduct(),transaction:a.getWorkflowManager().getTransaction(),workflowSelections:a.getWorkflowManager().getWorkflowSelections(),designName:a.getWorkflowManager().getWorkflow().name,workflowMetadata:a.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(a,i)=>{const s=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===i);return s?e(s):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,items:A,bundleOwnerId:this.ownerId}}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,A){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,A),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignProductCollection(t){var A,a;const e=await F.getShadowGraphqlClient().mutate({mutation:No(((A=this.globalPropertyStateManager.getBundleOptions())==null?void 0:A.eagerFetchProducts)??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});(a=e.data)!=null&&a.bundleAssignProductCollection.productCollection&&(this.productCollection=e.data.bundleAssignProductCollection.productCollection,this.globalPropertyStateManager.setConfiguration(e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration))}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const a=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===a.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(A){console.error(`Unable to apply state to workflow experience: ${A}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const A=await this.client.getWorkflowExperiences(t.map(a=>({type:"transaction",transactionId:a})),e);if(A.forEach(a=>a.setBundle(this)),A.forEach(a=>a.checkForPriceBreakChanges()),this.workflowExperiences=A,this.previewService)for(const a of A)await this.injectExperienceIntoPreviewService(a)}async updateBundle(){var e;if(!((e=(await F.getShadowGraphqlClient().mutate({mutation:Io,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([A,a])=>({key:A,value:a})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}})).data)!=null&&e.bundleUpdate))throw new Error("Bundle not found!")}async updateTransactionOrder(){await F.getShadowGraphqlClient().mutate({mutation:vo,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async checkConditionalHandlesChanged(t,e){const A=await this.globalPropertyHandleService.getHandles(),a=this.globalPropertyHandleService.applyConditionsFromState(A,t),i=this.globalPropertyHandleService.applyConditionsFromState(A,e);if((()=>{if(a.length!==i.length)return!0;for(let o=0;o<a.length;o++)if(a[o].getName()!==i[o].getName())return!0;return!1})()){this.fireEvent("conditional-global-properties-changed",{globalProperties:i});const o=i.filter(r=>!a.includes(r));await Promise.all(o.map(r=>r.applyGlobalState()))}}fireEvent(t,e){(this.eventListeners.get(t)||[]).forEach(a=>a({bundle:this,event:t,data:e}))}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t){await F.getShadowGraphqlClient().mutate({mutation:Ho,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t}})}async reject(t){await F.getShadowGraphqlClient().mutate({mutation:bo,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t}})}}const wr=p.gql`
|
|
3227
3227
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
|
3228
3228
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
|
3229
3229
|
id
|
|
@@ -3346,7 +3346,7 @@ IfnI8vaNAAAAAElFTkSuQmCC" transform="matrix(0.13 0.0141 -0.0141 0.1301 104.926 1
|
|
|
3346
3346
|
}
|
|
3347
3347
|
}
|
|
3348
3348
|
}
|
|
3349
|
-
`,Ir=async(n,t)=>{var a;const e=await F.getShadowGraphqlClient().query({query:Gi(((a=t==null?void 0:t.assets)==null?void 0:a.metadata)||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const A=e.data.workflows;if(A===void 0||A.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return A.forEach(i=>{i.steps.forEach(s=>{var o,r,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((r=s.option.defaultVariant)!=null&&r.asset&&G.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&G.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(l=>{l.asset&&G.cacheAsset(l.asset),l.thumbnail&&G.cacheAsset(l.thumbnail),l.material&&G.cacheMaterial(l.material)}),Pt.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.partner.termsMarkdown}),A},Fr=async(n,t)=>{const A=(await t).find(a=>a.id===n);if(!A)throw new Error(`Workflow not found: ${n}`);return A},HA=async(n,t)=>{const e=n.map(o=>Pt.get({id:o,options:t})),A=n.filter((o,r)=>e[r]===void 0);if(A.length===0)return Promise.all(e);const a=Ir(A,t),i=A.map(o=>Pt.set({id:o,options:t},Fr(o,a))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},yr=async(n,t)=>(await HA([n],t))[0],Mr=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:R(),panelId:t.name,name:t.name,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),Sr=(n,t)=>{const e=n.workflowState,A=e?JSON.parse(e):void 0;return A?Object.values(A.layouts).map(a=>a.layout):Mr(t.panels)};class xr{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return F.getShadowGraphqlClient().mutate({...e,mutation:Mi})}catch(A){throw console.error(A),new ct("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ai(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 26.1.1"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){gt.setHubUrl(t.hubUrl),gt.setServerUrl(t.serverUrl),gt.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,t.bearerAuthenticationToken&&ma(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return G}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!ai())throw new Error("Application key required to use Flow Service.");return new Yn}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=Nn(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 a,i;const e=N.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:jt.Owner});const A=N.getMap("bundlePartnerIds")||new Map;if(A.has(t)){const s=A.get(t),r=(N.getMap("partnerCustomerIds")||new Map).get(s);if(r&&await this.authenticateCustomerId(r)){const l=(i=(a=this.customer)==null?void 0:a.bundleStakeholders)==null?void 0:i.find(g=>{var d;return((d=g.bundle)==null?void 0:d.id)===t});if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var l,g,d,B,h,C;const e=F.getShadowGraphqlClient(),A=await e.query({query:Ti,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!A.data.transactions||A.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const a=A.data.transactions[0];if(!((g=(l=a.product)==null?void 0:l.partner)==null?void 0:g.id))throw new Error(`Unable to read transaction: ${t}`);if(a.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=N.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:jt.Owner});const o=N.getMap("transactionCustomerIds");if(o!=null&&o.has(t)){const w=o.get(t);if(w&&await this.authenticateCustomerId(w)){const E=((B=(d=this.customer)==null?void 0:d.bundleStakeholders)==null?void 0:B.find(m=>{var f,Q;return(Q=(f=m.bundle)==null?void 0:f.transactions)==null?void 0:Q.some(D=>D.id===t)}))||((C=(h=this.customer)==null?void 0:h.stakeholders)==null?void 0:C.find(m=>{var f;return((f=m.transaction)==null?void 0:f.id)===t}));if(E)return Promise.resolve({success:!0,stakeholderType:E.type})}}const c=(await e.query({query:Ji,errorPolicy:"all",variables:{id:a.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${a.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:a.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=N.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),N.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const a=(await F.getShadowGraphqlClient().query({query:ea,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return a.id?a.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var A,a;const e=(a=(A=this.customer)==null?void 0:A.stakeholders)==null?void 0:a.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=F.getShadowGraphqlClient(),a=(await e.query({query:ea,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!a.id){const r=(s=(await e.mutate({mutation:mr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!r)throw new Error("Unable to create customer.");return this.storeCustomer(r),this.customer=r,{customer:r,isAuthenticated:!1}}this.storeCustomer(a);const i=await this.authenticateCustomerId(a.id);return{customer:this.customer||a,isAuthenticated:i}}getCustomer(){return this.customer}async authenticateCustomerId(t){var o;const e=F.getShadowGraphqlClient(),A=N.getMap("customerTokens");if(!(A!=null&&A.has(t)))return!1;const a=A.get(t);if(!a)return!1;const s=(o=(await e.mutate({mutation:fr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:a}})).data)==null?void 0:o.customerAuthenticate;return s?(this.storeCustomer(s),OA(a),this.customer=s,!0):!1}async generateVerificationCode(t){await F.getShadowGraphqlClient().mutate({mutation:Qr,variables:{emailAddress:t}})}async verifyCode(t,e){var i,s;const a=(i=(await F.getShadowGraphqlClient().mutate({mutation:pr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data)==null?void 0:i.customerVerifyCode;if(a!=null&&a.loginToken){if(!((s=a.partner)!=null&&s.id))throw new Error(`Unable to find customer: ${t}`);const o=N.getMap("customerTokens")||new Map;return o.set(a.id,a.loginToken),N.setMap("customerTokens",o),this.storeCustomer(a),OA(a.loginToken),this.customer={...a,loginToken:void 0},!0}return!1}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await F.getShadowGraphqlClient().query({query:Dr,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,A){var c,l,g,d,B;const i=(g=(await F.getShadowGraphqlClient().mutate({mutation:po(((l=(c=A==null?void 0:A.graphql)==null?void 0:c.productCollection)==null?void 0:l.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((h,C)=>({key:h[0],value:h[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:g.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=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 r=new Oe(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(B=(d=A==null?void 0:A.graphql)==null?void 0:d.productCollection)==null?void 0:B.eagerFetchProducts});return await r.getInitializationPromise(),r}async getExistingBundle(t,e,A,a){var w,u,E,m,f,Q,D,I,y,x,Y;const i=N.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),r=((w=Object.entries(localStorage).find(([P,v])=>P.startsWith("CognitoIdentityServiceProvider")&&P.endsWith("idToken")))==null?void 0:w[0])||"",c=localStorage.getItem(r),l={};c&&!me(c)&&(l.Authorization=`Bearer ${c}`);const g={bundleOwnerId:s,...l,...(u=a==null?void 0:a.graphql)==null?void 0:u.additionalHeaders},d=await F.getShadowGraphqlClient().query({query:Eo(((m=(E=a==null?void 0:a.graphql)==null?void 0:E.productCollection)==null?void 0:m.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:g}});if(!((f=d.data)!=null&&f.bundles)||((Q=d.data)==null?void 0:Q.bundles.length)===0||!((D=d.data)!=null&&D.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const B=(I=d.data)==null?void 0:I.bundles[0],h=N.getMap("bundlePartnerIds")||new Map;h.set(B.id,B.partner.id),N.setMap("bundlePartnerIds",h);const C=new Oe(this,B,e,A,s,{additionalHeaders:(y=a==null?void 0:a.graphql)==null?void 0:y.additionalHeaders,eagerFetchProducts:(Y=(x=a==null?void 0:a.graphql)==null?void 0:x.productCollection)==null?void 0:Y.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState});return await C.getInitializationPromise(),C}async duplicateBundle(t,e,A,a){var w,u,E,m,f,Q,D,I;const i=(w=N.getMap("bundleOwnerIds"))==null?void 0:w.get(t),o=((u=Object.entries(localStorage).find(([y,x])=>y.startsWith("CognitoIdentityServiceProvider")&&y.endsWith("idToken")))==null?void 0:u[0])||"",r=localStorage.getItem(o),c={};r&&!me(r)&&(c.Authorization=`Bearer ${r}`);const l={bundleOwnerId:i,...c,...(E=a==null?void 0:a.graphql)==null?void 0:E.additionalHeaders},d=(Q=(await F.getShadowGraphqlClient().mutate({mutation:Do(((f=(m=a==null?void 0:a.graphql)==null?void 0:m.productCollection)==null?void 0:f.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:A},context:{headers:l},fetchPolicy:"no-cache"})).data)==null?void 0:Q.bundleDuplicate;if(!(d!=null&&d.id))throw new Error("Unable to duplicate bundle");const B=N.getMap("bundlePartnerIds")||new Map;B.set(d.id,d.partner.id),N.setMap("bundlePartnerIds",B);const h=N.getMap("bundleOwnerIds")||new Map;h.set(d.id,d.bundleOwnerId),N.setMap("bundleOwnerIds",h);const C=new Oe(this,d,void 0,void 0,d.bundleOwnerId,{eagerFetchProducts:(I=(D=a==null?void 0:a.graphql)==null?void 0:D.productCollection)==null?void 0:I.eagerFetchProducts});return await C.getInitializationPromise(),C}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...A}=t;return(await F.getShadowGraphqlClient().query({query:ko(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 F.getShadowGraphqlClient().query({query:mo,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const A=t.data.customers[0].bundleStakeholders||[],a=N.getMap("bundlePartnerIds")||new Map;return A.forEach(s=>{var o,r;(o=s.bundle)!=null&&o.id&&((r=s.bundle.partner)!=null&&r.id)&&a.set(s.bundle.id,s.bundle.partner.id)}),N.setMap("bundlePartnerIds",a),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),a=A[0];return e&&await a.getWorkflowManager().injectIntoPreviewService(e(a.getWorkflowManager().getWorkflow())),A[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new ct("No options provided!");const A=F.getShadowGraphqlClient(),a=async Q=>{var x,Y,P;if(Q.length===0)return[];const D=Q.map(v=>v.option.transactionId),I=await A.query({query:yi,variables:{ids:D},errorPolicy:"all",fetchPolicy:"no-cache"}),y=I.data.transactions;if(y.length!==Q.length){const v=((Y=(x=I.errors)==null?void 0:x[0])==null?void 0:Y.message)||"Unknown error";throw new ct(`Not all transactions were found: ${v}`)}return!this.activeIntegration&&((P=y[0].integrationProduct)!=null&&P.integration)&&(this.activeIntegration=Promise.resolve(y[0].integrationProduct.integration)),y.map((v,b)=>{var K;return{transaction:v,workflowId:v.workflowId,readOnly:((K=Q.find(j=>j.option.transactionId===v.id))==null?void 0:K.option.readOnly)??!1,index:Q[b].index}})},i=async Q=>{var y,x,Y;if(Q.length===0)return[];const D=await A.mutate({mutation:Fi,variables:{inputs:Q.map(P=>({integrationProductId:P.option.type==="integration"?P.option.integrationProductId:void 0,externalIntegrationId:P.option.type==="external"?P.option.externalIntegrationId:void 0,externalProductId:P.option.type==="external"?P.option.externalProductId:void 0,workflowId:P.option.workflowId,designName:P.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),I=(y=D.data)==null?void 0:y.transactionCreateMany;if(!I||I.length===0){const P=((Y=(x=D.errors)==null?void 0:x[0])==null?void 0:Y.message)||"Unknown error";throw new ct(`Failed to create transactions: ${P}`)}return I.map((P,v)=>({transaction:P,workflowId:P.workflowId,readOnly:!1,index:Q[v].index}))},s=t.map((Q,D)=>({option:Q,index:D})),o=s.filter(Q=>Q.option.type==="transaction"),r=s.filter(Q=>Q.option.type==="integration"||Q.option.type==="external"),c=UA(o,10),l=UA(r,10),g=(await Promise.all([...c.map(a),...l.map(i)])).flat(),d=[...new Set(g.map(Q=>Q.workflowId))],B=await HA(d,e),h=new Map(B.map(Q=>[Q.id,Q])),C=N.getMap("transactionOwnerIds")||new Map,w=g.map(async Q=>{var K;const{transaction:D,workflowId:I,readOnly:y,index:x}=Q,Y=h.get(I),P=t[x];!C.get(D.id)&&D.transactionOwnerId&&C.set(D.id,D.transactionOwnerId);const v=C.get(D.id)||void 0,b={product:D.product,transaction:D,layouts:[],singleVariantsRenderable:(K=P==null?void 0:P.workflowConfiguration)==null?void 0:K.singleVariantsRenderable,stateMutationFunc:y?async()=>{throw new L("State mutation is forbidden in read only mode!")}:async j=>this.updateTransactionState({...j,context:{transactionOwnerId:v,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),readOnly:y,workflow:Y,isReloadedTransaction:P.type==="transaction"};if(P.type==="transaction"&&D.workflowState){const j=JSON.parse(D.workflowState);b.layouts=Object.values(j.layouts||{}).map(At=>At.layout),await XA(j),b.reloadedState=j}else if(!y&&P.workflowState){const j=JSON.parse(P.workflowState);b.layouts=Object.values(j.layouts||{}).map(At=>At.layout),await XA(j),b.reloadedState=j}else b.layouts=Sr(b.transaction,b.workflow);return b.renderableContextService=new sr(b.layouts),b.delayWorkflowStateSync=!0,{experienceOptions:b,index:x,options:P}}),u=await Promise.all(w);N.setMap("transactionOwnerIds",C);const m=u.sort((Q,D)=>Q.index-D.index).map(async Q=>{const{experienceOptions:D,options:I}=Q,y=new Dn(this,D);return await y.getWorkflowManager().getInitializationPromise(),I.type!=="transaction"&&this.customer&&await y.attachCustomerDetails({email:this.customer.emailAddress}),y}),f=await Promise.all(m);return f.forEach(Q=>Q.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),f}storeCustomer(t){const e=N.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),N.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t){var i,s;const a=(i=(await F.getShadowGraphqlClient().query({query:Pi,variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:i.integrationProducts;if(!a||a.length===0||!((s=a[0])!=null&&s.id))throw new Error("Integration product not found.");return new sA(a[0])}async getIntegrationProductFromExternalIds(t,e){var s;const i=(s=(await F.getShadowGraphqlClient().query({query:vi,variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProductFromExternalIds;if(!(i!=null&&i.id))throw new Error("Integration product not found.");return new sA(i)}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,a=await F.getShadowGraphqlClient().query({query:Yi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:A}});if(!a.data.transactions||a.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return a.data.transactions[0].transactionShareActions}}const Nn=async n=>(await F.getShadowGraphqlClient().query({query:Oi,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}}})).data.currentIntegration,Yr=async n=>{const e=await F.getShadowGraphqlClient().query({query:xi,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Pr=async(n,t)=>{var A;return(A=(await F.getShadowGraphqlClient().query({query:Li,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data)==null?void 0:A.marketplaceThemeInstallConfiguration},vr=async n=>{var e,A,a;return(a=(A=(e=(await F.getShadowGraphqlClient().query({query:ji,errorPolicy:"all",variables:{id:n}})).data)==null?void 0:e.bundles)==null?void 0:A[0])==null?void 0:a.marketplaceThemeInstallConfiguration},Nr=async n=>{var e,A,a;return(a=(A=(e=(await F.getShadowGraphqlClient().query({query:zi,errorPolicy:"all",variables:{id:n}})).data)==null?void 0:e.transactions)==null?void 0:A[0])==null?void 0:a.marketplaceThemeInstallConfiguration};class kr{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 kn=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(kn||{});class Rn extends et{constructor(t,e,A){var a;super(t,e,A),this.frameService=(a=this.manager.getStepSpecificServices(this.getId()))==null?void 0:a.frameService}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ot.selectVariant(this.step,t.getResource(),e,this.manager,A=>this.setUpdateState(A))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,A=!0){var a;if(await ot.selectImage(this.step,t,this.manager,A),e){const i=((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(fe.BackgroundRemover)}async canRemoveBackground(){var t,e,A,a;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((a=(A=this.frameService)==null?void 0:A.getImageData())!=null&&a.svg)}async removeBackgroundFromImageSelection(t=!0){var i;if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const A=await G.removeBackgroundFromAsset(e);t&&await ot.selectImage(this.step,A,this.manager,!1);const a=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,backgroundRemovedAssetKey:A.key,useOriginalAsset:!t}}),A}changeColors(t){ot.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?ot.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 it(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ot.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,A,a){return a&&a.length>1&&t===void 0?"SelectFrame":e||A||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.originalAssetKey;if(t)return G.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 G.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var a;const e=((a=this.getFrameStepStorage())==null?void 0:a.framePatternData)||{};if(e.useOriginalAsset===t)return;const A=await this.getOriginalImageSelection();if(!A)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(A,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Rr=p.gql`
|
|
3349
|
+
`,Ir=async(n,t)=>{var a;const e=await F.getShadowGraphqlClient().query({query:Gi(((a=t==null?void 0:t.assets)==null?void 0:a.metadata)||!1),errorPolicy:"all",variables:{ids:n}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const A=e.data.workflows;if(A===void 0||A.length!==n.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return A.forEach(i=>{i.steps.forEach(s=>{var o,r,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((r=s.option.defaultVariant)!=null&&r.asset&&G.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&G.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(l=>{l.asset&&G.cacheAsset(l.asset),l.thumbnail&&G.cacheAsset(l.thumbnail),l.material&&G.cacheMaterial(l.material)}),Pt.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.partner.termsMarkdown}),A},Fr=async(n,t)=>{const A=(await t).find(a=>a.id===n);if(!A)throw new Error(`Workflow not found: ${n}`);return A},HA=async(n,t)=>{const e=n.map(o=>Pt.get({id:o,options:t})),A=n.filter((o,r)=>e[r]===void 0);if(A.length===0)return Promise.all(e);const a=Ir(A,t),i=A.map(o=>Pt.set({id:o,options:t},Fr(o,a))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},yr=async(n,t)=>(await HA([n],t))[0],Mr=n=>n.sort((t,e)=>t.index-e.index).map(t=>({id:R(),panelId:t.name,name:t.name,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),Sr=(n,t)=>{const e=n.workflowState,A=e?JSON.parse(e):void 0;return A?Object.values(A.layouts).map(a=>a.layout):Mr(t.panels)};class xr{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return F.getShadowGraphqlClient().mutate({...e,mutation:Mi})}catch(A){throw console.error(A),new ct("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Ai(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 26.1.2"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){gt.setHubUrl(t.hubUrl),gt.setServerUrl(t.serverUrl),gt.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,t.bearerAuthenticationToken&&ma(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration()}getAssetManager(){return G}getCurrencyCode(){if(this.currencyCode===void 0)throw new Error("No currency code set.");return this.currencyCode}getFlowService(){if(!ai())throw new Error("Application key required to use Flow Service.");return new Yn}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=Nn(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 a,i;const e=N.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:jt.Owner});const A=N.getMap("bundlePartnerIds")||new Map;if(A.has(t)){const s=A.get(t),r=(N.getMap("partnerCustomerIds")||new Map).get(s);if(r&&await this.authenticateCustomerId(r)){const l=(i=(a=this.customer)==null?void 0:a.bundleStakeholders)==null?void 0:i.find(g=>{var d;return((d=g.bundle)==null?void 0:d.id)===t});if(l)return Promise.resolve({success:!0,stakeholderType:l.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var l,g,d,B,h,C;const e=F.getShadowGraphqlClient(),A=await e.query({query:Ti,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!A.data.transactions||A.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const a=A.data.transactions[0];if(!((g=(l=a.product)==null?void 0:l.partner)==null?void 0:g.id))throw new Error(`Unable to read transaction: ${t}`);if(a.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=N.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:jt.Owner});const o=N.getMap("transactionCustomerIds");if(o!=null&&o.has(t)){const w=o.get(t);if(w&&await this.authenticateCustomerId(w)){const E=((B=(d=this.customer)==null?void 0:d.bundleStakeholders)==null?void 0:B.find(m=>{var f,Q;return(Q=(f=m.bundle)==null?void 0:f.transactions)==null?void 0:Q.some(D=>D.id===t)}))||((C=(h=this.customer)==null?void 0:h.stakeholders)==null?void 0:C.find(m=>{var f;return((f=m.transaction)==null?void 0:f.id)===t}));if(E)return Promise.resolve({success:!0,stakeholderType:E.type})}}const c=(await e.query({query:Ji,errorPolicy:"all",variables:{id:a.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${a.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:a.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=N.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),N.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const a=(await F.getShadowGraphqlClient().query({query:ea,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return a.id?a.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var A,a;const e=(a=(A=this.customer)==null?void 0:A.stakeholders)==null?void 0:a.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=F.getShadowGraphqlClient(),a=(await e.query({query:ea,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!a.id){const r=(s=(await e.mutate({mutation:mr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!r)throw new Error("Unable to create customer.");return this.storeCustomer(r),this.customer=r,{customer:r,isAuthenticated:!1}}this.storeCustomer(a);const i=await this.authenticateCustomerId(a.id);return{customer:this.customer||a,isAuthenticated:i}}getCustomer(){return this.customer}async authenticateCustomerId(t){var o;const e=F.getShadowGraphqlClient(),A=N.getMap("customerTokens");if(!(A!=null&&A.has(t)))return!1;const a=A.get(t);if(!a)return!1;const s=(o=(await e.mutate({mutation:fr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{loginToken:a}})).data)==null?void 0:o.customerAuthenticate;return s?(this.storeCustomer(s),OA(a),this.customer=s,!0):!1}async generateVerificationCode(t){await F.getShadowGraphqlClient().mutate({mutation:Qr,variables:{emailAddress:t}})}async verifyCode(t,e){var i,s;const a=(i=(await F.getShadowGraphqlClient().mutate({mutation:pr,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t,verificationCode:e}})).data)==null?void 0:i.customerVerifyCode;if(a!=null&&a.loginToken){if(!((s=a.partner)!=null&&s.id))throw new Error(`Unable to find customer: ${t}`);const o=N.getMap("customerTokens")||new Map;return o.set(a.id,a.loginToken),N.setMap("customerTokens",o),this.storeCustomer(a),OA(a.loginToken),this.customer={...a,loginToken:void 0},!0}return!1}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await F.getShadowGraphqlClient().query({query:Dr,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,A){var c,l,g,d,B;const i=(g=(await F.getShadowGraphqlClient().mutate({mutation:po(((l=(c=A==null?void 0:A.graphql)==null?void 0:c.productCollection)==null?void 0:l.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((h,C)=>({key:h[0],value:h[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:g.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=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 r=new Oe(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(B=(d=A==null?void 0:A.graphql)==null?void 0:d.productCollection)==null?void 0:B.eagerFetchProducts});return await r.getInitializationPromise(),r}async getExistingBundle(t,e,A,a){var w,u,E,m,f,Q,D,I,y,x,Y;const i=N.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),r=((w=Object.entries(localStorage).find(([P,v])=>P.startsWith("CognitoIdentityServiceProvider")&&P.endsWith("idToken")))==null?void 0:w[0])||"",c=localStorage.getItem(r),l={};c&&!me(c)&&(l.Authorization=`Bearer ${c}`);const g={bundleOwnerId:s,...l,...(u=a==null?void 0:a.graphql)==null?void 0:u.additionalHeaders},d=await F.getShadowGraphqlClient().query({query:Eo(((m=(E=a==null?void 0:a.graphql)==null?void 0:E.productCollection)==null?void 0:m.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:g}});if(!((f=d.data)!=null&&f.bundles)||((Q=d.data)==null?void 0:Q.bundles.length)===0||!((D=d.data)!=null&&D.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const B=(I=d.data)==null?void 0:I.bundles[0],h=N.getMap("bundlePartnerIds")||new Map;h.set(B.id,B.partner.id),N.setMap("bundlePartnerIds",h);const C=new Oe(this,B,e,A,s,{additionalHeaders:(y=a==null?void 0:a.graphql)==null?void 0:y.additionalHeaders,eagerFetchProducts:(Y=(x=a==null?void 0:a.graphql)==null?void 0:x.productCollection)==null?void 0:Y.eagerFetchProducts,existingGlobalPropertyState:d.data.globalPropertyState});return await C.getInitializationPromise(),C}async duplicateBundle(t,e,A,a){var w,u,E,m,f,Q,D,I;const i=(w=N.getMap("bundleOwnerIds"))==null?void 0:w.get(t),o=((u=Object.entries(localStorage).find(([y,x])=>y.startsWith("CognitoIdentityServiceProvider")&&y.endsWith("idToken")))==null?void 0:u[0])||"",r=localStorage.getItem(o),c={};r&&!me(r)&&(c.Authorization=`Bearer ${r}`);const l={bundleOwnerId:i,...c,...(E=a==null?void 0:a.graphql)==null?void 0:E.additionalHeaders},d=(Q=(await F.getShadowGraphqlClient().mutate({mutation:Do(((f=(m=a==null?void 0:a.graphql)==null?void 0:m.productCollection)==null?void 0:f.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:A},context:{headers:l},fetchPolicy:"no-cache"})).data)==null?void 0:Q.bundleDuplicate;if(!(d!=null&&d.id))throw new Error("Unable to duplicate bundle");const B=N.getMap("bundlePartnerIds")||new Map;B.set(d.id,d.partner.id),N.setMap("bundlePartnerIds",B);const h=N.getMap("bundleOwnerIds")||new Map;h.set(d.id,d.bundleOwnerId),N.setMap("bundleOwnerIds",h);const C=new Oe(this,d,void 0,void 0,d.bundleOwnerId,{eagerFetchProducts:(I=(D=a==null?void 0:a.graphql)==null?void 0:D.productCollection)==null?void 0:I.eagerFetchProducts});return await C.getInitializationPromise(),C}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...A}=t;return(await F.getShadowGraphqlClient().query({query:ko(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 F.getShadowGraphqlClient().query({query:mo,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const A=t.data.customers[0].bundleStakeholders||[],a=N.getMap("bundlePartnerIds")||new Map;return A.forEach(s=>{var o,r;(o=s.bundle)!=null&&o.id&&((r=s.bundle.partner)!=null&&r.id)&&a.set(s.bundle.id,s.bundle.partner.id)}),N.setMap("bundlePartnerIds",a),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),a=A[0];return e&&await a.getWorkflowManager().injectIntoPreviewService(e(a.getWorkflowManager().getWorkflow())),A[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new ct("No options provided!");const A=F.getShadowGraphqlClient(),a=async Q=>{var x,Y,P;if(Q.length===0)return[];const D=Q.map(v=>v.option.transactionId),I=await A.query({query:yi,variables:{ids:D},errorPolicy:"all",fetchPolicy:"no-cache"}),y=I.data.transactions;if(y.length!==Q.length){const v=((Y=(x=I.errors)==null?void 0:x[0])==null?void 0:Y.message)||"Unknown error";throw new ct(`Not all transactions were found: ${v}`)}return!this.activeIntegration&&((P=y[0].integrationProduct)!=null&&P.integration)&&(this.activeIntegration=Promise.resolve(y[0].integrationProduct.integration)),y.map((v,b)=>{var K;return{transaction:v,workflowId:v.workflowId,readOnly:((K=Q.find(j=>j.option.transactionId===v.id))==null?void 0:K.option.readOnly)??!1,index:Q[b].index}})},i=async Q=>{var y,x,Y;if(Q.length===0)return[];const D=await A.mutate({mutation:Fi,variables:{inputs:Q.map(P=>({integrationProductId:P.option.type==="integration"?P.option.integrationProductId:void 0,externalIntegrationId:P.option.type==="external"?P.option.externalIntegrationId:void 0,externalProductId:P.option.type==="external"?P.option.externalProductId:void 0,workflowId:P.option.workflowId,designName:P.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),I=(y=D.data)==null?void 0:y.transactionCreateMany;if(!I||I.length===0){const P=((Y=(x=D.errors)==null?void 0:x[0])==null?void 0:Y.message)||"Unknown error";throw new ct(`Failed to create transactions: ${P}`)}return I.map((P,v)=>({transaction:P,workflowId:P.workflowId,readOnly:!1,index:Q[v].index}))},s=t.map((Q,D)=>({option:Q,index:D})),o=s.filter(Q=>Q.option.type==="transaction"),r=s.filter(Q=>Q.option.type==="integration"||Q.option.type==="external"),c=UA(o,10),l=UA(r,10),g=(await Promise.all([...c.map(a),...l.map(i)])).flat(),d=[...new Set(g.map(Q=>Q.workflowId))],B=await HA(d,e),h=new Map(B.map(Q=>[Q.id,Q])),C=N.getMap("transactionOwnerIds")||new Map,w=g.map(async Q=>{var K;const{transaction:D,workflowId:I,readOnly:y,index:x}=Q,Y=h.get(I),P=t[x];!C.get(D.id)&&D.transactionOwnerId&&C.set(D.id,D.transactionOwnerId);const v=C.get(D.id)||void 0,b={product:D.product,transaction:D,layouts:[],singleVariantsRenderable:(K=P==null?void 0:P.workflowConfiguration)==null?void 0:K.singleVariantsRenderable,stateMutationFunc:y?async()=>{throw new L("State mutation is forbidden in read only mode!")}:async j=>this.updateTransactionState({...j,context:{transactionOwnerId:v,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),readOnly:y,workflow:Y,isReloadedTransaction:P.type==="transaction"};if(P.type==="transaction"&&D.workflowState){const j=JSON.parse(D.workflowState);b.layouts=Object.values(j.layouts||{}).map(At=>At.layout),await XA(j),b.reloadedState=j}else if(!y&&P.workflowState){const j=JSON.parse(P.workflowState);b.layouts=Object.values(j.layouts||{}).map(At=>At.layout),await XA(j),b.reloadedState=j}else b.layouts=Sr(b.transaction,b.workflow);return b.renderableContextService=new sr(b.layouts),b.delayWorkflowStateSync=!0,{experienceOptions:b,index:x,options:P}}),u=await Promise.all(w);N.setMap("transactionOwnerIds",C);const m=u.sort((Q,D)=>Q.index-D.index).map(async Q=>{const{experienceOptions:D,options:I}=Q,y=new Dn(this,D);return await y.getWorkflowManager().getInitializationPromise(),I.type!=="transaction"&&this.customer&&await y.attachCustomerDetails({email:this.customer.emailAddress}),y}),f=await Promise.all(m);return f.forEach(Q=>Q.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),f}storeCustomer(t){const e=N.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),N.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t){var i,s;const a=(i=(await F.getShadowGraphqlClient().query({query:Pi,variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:i.integrationProducts;if(!a||a.length===0||!((s=a[0])!=null&&s.id))throw new Error("Integration product not found.");return new sA(a[0])}async getIntegrationProductFromExternalIds(t,e){var s;const i=(s=(await F.getShadowGraphqlClient().query({query:vi,variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProductFromExternalIds;if(!(i!=null&&i.id))throw new Error("Integration product not found.");return new sA(i)}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,a=await F.getShadowGraphqlClient().query({query:Yi,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:A}});if(!a.data.transactions||a.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return a.data.transactions[0].transactionShareActions}}const Nn=async n=>(await F.getShadowGraphqlClient().query({query:Oi,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":n}}})).data.currentIntegration,Yr=async n=>{const e=await F.getShadowGraphqlClient().query({query:xi,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:n}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Pr=async(n,t)=>{var A;return(A=(await F.getShadowGraphqlClient().query({query:Li,errorPolicy:"all",variables:{themeConfigurationId:n,themeInstallId:t}})).data)==null?void 0:A.marketplaceThemeInstallConfiguration},vr=async n=>{var e,A,a;return(a=(A=(e=(await F.getShadowGraphqlClient().query({query:ji,errorPolicy:"all",variables:{id:n}})).data)==null?void 0:e.bundles)==null?void 0:A[0])==null?void 0:a.marketplaceThemeInstallConfiguration},Nr=async n=>{var e,A,a;return(a=(A=(e=(await F.getShadowGraphqlClient().query({query:zi,errorPolicy:"all",variables:{id:n}})).data)==null?void 0:e.transactions)==null?void 0:A[0])==null?void 0:a.marketplaceThemeInstallConfiguration};class kr{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 kn=(n=>(n.SelectFrame="SelectFrame",n.SelectImage="SelectImage",n.Position="Position",n))(kn||{});class Rn extends et{constructor(t,e,A){var a;super(t,e,A),this.frameService=(a=this.manager.getStepSpecificServices(this.getId()))==null?void 0:a.frameService}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ot.selectVariant(this.step,t.getResource(),e,this.manager,A=>this.setUpdateState(A))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,A=!0){var a;if(await ot.selectImage(this.step,t,this.manager,A),e){const i=((a=this.manager.getStepStorage(this.step.stepName))==null?void 0:a.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(fe.BackgroundRemover)}async canRemoveBackground(){var t,e,A,a;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((a=(A=this.frameService)==null?void 0:A.getImageData())!=null&&a.svg)}async removeBackgroundFromImageSelection(t=!0){var i;if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const A=await G.removeBackgroundFromAsset(e);t&&await ot.selectImage(this.step,A,this.manager,!1);const a=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...a,backgroundRemovedAssetKey:A.key,useOriginalAsset:!t}}),A}changeColors(t){ot.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?ot.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 it(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ot.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,A,a){return a&&a.length>1&&t===void 0?"SelectFrame":e||A||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){var e,A;const t=(A=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:A.originalAssetKey;if(t)return G.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 G.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var a;const e=((a=this.getFrameStepStorage())==null?void 0:a.framePatternData)||{};if(e.useOriginalAsset===t)return;const A=await this.getOriginalImageSelection();if(!A)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(A,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const Rr=p.gql`
|
|
3350
3350
|
query GetLoggedInCustomer($email: String!) {
|
|
3351
3351
|
customer(emailAddress: $email) {
|
|
3352
3352
|
id
|