@spiffcommerce/core 14.3.0 → 14.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/main.js CHANGED
@@ -467,7 +467,7 @@ var t=require("@apollo/client"),e=require("lodash.clonedeep"),i=require("react/j
467
467
  workflowState
468
468
  }
469
469
  }
470
- `,Gs=t=>{const e=[];for(const i of t.steps)switch(i.type){case si.DigitalContent:i.data.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case si.Frame:const t=i.data;t.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),t.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case si.Illustration:const A=i.data;A.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),A.varyColors&&A.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Colors});break;case si.Material:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Model:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Picture:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Question:i.data.varySelections&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selections});break;case si.Shape:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Text:const n=i.data;n.varyText&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Text}),n.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),n.varyColor&&n.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Color})}return e},Ts=[si.SilentIllustration,si.ProductOverlay],Os=async(t,e,i)=>{const A=[];t.introduction&&A.push({name:"Introduction",title:t.name,renderableSteps:[{type:si.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const i of t.steps){if(e.bulkScene){let t=!1;switch(i.type){case si.DigitalContent:i.data.varyUpload&&(t=!0);break;case si.Frame:{const e=i.data;!e.varyUpload||!e.varySelection&&i.option||(t=!0)}break;case si.Illustration:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case si.Material:i.data.varySelection&&(t=!0);break;case si.Model:i.data.varySelection&&(t=!0);break;case si.Picture:i.data.varySelection&&(t=!0);break;case si.Question:i.data.varySelections&&(t=!0);break;case si.Shape:i.data.varySelection&&(t=!0);break;case si.Text:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const n=Js(i.stepName,t.stepGroups);if(n){const t=A.find((t=>t.name===n.name));t?Ts.includes(i.type)?t.silentSteps.push(i):t.renderableSteps.push(i):A.push({name:n.name,title:n.name,renderableSteps:Ts.includes(i.type)?[]:[i],silentSteps:Ts.includes(i.type)?[i]:[]})}else A.push({name:i.stepName,title:i.stepTitle,renderableSteps:Ts.includes(i.type)?[]:[i],silentSteps:Ts.includes(i.type)?[i]:[]})}if(e.bulkScene){const n=i?.product?.bulkConfiguration;A.push({name:"Bulk",title:n?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:si.Bulk,stepName:"Bulk",stepTitle:n?.stepTitle??e.bulkSceneTitle,helpText:n?.helpText,data:{aspects:Gs(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&A.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:si.Finish,stepName:"Finish",stepTitle:e.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),A},Js=(t,e)=>e.find((e=>e.stepNames.includes(t))),Ls=(t,e)=>(t.conditions||[]).every((t=>{const i=e[t.targetStepName];if(i&&i.selectedVariants){const e=i.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),zs=(t,e)=>t.map((t=>((t,e)=>{const i={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Ls(t,e))),silentSteps:t.silentSteps.filter((t=>Ls(t,e)))};return 0===i.silentSteps.length&&0===i.renderableSteps.length?null:i})(t,e))).filter((t=>null!==t)),js=async(t,e)=>{const i=zs(t,e),A=[];for(const t of i)for(const e of t.renderableSteps)if(e.type===si.Model||e.type===si.Material||e.type===si.Picture||e.type===si.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&A.push(e.stepName)}else A.push(e.stepName);const n=i.filter((t=>t.renderableSteps.filter((t=>A.includes(t.stepName))).length>0));for(const t of n)t.renderableSteps=t.renderableSteps.filter((t=>A.includes(t.stepName)));return n};function Vs(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function Ks(t,e,i,A){const n=i.width*t.zoom,r=i.height*t.zoom;if(A){const A=t,n=Math.max(e.width/i.width,e.height/i.height);A.zoom=Math.max(n,t.zoom);const r=i.width*A.zoom,a=i.height*A.zoom;return A.x=Ws(t.x,e.width-r,0),A.y=Ws(t.y,e.height-a,0),A}const a=t;return a.x=Ws(a.x,-n,e.width),a.y=Ws(a.y,-r,e.height),a}function Ws(t,e,i){return Math.min(Math.max(t,e),i)}class Xs{constructor(t){Vs(this,"offsets",void 0),Vs(this,"forceImageCover",void 0),Vs(this,"targetElements",void 0),Vs(this,"imageData",void 0),Vs(this,"frameData",void 0),Vs(this,"_debouncedUpdateFrameOffsets",void 0),Vs(this,"minZoomScale",[.03]),Vs(this,"maxZoomScale",[20]),Vs(this,"onFrameDataChangeListeners",void 0),Vs(this,"onZoomChangeListeners",void 0),Vs(this,"workflowManager",void 0),Vs(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=F(I)(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback((async t=>{if(t){const e=t;if(e.currentFrameSources){let t=!1;for(let i=0;i<e.currentFrameSources.length;i++){const A=e.currentFrameSources[i],n=await kn(A);F(C)(n,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[i]=n,t=!0)}t&&(this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){t?t.forEach(((e,i)=>{const A=Yn.get(e);A&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[i]=A)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,i,A){if(this.imageData&&this.offsets&&this.frameData){this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length));const n=this.frameData.map(((A,n)=>{const r=(e[n]-this.offsets[n].x)/this.offsets[n].zoom,a=(i[n]-this.offsets[n].y)/this.offsets[n].zoom;return{x:e[n]-r*t[n],y:i[n]-a*t[n],zoom:this.imageData.width*t[n]/this.imageData.width}}));this.updateOffsets(n,A),this.onZoomChangeListeners.forEach((e=>e(t)))}}setPatternData(t){this.imageData=t,t&&this.frameData&&(this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,i){const A=this.imageData;if(!A||!this.frameData)return;if(this.frameData.length!==t.length)throw new ar("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,i)=>t[i].x!==e.x||t[i].y!==e.y||t[i].zoom!==e.zoom))||i?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,i)=>{this.offsets[i]=Ks(t[i],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,A,this.frameData,this.targetElements,e)):e&&e()}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,i,A,n){if(!i||0===i.length||i.some((t=>!t)))throw new ar("Frame data not set. This is a bug");if(!this.workflowManager)throw new ar("No workflow manager set, cannot update offsets.");const r=this.workflowManager.getCommandDispatcher();A.forEach(((i,A)=>{r(new wn(i,e,t[A]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),n&&n()}recalculateZoomLimits(t,e){this.minZoomScale.length===e.length&&this.maxZoomScale.length===e.length||(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach(((e,i)=>{const A=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[i]=A,this.maxZoomScale[i]=2.5*A):(this.minZoomScale[i]=A/10,this.maxZoomScale[i]=2.5*A)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,i)=>{this.offsets[i]=Hn(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function qs(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class Zs{constructor(t,e,i){qs(this,"configuration",void 0),qs(this,"layouts",void 0),qs(this,"product",void 0),qs(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new er(t);let i="";if(this.configuration.type===si.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),i=t,!t)throw new nr(this.configuration,"Couldn't find an asset for product overlay step")}const A=this.evaluateAssetType();if(A===ze.Image){const i=this.configuration.type===si.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!i)throw new Error("Undefined raster silent step source");const n={stepName:this.configuration.stepName,id:Te(),src:i,type:A,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,productOverlay:this.configuration.type===si.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:n.id,region:t},command:new an(n,e)}}{const n=this.configuration.type===si.SilentIllustration?this.configuration.data.asset?.fileLink:i,r=async()=>new Promise(((t,e)=>{n?Wi(n).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),a=await TA(await r()),s={stepName:this.configuration.stepName,id:Te(),cachedObjectURL:await Wn(a.svg),src:n,svg:a.svg,colors:a.colors,type:A,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,immutable:t.immutable,productOverlay:this.configuration.type===si.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new an(s,e)}}})),this.configuration=t,this.layouts=e,this.product=i||void 0}async trigger(){if(!this.configuration.data.regions)throw new nr(this.configuration,"Missing regions.");if(this.configuration.type===si.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===si.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new er(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===si.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?ze.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),ze.Illustration)}}const $s=async t=>{const e=`${wr.getServicesApiUrl()}/shortener`;try{const i=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await i.json()).shortUrl}catch(t){throw console.error(t),new cr("Failed to shorten URL, see console.")}};function _s(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class to{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(t){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,i,A=3e3,n=10){_s(this,"pollingId",void 0),_s(this,"attempts",void 0),_s(this,"interval",void 0),_s(this,"maxAttempts",void 0),_s(this,"predicate",void 0),_s(this,"onSuccess",void 0),_s(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=i,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=A,this.maxAttempts=n,this.poll()}}const eo=new class{async init(t,e,i){return i&&await this.reload(t,e,i),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],n,(async()=>{const i=A?.storage?.videoShortUrl,n=A?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:i,videoUrl:n})}))}async regenerateQRCode(t,e,i,A,n,r,a,s,o){if(e||""===i||""!==A)o(!1);else{const e=async()=>{const t=(await br([i]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},c=await new Promise(((t,i)=>{new to((async()=>!!(await e()).link),(async()=>{const i=await e();if(!i.link||!i.link)throw new Ar(i.asset);t({rel:"mpeg4",href:i.link})}),(()=>{i("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>s(new sn(t.id))));const l="http"===r.data.baseUrl.slice(0,4)?"":"https://",g=new URL(l+r.data.baseUrl);g.searchParams.append("video",btoa(JSON.stringify([c]))),g.pathname=g.pathname+("/"===g.pathname.slice(-1)?"":"/");const h=g.toString();if(h.length>=2e3)throw new cr("Cannot create QR code, URL too long.");const d=await $s(h);if(a(d),!r.data||!r.data.regions)throw new nr(r,"Missing regions.");const u=await this.regionElements(r),w=await this.command(d,u,n,r.stepName);w&&(w.command&&n.getCommandDispatcher()(w.command),w.followup&&await w.followup()),await n.setSelectionsAndElements(r.stepName,[],u,(async()=>{n.updateStorage(r.stepName,{videoShortUrl:d,videoUrl:A}),o(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:Te(),region:t})))}async command(t,e,i,A){const n=i.getLayouts(),r=`data:image/svg+xml;base64,${btoa(await(0,y.toString)(t,{type:"svg"}))}`,a=e.map((t=>{const e=t.region,i=n.find((t=>t.panelId===e?.panelId));if(!i&&e)throw new er(e);if(i&&!e)throw new Error("Region not found");if(!i||!e)throw new Error("Neither a region or layout found!");return new an({stepRegion:e,stepName:A,id:t.id,src:r,type:ze.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},i)}));return{command:new An(a),followup:async()=>{}}}};function io(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const Ao=new class{constructor(){io(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Nn(e);const i=t.asset;if(!i)throw new ir(t);const A=i.fileLink;if(A)return Wi(A);throw new Ar(i)}))}async init(t,e,i){if(i)return await this.reload(t,e,i),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const i=t.option,A=Ur.getDefaultVariant(i);return A?this.selectVariantCommand(t,A,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const i=t.data.regions.map((t=>Nn(t)));e.updateStorage(t.stepName,{currentFrameSources:i})}if(A){const i=async()=>{const i=A.storage?.framePatternSrc,n=A.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:n,framePatternSrc:i}),i){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,A),e.updateMetadata(t.stepName,{image:i}),e.updateStorage(t.stepName,{framePatternSrc:i})}if(n?.some((t=>t.zoom))){const i=e.getStepSpecificServices(t.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");i.updateOffsets(n)}e.setMandatoryFulfilled(t.stepName,!0)};if(A.selectedVariants&&A.selectedVariants.length>0){const r=A.selectedVariants[0].id;if(t.option&&r){const A=t.option.variants?.find((t=>t.id===r));A&&await e.setSelectionsAndElements(t.stepName,[A],n,(async()=>{const n=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(A,t))));e.updateStorage(t.stepName,{currentFrameSources:n}),await i()}))}}else await e.setSelectionsAndElements(t.stepName,[],n,i)}}selectImage(t,e,i){i.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?i.addPoller(new to((async()=>{const t=(await Nr.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{Nr.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,i)}))}),(()=>{throw new cr("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,i)}async selectVariant(t,e,i,A,n){const r=await this.selectVariantCommand(t,e,i,A,n);r&&(r.command&&A.getCommandDispatcher()(r.command),r.followup&&await r.followup())}getCreateElementCommand(t,e,i,A){return new an({id:t,type:ze.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/A.frameData.width,scaleY:e.height/A.frameData.height,path:A.frameData.path,dataWidth:A.frameData.width,dataHeight:A.frameData.height,stepRegion:e,stepName:A.stepName,disablePlaceholder:A.disablePlaceholder,focalBlur:A.focalBlur,focalBlurStrength:A.focalBlurStrength,focalBlurRadius:A.focalBlurRadius,pattern:A.pattern,immutable:e.immutable},i)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const i=await Gn(t),A=i.width,n=i.height,r={src:t,width:A,height:n,aspect:A/n};bn.set(t,r),e.setPatternData(r)}else{const i=await Ki(t),A=await Sn(i),n={src:t,width:A.width,height:A.height,aspect:A.width/A.height};bn.set(t,n),e.setPatternData(n)}}async selectVariantCommand(t,e,i,A,n,r){const a=A.getStepSpecificServices(t.stepName)?.frameService;if(!a)throw new Error("Frame service unavailable, cannot load pattern!");const s=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));n&&n(!0);const o=await Promise.all(t.data.regions.map((async(e,n)=>{const r=await kn(s[n]),o=a.getImageData(),c=i.map((t=>new sn(t.id))),l=o?Hn(o,r):void 0,g=o?{id:Te(),src:o.src,x:l?.x||0,y:l?.y||0,width:o.width,height:o.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,h=Te(),d=A.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new er(e);return{command:this.getCreateElementCommand(h,e,d,{frameData:r,pattern:g,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:h,region:e},removeExistingCommands:c}}))),c=o.map((t=>t.command)),l=o.map((t=>t.removeExistingCommands)).flat();return{command:new An([...c,...l]),followup:async()=>{n&&n(!1),await A.setSelectionsAndElements(t.stepName,e?[e]:[],[...o.map((t=>t.regionEl))],(async()=>{if(A.updateStorage(t.stepName,{currentFrameSources:s}),r){const e=A.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(r,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const i=t.fileLink;if(i)return i;throw new Ar(t)}async loadPatternFromAsset(t,e,i){const A=this.patternSource(t),n=i.markUpdatePending(),r=i.getStepSpecificServices(e.stepName)?.frameService;if(!r)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,r),i.updateMetadata(e.stepName,{image:A}),i.updateStorage(e.stepName,{framePatternSrc:A}),i.markUpdateCompleted(n)}};const no=new class{async getIllustrationBody(t){return new Promise((e=>{Wi(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,i,A){return new an({stepRegion:e,stepName:A.stepName,colors:A.svg.colors,id:t,src:A.src,svg:A.svg.svg,cachedObjectURL:A.objectURL,type:ze.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},i)}getColors(t,e){const i=e.getRegionElements(t.stepName)||[];if(0===i.length)return[];try{return KA(i[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,i){const A=t.option;if(!A)return null;if(i)return this.reload(t,e,i);{const i=Ur.getDefaultVariant(A);if(i)return await this.selectVariantCommand(t,i,[],(()=>{}),e)}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(!r||!i)throw new Error("Required illustration variant no longer available");{const a=r.variants?.find((t=>t.id===i));if(a){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[a],i,(async()=>{e.updateMetadata(t.stepName,{colors:A.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const i=t.data.colorOption;return i&&i?i.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,i,A,n){const r={};for(const[t,e]of n.entries())r[t]={browserValue:e,spotColor:r[t]?.spotColor};const a=GA(t,e,i,r),s=await Wn(a),o=[];for(const t of A){for(const[e,i]of n.entries())o.push(new pn(t,e,i));o.push(new En(t,a,s))}return new An(o)}async changeColors(t,e,i,A,n){if(0===e.length)return;const r=KA(e[0].id,A().map((t=>t.layoutState))),a={...r.colors},s={};Object.entries(a).forEach((([t,e])=>{const i={browserValue:e.browserValue},A=e.spotColor;A&&(i.spotColor={profileName:A.profileName,namedColor:A.namedColor}),s[t]=i}));for(const[t,e]of n.entries())a[t]={browserValue:e,spotColor:a[t]?.spotColor},s[t]={browserValue:e};let o=Array.from(Object.values(a)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{o=o.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),i.updateMetadata(t.stepName,{colors:o});const l=new Map;if(Object.entries(a).forEach((([t,e])=>{l.set(t,e.browserValue)})),!r.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const g=await this.changeColorsCommand(r.svg,r.width,r.height,e.map((t=>t.id)),l);i.updateStorage(t.stepName,{colors:s}),i.getCommandDispatcher()(g)}async selectVariant(t,e,i,A,n){const r=await this.selectVariantCommand(t,e,i,A,n);r&&(r.command&&n.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantCommand(t,e,i,A,n){if(!t.data||!t.data.regions)throw new nr(t,"Missing regions.");A(!0);const r=i.map((t=>new sn(t.id)));n.setMandatoryFulfilled(t.stepName,!1);const a=e.asset;if(!a)throw new ir(e);const s=a.fileLink;if(!s)throw new Ar(a);const o=await TA(await this.getIllustrationBody(s)),c=await Wn(o.svg),l=t.data.regions.map((e=>{const i=n.getLayouts().find((t=>t.panelId===e.panelId));if(!i)throw new er(e);const A=Te();return{regionElement:{id:A,region:e},command:this.getCreateElementCommand(A,e,i,{stepName:t.stepName,src:s,objectURL:c,svg:o})}})),g=[...l.map((t=>t.command)),...r];let h=Array.from(Object.values(o.colors)).map((t=>t.browserValue));const d=t.data.colorOption;return d&&d.variants?.forEach((t=>{h=h.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),n.updateMetadata(t.stepName,{colors:h}),{command:new An(g),followup:async()=>{await n.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{n.setMandatoryFulfilled(t.stepName,!0),A(!1)}))}}}};const ro=new class{async init(t,e,i){const A=t.option;if(!A)throw new tr(t);if(i)await this.reload(t,e,i);else{const i=Ur.getDefaultVariant(A);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(!r)throw new tr(t);if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(i){const A=r.variants?.find((t=>t.id===i));if(A){const i=A.material,a=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],a,(async()=>{const A=e.getModelContainer();if(A){const n=t.data.targetMaterials.map((t=>A.applyMaterialVariant(t,r.id||"",i||{})));Promise.all(n).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantLambda(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i,A){const n=i.getModelContainer();A(!0);const r=e.material;if(!r)throw A(!1),new ir(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{n&&t.data.targetMaterials.forEach((e=>{t.option&&n.applyMaterialVariant(e,t.option.id||"",r)})),i.setMandatoryFulfilled(t.stepName,!0)}finally{A(!1)}}))}}}};const ao=new class{async init(t,e,i){const A=t.option;if(!A)throw new tr(t);if(i)await this.reload(t,e,i);else{const i=Ur.getDefaultVariant(A);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const A=r.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{const i=e.getModelContainer();if(i&&t.option){const n=A.asset?.fileLink;if(!n)throw new ir(A);await i.applyModelVariant(t.option.id||"",{model:n,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantLambda(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i,A){A(!0);const n=e.asset?.fileLink;if(!n)throw new ir(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=i.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:n,contextService:i.getLayoutPreviewService()},t.data.replaceProductModel||!1),i.setMandatoryFulfilled(t.stepName,!0)}finally{A(!1)}}))}}}};const so=new class{async init(t,e,i){return i?(await this.reload(t,e,i),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],n,(async()=>{e.updateStorage(t.stepName,{text:A?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==A?.storage?.text)}))}async changeText(t,e,i,A,n){const r=await this.changeTextCommand(t,e,i,A,n);r&&(r.command&&i.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async changeTextCommand(t,e,i,A,n){const r=i.getRegionElements(t.stepName),a=i.getStepSpecificServices(t.stepName)?.module;if(!a)return console.error("Missing module."),null;const s=i.getProfanities();if(!this.validateInput(t,e,s,n))return i.setMandatoryFulfilled(t.stepName,!1),console.error(A),null;if(i.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;i.updateStorage(t.stepName,{text:e});const o=(e,A,n)=>{const r=n||Te(),a=i.getLayouts().find((t=>t.panelId===A.panelId));if(!a)return console.error(`Can not find layout for region: ${A.panelId}`),null;const s=[];return n&&s.push(new sn(r)),s.push(new an({stepRegion:A,stepName:t.stepName,colors:{},id:r,svg:e,type:ze.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable},a)),{id:r,region:A,command:new An(s)}};if(r.length>0){const t=r.map((t=>{if(!t.region)return null;const i=a.svgPrint(e,t.region);return o(i,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new An(t),followup:async()=>{}}}{const A=t.data.regions.map((t=>o(a.svgPrint(e,t),t))),n=A.filter((t=>!!t)).map((t=>t&&t.command));return{command:new An(n),followup:async()=>{const e=A.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await i.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,i,A){if(t.data&&t.data.maxLength){const i=t.data.maxLength;if(e.length>i)return A("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return A("Unsupported characters."),!1;const n=(0,x.split)(e.toLowerCase());for(const t of n)for(const e in i){if(t===i[e].toLowerCase().replace(/\s/g,""))return A("Blocked profanity."),!1}return A(""),!0}};const oo=new class{async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else if(A.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,A.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const A=r.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantCommand(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantCommand(t,e,i,A){const n=e.asset;if(!n)throw new ir(e);const r=n?.fileLink;if(!r)return console.error("No URL for picture!"),null;A(!0),i.setMandatoryFulfilled(t.stepName,!1);const a=i.getRegionElements(t.stepName).map((t=>new sn(t.id))),s=t.data.regions.map((e=>{const A=i.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new er(e);const n=Te();return{regionElement:{id:n,region:e},command:new an({stepName:t.stepName,stepRegion:e,id:n,src:r,type:ze.Image,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,preserveAspectRatio:"none"},A)}}));return{command:new An([...a,...s.map((t=>t.command))]),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],s.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),A(!1)}))}}}};const co=new class{async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else{const i=A.variants;if(Ur.getDefaultVariant(A)){const n=i?.find((t=>t.id===A.defaultVariant?.id));return this.selectVariantLambda(t,n?.id||"",e)}}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(n&&i){const A=n.variants?.find((t=>t.id===i));A&&await e.setSelectionsAndElements(t.stepName,[A],[])}}}async selectVariant(t,e,i){await i.getInitializationPromise();const A=await this.selectVariantLambda(t,e,i);A&&(A.command&&i.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async selectVariantLambda(t,e,i){const A=t.option;if(!A)return null;const n=A.variants;if(!n)return null;const r=n.length>1?n.find((t=>t.id===e)):n[0];if(!r)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[r],[],(async()=>{i.setMandatoryFulfilled(t.stepName,!0)}))}}}};const lo=new class{async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}async init(t,e,i){const A=t.option;if(!A)throw new tr(t);if(!i){const i=Ur.getDefaultVariant(A);if(!i)return null;const n={fill:i.color,stroke:i.color,variant:i};return this.selectVariantCommand(t,n,[],e)}return await this.reload(t,e,i),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const A=r.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{e.updateStorage(t.stepName,{colour:A.color||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantCommand(t,e,i,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantCommand(t,e,i,A){const n=A.getLayouts();if(i.length>0){const r=t=>{const i=t.region;if(!n.find((t=>t.panelId===i?.panelId)))throw new er(i);const A=e.variant?.color;return A?new pn(t.id,"spiff-fill-shape",A):(console.error("Failed to change color."),null)},a=i.map(r).filter((t=>!!t));return{command:new An(a),followup:async()=>{await A.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],i),A.updateStorage(t.stepName,{colour:e.fill||""})}}}{const i=i=>{const A=n.find((t=>t.panelId===i.panelId));if(!A)throw new er(i);const r=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${e.variant?.color}"\n />\n </svg>\n `,a={};a["spiff-fill-shape"]={browserValue:e.variant.color};const s=Te();return{id:s,region:i,command:new an({stepRegion:i,stepName:t.stepName,colors:a,id:s,svg:r,type:ze.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,immutable:i.immutable,excludeFromExport:t.data.excludeFromPrint},A)}},r=t.data.regions.map(i),a=r.filter((t=>!!t)).map((t=>t?.command)),s=r.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new An(a),followup:async()=>{await A.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],s,(async()=>{A.updateStorage(t.stepName,{colour:e.fill||""})}))}}}}};function go(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class ho extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=ho.name}}const uo=["‘","’","“","”","\n"];class wo extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=wo.name}}const Bo=new class{constructor(){go(this,"cachedColors",new Map),go(this,"filterUnsupportedCharacters",((t,e)=>{let i=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const A=[],n=e?cA(e):void 0;if(n){const t=i.split("").filter((t=>!uo.includes(t))).join(""),e=t.split("").map((t=>n.getFont().charToGlyph(t)));for(let i=0;i<e.length;i++){".notdef"===e[i].name&&A.push(String.fromCharCode(t.charCodeAt(i)))}}for(let t=0;t<A.length;t++)i=i.replaceAll(A[t],"");return i})),go(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),go(this,"getErrorsForText",((t,e,i)=>{const A=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&A.push({localizationKey:"workflow.steps.text.characterLimit"});const n=i.getProfanities(),r=(0,x.split)(t.toLowerCase());for(const t of r)for(const e in n){if(t===n[e].toLowerCase().replace(/\s/g,"")){A.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&A.push({localizationKey:"workflow.steps.text.multipleLines"}),A}))}async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else{const i=this.getDefaultImageFillVariant(t.data),n=i?.asset?.fileLink,r=n?await Un(n):void 0,a=r?{src:r.src,height:r.height,width:r.width,scale:t.data.imageFillScale||1}:void 0;e.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:a}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:i?.name});const s=Ur.getDefaultVariant(A);if(s)return this.selectVariantCommand(t,s,{},[],e,(()=>{}),(()=>{}),a)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>KA(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const i=t.data.colorOption;if(i){const e=i.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,i,A){if(!t.data||!t.data.regions)return;const n=A.getCommandDispatcher();e.variant?A.updateMetadata(t.stepName,{color:e.variant.name}):A.updateMetadata(t.stepName,{color:e.fill});const r=t.data.colorOption,a=r?this.createTextFillSpotColor(r,e.variant):void 0;r?A.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:r.colorProfile?.key}):A.updateStorage(t.stepName,{color:e.fill});for(const t of i){if(!e.fill)throw new Error("Fill not set on new color selection!");n(new cn(t.id,e.fill,a))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const i=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(i.map((async e=>{const i=await Un(e);return{src:e,width:i.width,height:i.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,i,A){if(!t.data||!t.data.regions)return;const n=A.getCommandDispatcher(),r=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));A.updateMetadata(t.stepName,{fillImage:r?.name}),A.updateStorage(t.stepName,{fillImage:e});for(const t of i){n(new ln(t.id,e))}}getProcessedInput(t,e,i){const A=i?t:this.injectReplaceableText(t,e);return QA(A,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,i,A){const n=A.getStepStorage(i.stepName),r=this.getProcessedInput(t,i.data,!!n.customiseAllText),a={command:void 0,helperText:"",errors:this.getErrorsForText(t,i,A)};if(a.errors.length>0)return a.helperText=a.errors[0].localizationKey,a;const s=(i.data.maxLength-r.length).toString();a.helperText=`${s} characters remaining`;const o=A.getTransaction().bulk&&i.data.varyText||!1,c=[],l=new Map,g=new Map;for(const t of e){if(!t.fontData)throw new ar("Failed to resolve font data for text.");const[e,A]=Ln(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[r],{size:i.data.size,minSize:i.data.minSize,maxSize:i.data.maxSize});l.set(t.id,e),g.set(t.id,A);const n=i.data.curved?r:(A||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,i.data,t.id,n,o))}if(!i.data.curved&&e.length>0){if(!Array.from(g.values()).every((t=>t)))return a.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),a}return A.updateStorage(i.stepName,{text:t}),A.updateMetadata(i.stepName,{text:r}),n.defaultCleared&&A.setMandatoryFulfilled(i.stepName,!0),a.command=new An(c),a.command.varying=o,a}async selectVariant(t,e,i,A,n){const r=await this.selectVariantCommand(t,e,i.getStepStorage(t.stepName)||{},i.getRegionElements(t.stepName),i,A,n);r&&(r.command&&i.getCommandDispatcher()(r.command),r.followup&&await r.followup())}createTextFillSpotColor(t,e){const i=t.colorProfile;if(i){const t=(i.name||"").replace(/\s/g,"-"),A=t.lastIndexOf("/"),n=t.slice(A+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:n,namedColor:e.namedColor}}}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const a=r.variants?.find((t=>t.id===i));if(a){const i=await this.fontDataFromVariant(a),r=n.map((t=>({id:t.id,region:t.stepRegion}))),s=A.storage?.color,o=A.storage?.text;await e.setSelectionsAndElements(t.stepName,[a],r,(async()=>{e.updateMetadata(t.stepName,{color:s,text:o}),e.updateStorage(t.stepName,{text:o,inputText:o});const A=n.map((t=>new dn(t.id,i))),r=new An(A);e.getCommandDispatcher()(r),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=Bo.updateInputText(o||"",n,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return Ur.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return Ur.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return Ur.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ir(t);const i=e.fileLink;if(!i)throw new Ar(e);return{assetUrl:i,name:(await sA(i)).names.fullName.en}}async selectVariantCommand(t,e,i,A,n,r,a,s){const o=n.markUpdatePending(),c=await this.fontDataFromVariant(e);if(A.length>0){const l=A.map((t=>new dn(t.id,c)));if(s){const t=A.map((t=>new ln(t.id,s)));l.push(...t)}const g=await this.changeInputTextWithRegion(t,t.data.size||30,c,i.text||"",i,n,!!i.customiseAllText,r,a);g&&l.push(g);return{command:new An(l),followup:async()=>{n.markUpdateCompleted(o),await n.setSelectionsAndElements(t.stepName,[e],A)}}}{const A=await this.createTextboxRegions(t.stepName,e,t.data,c,i,n),l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A[0]?.newElement.input||i.text||t.data.defaultText||"",i,n,!!i.customiseAllText,r,a),g=A.flatMap((t=>t.commands));if(s){const t=A.map((t=>new ln(t.regionElement.id,s)));g.push(...t)}l&&g.push(l);return{command:new An(g),followup:async()=>{n.markUpdateCompleted(o)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,i,A,n,r){if(!i||!i.regions)throw new Error("Step data not supplied");const a=r.getTransaction().bulk&&i.varyText||!1,s=a?"":n.text||i.defaultText||"",o=this.getProcessedInput(s,i,!1),c=await Promise.all(i.regions.map((async e=>{const c=r.getLayouts().find((t=>t.panelId===e.panelId)),l=Te();try{if(!c)throw new wo("Failed to find layout for region: "+e.panelId);const g=i.colorOption;let h;if(g&&g.variants){const e=g.variants.find((t=>t.id===g.defaultVariant?.id))||g.variants[0];h=this.createTextFillSpotColor(g,e),r.updateStorage(t,{colorProfileAssetKey:g.colorProfile?.key})}const d=await this.getDefaultColor(i),u=d||"#000000",w={stepRegion:e,stepName:t,align:this.textAlign(i),fill:n.color?n.color:u,fontSize:i.size||30,fontData:A,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:o,input:s,type:ze.Textbox,vertical:i.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:i.verticalAlign||"middle",curved:i.curved,paths:i.paths,fillSpotColorDefinition:h},B=[],p=new Map,E=new Map;if(!w.fontData)throw new ar("Failed to resolve font data for text.");const[m,f]=Ln(w.fontSize,w.fontData,{left:w.x,top:w.y,width:w.width,height:w.height,rotation:w.rotation,panelId:""},[o],{size:i.size,minSize:i.minSize,maxSize:i.maxSize});p.set(w.id,m),E.set(w.id,f);const C=i.curved||i.vertical?o:(f||[]).join("\n");B.push(this.generateTextChangeCommandsForRegion(m,i,w.id,C,a));const Q=new an(w,c);return Q.varying=a,{regionElement:{id:l,region:e},commands:[Q,...B],newElement:w,fontData:A}}catch(t){throw console.log(t),new ho("Error adding font to region")}}))).catch((t=>{throw t instanceof ho?(ca.setLatestToast("Failed to load font.",Eo.Error),t):t instanceof wo?t:new Error(t)}));return await r.setSelectionsAndElements(t,[e],c.map((t=>t.regionElement)),(async()=>{r.updateMetadata(t,{text:s}),r.updateStorage(t,{text:s})})),c}generateTextChangeCommandsForRegion(t,e,i,A,n){const r=[],a=new Bn(i,A);if(a.varying=n,r.push(a),!e.size){const e=new gn(i,t);e.varying=n,r.push(e)}const s=new An(r);return s.varying=n,s}async changeInputTextWithRegion(t,e,i,A,n,r,a,s,o,c){const l=(A||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),g=this.getProcessedInput(l,t.data,a),h=r.getRegionElements(t.stepName),d=new Map,u=new Map;for(const A of h)if(A.region){const[n,r]=Ln(e,i,A.region,[g],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(A.id,n),u.set(A.id,r)}const w=(()=>{if(t.data&&t.data.maxLength&&g.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=r.getProfanities(),i=(0,x.split)(g.toLowerCase());for(const t of i)for(const i in e){if(t===e[i].toLowerCase().replace(/\s/g,""))return s(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(g.includes("\n")||g.includes("\r")))return s(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(u.values()).every((t=>t)))return s(!0),{error:"Does not fit."}}return s(!1),{info:(t.data.maxLength-g.length).toString()}})();if(w.error)return void o(w.error);if(o(`${w.info} characters remaining`||""),c)return;r.updateStorage(t.stepName,{text:l}),r.updateMetadata(t.stepName,{text:this.injectReplaceableText(l,t.data)});const B=r.getTransaction().bulk&&t.data.varyText||!1;n.defaultCleared&&r.setMandatoryFulfilled(t.stepName,!0);const p=[];for(const e of h){const i=t.data.curved?g:(u.get(e.id)||[]).join("\n");p.push(this.generateTextChangeCommandsForRegion(d.get(e.id)||1,t.data,e.id,i,B))}const E=new An(p);return E.varying=B,E}};function po(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}let Eo;var mo;(mo=Eo||(Eo={})).Error="Error",mo.Warning="Warning",mo.Info="Info";class fo extends Ja{constructor(t){super(),po(this,"update",void 0),po(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Co{constructor(t,e,i,A,n,r,a,s,o,c,l=!1,g,h=!1){po(this,"reloadedState",void 0),po(this,"transaction",void 0),po(this,"ownerCustomer",void 0),po(this,"updateTransaction",void 0),po(this,"confirmedDesign",void 0),po(this,"editedSteps",void 0),po(this,"informationResults",void 0),po(this,"layouts",void 0),po(this,"mandatorySteps",void 0),po(this,"pendingUpdates",void 0),po(this,"selectionCost",void 0),po(this,"workflow",void 0),po(this,"stepSpecificServices",void 0),po(this,"previewService",void 0),po(this,"profanityFilter",void 0),po(this,"pollers",void 0),po(this,"commandContext",void 0),po(this,"stepElements",void 0),po(this,"stepInitialised",void 0),po(this,"stepMetadata",void 0),po(this,"stepSelections",void 0),po(this,"storage",void 0),po(this,"confirmCallbacks",void 0),po(this,"editedCallbacks",void 0),po(this,"elementsCallbacks",void 0),po(this,"informationResultCallbacks",void 0),po(this,"initCallbacks",void 0),po(this,"makingAdjustmentsCallback",void 0),po(this,"mandatoryCallbacks",void 0),po(this,"metadataCallbacks",void 0),po(this,"selectionCallbacks",void 0),po(this,"stepSpecificStorageCallbacks",void 0),po(this,"storageCallbacks",void 0),po(this,"currentVariationRecordCallbacks",void 0),po(this,"variationRecordCallbacks",void 0),po(this,"allScenes",void 0),po(this,"product",void 0),po(this,"invalidModelVariants",void 0),po(this,"currentAdjustingStepId",void 0),po(this,"renderableContextService",void 0),po(this,"workflowStatePromiseQueue",new La(1)),po(this,"variationRecords",[]),po(this,"currentVariationRecord",void 0),po(this,"initializationPromise",void 0),po(this,"initialized",!1),po(this,"readOnly",!1),po(this,"modelContainer",void 0),po(this,"isReloadedTransaction",!1),po(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,i]of e)i.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=n,this.commandContext=A,this.reloadedState=c,this.transaction=r,this.readOnly=l,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=e,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=a,this.previewService=s,this.modelContainer=g,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=o,this.currentVariationRecord=null,this.isReloadedTransaction=h,this.initializationPromise=this.initializeDefaultWorkflowState(t,r),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((t=>{throw console.error(t),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>{this.updateStateWithServer(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,e){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await Os(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const i=zs(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:A,commands:n}=await this.stepElementsForIntroducedSilentSteps(i,!!this.reloadedState);this.commandContext.apply(new An(n),!0),this.stepElements={...this.stepElements,...A},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,i=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),i&&this.modelContainer?.executeAnimation(i)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const e={...t,recordNumber:this.variationRecords.reduce(((t,e)=>e.recordNumber>t?e.recordNumber:t),0)+1};return this.variationRecords.push(e),this.onVariationRecordsChange(),e}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((e=>e.recordNumber!==t)),this.variationRecords.forEach(((t,e)=>t.recordNumber=e+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,e=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(e||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(t){this.variationRecords=t,this.onVariationRecordsChange(),0===t.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(t[0])}setCurrentVariationRecord(t){if(this.currentVariationRecord=t,this.onCurrentVariationRecordChange(),t){const e=this.variationRecords.find((e=>e.recordNumber===t.recordNumber));e&&(e.values=t.values,this.onVariationRecordsChange())}}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addCurrentVariationCallback(t){t(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(t)}addVariationRecordsCallback(t){t(this.variationRecords),this.variationRecordCallbacks.push(t)}addPoller(t){this.pollers.push(t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((t=>t.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t)}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach((e=>{const i=this.stepSelections[e.stepName];i&&i.selectedVariants&&i.selectedVariants.length>0&&(t[e.stepName]={selections:i.selectedVariants})})),t}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach((t=>{e[t]=!0})),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((e=>e!==t))}markUpdatePending(){const t=Te();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t){if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const e=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()});this.setModelContainer(e),await e.getInitializationPromise(),this.render3DScene()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}async updateStorage(t,e){const i={...this.storage,[t]:{...this.storage[t],...e}};if(!F(C)(i,this.storage)){this.storage=i;const e=new $A(this.constructSerializableWorkflow());this.commandContext.apply(e,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((e=>{e.renderableSteps.forEach((e=>{const i={stepName:e.stepName};i.storage=this.storage[e.stepName],i.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(i)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new fo((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new fo((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new ar("Attempted to serialize state before it was initialized.");const i=JSON.stringify(this.dehydrateState(F(e)(t.transaction))),A=t.variation;if(!A)return{transaction:i};const n={layouts:{},serializableWorkflow:{steps:[]},...F(e)(A)||{}};return{transaction:i,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(t){for(const e of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===e.type&&(delete e.cachedObjectURL,e.src&&delete e.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,e)=>Object.keys(t).reduce(((i,A)=>{const n=[...t[A]||[]];return e.forEach((t=>{const e=n.findIndex((e=>e.id===t.id));e>-1&&n.splice(e,1)})),i[A]=n,i}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(Ls(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach((e=>t.push(e))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,e)=>("Model"===e.type&&e.option?.id&&!Ls(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const i=this.product;if(!i)return Promise.resolve({stepElements:{},commands:[]});const A=async(t,e,i)=>{if(t.type===si.SilentIllustration){return{step:t,results:await new Zs(t,e).trigger()}}if(t.type===si.ProductOverlay){return{step:t,results:await new Zs(t,e,i).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},n=t.filter((t=>!this.stepInitialised[t.stepName])),r={stepElements:{},commands:[]},a=[];for(const t of n)this.markStepsAsInitialised([t.stepName]),e||a.push(A(t,this.layouts,i));const s=await Promise.all(a);for(const t of s)r.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),r.commands=[...r.commands,...t.results.map((t=>t.command))];return r}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,e){return e.find((e=>e.stepName===t))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((t=>t.layoutState.elements.forEach((t=>{this.getCommandDispatcher()(new sn(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,i,A){const n=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,e)=>t+e.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,e)=>t+e),0)),0),this.workflow.steps.forEach((t=>{Ls(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const r=this.allScenes,a=zs(r,n),s=zs(r,this.stepSelections),o=a.map((t=>t.silentSteps)).flat(),c=s.map((t=>t.silentSteps)).flat().filter((t=>!o.some((e=>e.stepName===t.stepName))));o.forEach((t=>{Ls(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:g,commands:h}=await this.stepElementsForIntroducedSilentSteps(c,!1);this.stepElements={...this.stepElements,...g,[t]:i},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===si.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(i.map((t=>t.id)))}const d=[...h,...l.map((t=>new sn(t.id))),new $A(this.constructSerializableWorkflow())];d.length>0&&this.commandContext.apply(new An(d),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),A&&await A()}async ensureStepsAreLoaded(){const t=[],e=zs(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const i of e)if(!this.stepInitialised[i.stepName])switch(this.stepInitialised[i.stepName]=!0,i.type){case si.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case si.DigitalContent:t.push(eo.init(i,this,this.reloadedState));break;case si.Frame:case si.Photo:{const e=new Xs(i.data.forceImageCover);e.connectWorkflowManager(this,i.stepName),this.stepSpecificServices[i.stepName]={frameService:e},t.push(Ao.init(i,this,this.reloadedState))}break;case si.Illustration:t.push(no.init(i,this,this.reloadedState));break;case si.Material:t.push(ro.init(i,this,this.reloadedState));break;case si.Model:t.push(ao.init(i,this,this.reloadedState));break;case si.Module:this.stepSpecificServices[i.stepName]={module:await cs(i.data.module)},t.push(so.init(i,this,this.reloadedState));break;case si.Picture:t.push(oo.init(i,this,this.reloadedState));break;case si.Question:t.push(co.init(i,this,this.reloadedState));break;case si.Shape:t.push(lo.init(i,this,this.reloadedState));break;case si.Text:t.push(Bo.init(i,this,this.reloadedState))}const i=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),A=i.filter((t=>!!t&&!!t.command)).map((t=>t.command)),n=i.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));A&&A.length>0&&this.commandContext.apply(new An(A),!0);for(const t of n)await t();n.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((t=>t(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((t=>t(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((t=>t(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((t=>t(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((t=>t(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((t=>{t(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((t=>t(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((t=>{t(this.stepMetadata)}))}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach((e=>e(this.storage[t])))}onStorageChange(){this.storageCallbacks.forEach((t=>t(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((t=>{t(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((t=>{t(this.variationRecords)})),this.render3DScene()}traversableScenes(){return js(this.allScenes,this.stepSelections)}}function Qo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class yo{constructor(t){Qo(this,"variantData",void 0),this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.thumbnail?.versions?.find((t=>"cdn"===t.name))?.link}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find((t=>"thumbnail"===t.name));return t?t.link:this.variantData.asset?.versions?.find((t=>"thumbnail"===t.name))?.link}getDisplayImage(){return this.variantData.displayImage?.versions?.find((t=>"medium"===t.name))?.link}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}function Do(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class Io{constructor(t,e){Do(this,"manager",void 0),Do(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Io.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Io.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new yo(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new yo(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new yo(t)))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),i=this.step.data.modelAnimation,A=this.step.data.lookAtAnimation;t&&A&&t.executeCameraAnimation(A),e&&i&&e.executeAnimation(i)}}function xo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}Do(Io,"updateState",new Map);const vo=t.gql`
470
+ `,Gs=t=>{const e=[];for(const i of t.steps)switch(i.type){case si.DigitalContent:i.data.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case si.Frame:const t=i.data;t.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),t.varyUpload&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Upload});break;case si.Illustration:const A=i.data;A.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),A.varyColors&&A.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Colors});break;case si.Material:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Model:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Picture:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Question:i.data.varySelections&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selections});break;case si.Shape:i.data.varySelection&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection});break;case si.Text:const n=i.data;n.varyText&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Text}),n.varySelection&&i.option&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Selection}),n.varyColor&&n.colorPickerEnabled&&e.push({stepName:i.stepName,stepType:i.type,aspectType:ci.Color})}return e},Ts=[si.SilentIllustration,si.ProductOverlay],Os=async(t,e,i)=>{const A=[];t.introduction&&A.push({name:"Introduction",title:t.name,renderableSteps:[{type:si.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const i of t.steps){if(e.bulkScene){let t=!1;switch(i.type){case si.DigitalContent:i.data.varyUpload&&(t=!0);break;case si.Frame:{const e=i.data;!e.varyUpload||!e.varySelection&&i.option||(t=!0)}break;case si.Illustration:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case si.Material:i.data.varySelection&&(t=!0);break;case si.Model:i.data.varySelection&&(t=!0);break;case si.Picture:i.data.varySelection&&(t=!0);break;case si.Question:i.data.varySelections&&(t=!0);break;case si.Shape:i.data.varySelection&&(t=!0);break;case si.Text:{const e=i.data;!e.varySelection&&i.option&&1!==(i.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const n=Js(i.stepName,t.stepGroups);if(n){const t=A.find((t=>t.name===n.name));t?Ts.includes(i.type)?t.silentSteps.push(i):t.renderableSteps.push(i):A.push({name:n.name,title:n.name,renderableSteps:Ts.includes(i.type)?[]:[i],silentSteps:Ts.includes(i.type)?[i]:[]})}else A.push({name:i.stepName,title:i.stepTitle,renderableSteps:Ts.includes(i.type)?[]:[i],silentSteps:Ts.includes(i.type)?[i]:[]})}if(e.bulkScene){const n=i?.product?.bulkConfiguration;A.push({name:"Bulk",title:n?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:si.Bulk,stepName:"Bulk",stepTitle:n?.stepTitle??e.bulkSceneTitle,helpText:n?.helpText,data:{aspects:Gs(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&A.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:si.Finish,stepName:"Finish",stepTitle:e.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),A},Js=(t,e)=>e.find((e=>e.stepNames.includes(t))),Ls=(t,e)=>(t.conditions||[]).every((t=>{const i=e[t.targetStepName];if(i&&i.selectedVariants){const e=i.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),zs=(t,e)=>t.map((t=>((t,e)=>{const i={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>Ls(t,e))),silentSteps:t.silentSteps.filter((t=>Ls(t,e)))};return 0===i.silentSteps.length&&0===i.renderableSteps.length?null:i})(t,e))).filter((t=>null!==t)),js=async(t,e)=>{const i=zs(t,e),A=[];for(const t of i)for(const e of t.renderableSteps)if(e.type===si.Model||e.type===si.Material||e.type===si.Picture||e.type===si.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&A.push(e.stepName)}else A.push(e.stepName);const n=i.filter((t=>t.renderableSteps.filter((t=>A.includes(t.stepName))).length>0));for(const t of n)t.renderableSteps=t.renderableSteps.filter((t=>A.includes(t.stepName)));return n};function Vs(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}function Ks(t,e,i,A){const n=i.width*t.zoom,r=i.height*t.zoom;if(A){const A=t,n=Math.max(e.width/i.width,e.height/i.height);A.zoom=Math.max(n,t.zoom);const r=i.width*A.zoom,a=i.height*A.zoom;return A.x=Ws(t.x,e.width-r,0),A.y=Ws(t.y,e.height-a,0),A}const a=t;return a.x=Ws(a.x,-n,e.width),a.y=Ws(a.y,-r,e.height),a}function Ws(t,e,i){return Math.min(Math.max(t,e),i)}class Xs{constructor(t){Vs(this,"offsets",void 0),Vs(this,"forceImageCover",void 0),Vs(this,"targetElements",void 0),Vs(this,"imageData",void 0),Vs(this,"frameData",void 0),Vs(this,"_debouncedUpdateFrameOffsets",void 0),Vs(this,"minZoomScale",[.03]),Vs(this,"maxZoomScale",[20]),Vs(this,"onFrameDataChangeListeners",void 0),Vs(this,"onZoomChangeListeners",void 0),Vs(this,"workflowManager",void 0),Vs(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=F(I)(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback((async t=>{if(t){const e=t;if(e.currentFrameSources){let t=!1;for(let i=0;i<e.currentFrameSources.length;i++){const A=e.currentFrameSources[i],n=await kn(A);F(C)(n,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[i]=n,t=!0)}t&&(this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){t?t.forEach(((e,i)=>{const A=Yn.get(e);A&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[i]=A)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,i,A){if(this.imageData&&this.offsets&&this.frameData){this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length));const n=this.frameData.map(((A,n)=>{const r=(e[n]-this.offsets[n].x)/this.offsets[n].zoom,a=(i[n]-this.offsets[n].y)/this.offsets[n].zoom;return{x:e[n]-r*t[n],y:i[n]-a*t[n],zoom:this.imageData.width*t[n]/this.imageData.width}}));this.updateOffsets(n,A),this.onZoomChangeListeners.forEach((e=>e(t)))}}setPatternData(t){this.imageData=t,t&&this.frameData&&(this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,i){const A=this.imageData;if(!A||!this.frameData)return;if(this.frameData.length!==t.length)throw new ar("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,i)=>t[i].x!==e.x||t[i].y!==e.y||t[i].zoom!==e.zoom))||i?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,i)=>{this.offsets[i]=Ks(t[i],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,A,this.frameData,this.targetElements,e)):e&&e()}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,i,A,n){if(!i||0===i.length||i.some((t=>!t)))throw new ar("Frame data not set. This is a bug");if(!this.workflowManager)throw new ar("No workflow manager set, cannot update offsets.");const r=this.workflowManager.getCommandDispatcher();A.forEach(((i,A)=>{r(new wn(i,e,t[A]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),n&&n()}recalculateZoomLimits(t,e){this.minZoomScale.length===e.length&&this.maxZoomScale.length===e.length||(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach(((e,i)=>{const A=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[i]=A,this.maxZoomScale[i]=2.5*A):(this.minZoomScale[i]=A/10,this.maxZoomScale[i]=2.5*A)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,i)=>{this.offsets[i]=Hn(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function qs(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class Zs{constructor(t,e,i){qs(this,"configuration",void 0),qs(this,"layouts",void 0),qs(this,"product",void 0),qs(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new er(t);let i="";if(this.configuration.type===si.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),i=t,!t)throw new nr(this.configuration,"Couldn't find an asset for product overlay step")}const A=this.evaluateAssetType();if(A===ze.Image){const i=this.configuration.type===si.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!i)throw new Error("Undefined raster silent step source");const n={stepName:this.configuration.stepName,id:Te(),src:i,type:A,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,productOverlay:this.configuration.type===si.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:n.id,region:t},command:new an(n,e)}}{const n=this.configuration.type===si.SilentIllustration?this.configuration.data.asset?.fileLink:i,r=async()=>new Promise(((t,e)=>{n?Wi(n).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),a=await TA(await r()),s={stepName:this.configuration.stepName,id:Te(),cachedObjectURL:await Wn(a.svg),src:n,svg:a.svg,colors:a.colors,type:A,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,immutable:t.immutable,productOverlay:this.configuration.type===si.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new an(s,e)}}})),this.configuration=t,this.layouts=e,this.product=i||void 0}async trigger(){if(!this.configuration.data.regions)throw new nr(this.configuration,"Missing regions.");if(this.configuration.type===si.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===si.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new er(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===si.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?ze.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),ze.Illustration)}}const $s=async t=>{const e=`${wr.getServicesApiUrl()}/shortener`;try{const i=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await i.json()).shortUrl}catch(t){throw console.error(t),new cr("Failed to shorten URL, see console.")}};function _s(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class to{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(t){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,i,A=3e3,n=10){_s(this,"pollingId",void 0),_s(this,"attempts",void 0),_s(this,"interval",void 0),_s(this,"maxAttempts",void 0),_s(this,"predicate",void 0),_s(this,"onSuccess",void 0),_s(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=i,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=A,this.maxAttempts=n,this.poll()}}const eo=new class{async init(t,e,i){return i&&await this.reload(t,e,i),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],n,(async()=>{const i=A?.storage?.videoShortUrl,n=A?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:i,videoUrl:n})}))}async regenerateQRCode(t,e,i,A,n,r,a,s,o){if(e||""===i||""!==A)o(!1);else{const e=async()=>{const t=(await br([i]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},c=await new Promise(((t,i)=>{new to((async()=>!!(await e()).link),(async()=>{const i=await e();if(!i.link||!i.link)throw new Ar(i.asset);t({rel:"mpeg4",href:i.link})}),(()=>{i("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>s(new sn(t.id))));const l="http"===r.data.baseUrl.slice(0,4)?"":"https://",g=new URL(l+r.data.baseUrl);g.searchParams.append("video",btoa(JSON.stringify([c]))),g.pathname=g.pathname+("/"===g.pathname.slice(-1)?"":"/");const h=g.toString();if(h.length>=2e3)throw new cr("Cannot create QR code, URL too long.");const d=await $s(h);if(a(d),!r.data||!r.data.regions)throw new nr(r,"Missing regions.");const u=await this.regionElements(r),w=await this.command(d,u,n,r.stepName);w&&(w.command&&n.getCommandDispatcher()(w.command),w.followup&&await w.followup()),await n.setSelectionsAndElements(r.stepName,[],u,(async()=>{n.updateStorage(r.stepName,{videoShortUrl:d,videoUrl:A}),o(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:Te(),region:t})))}async command(t,e,i,A){const n=i.getLayouts(),r=`data:image/svg+xml;base64,${btoa(await(0,y.toString)(t,{type:"svg"}))}`,a=e.map((t=>{const e=t.region,i=n.find((t=>t.panelId===e?.panelId));if(!i&&e)throw new er(e);if(i&&!e)throw new Error("Region not found");if(!i||!e)throw new Error("Neither a region or layout found!");return new an({stepRegion:e,stepName:A,id:t.id,src:r,type:ze.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},i)}));return{command:new An(a),followup:async()=>{}}}};function io(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}const Ao=new class{constructor(){io(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Nn(e);const i=t.asset;if(!i)throw new ir(t);const A=i.fileLink;if(A)return Wi(A);throw new Ar(i)}))}async init(t,e,i){if(i)return await this.reload(t,e,i),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const i=t.option,A=Ur.getDefaultVariant(i);return A?this.selectVariantCommand(t,A,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const i=t.data.regions.map((t=>Nn(t)));e.updateStorage(t.stepName,{currentFrameSources:i})}if(A){const i=async()=>{const i=A.storage?.framePatternSrc,n=A.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:n,framePatternSrc:i}),i){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(i,A),e.updateMetadata(t.stepName,{image:i}),e.updateStorage(t.stepName,{framePatternSrc:i})}if(n?.some((t=>t.zoom))){const i=e.getStepSpecificServices(t.stepName)?.frameService;if(!i)throw new Error("Frame service unavailable, cannot load pattern!");i.updateOffsets(n)}e.setMandatoryFulfilled(t.stepName,!0)};if(A.selectedVariants&&A.selectedVariants.length>0){const r=A.selectedVariants[0].id;if(t.option&&r){const A=t.option.variants?.find((t=>t.id===r));A&&await e.setSelectionsAndElements(t.stepName,[A],n,(async()=>{const n=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(A,t))));e.updateStorage(t.stepName,{currentFrameSources:n}),await i()}))}}else await e.setSelectionsAndElements(t.stepName,[],n,i)}}selectImage(t,e,i){i.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?i.addPoller(new to((async()=>{const t=(await Nr.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{Nr.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,i)}))}),(()=>{throw new cr("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,i)}async selectVariant(t,e,i,A,n){const r=await this.selectVariantCommand(t,e,i,A,n);r&&(r.command&&A.getCommandDispatcher()(r.command),r.followup&&await r.followup())}getCreateElementCommand(t,e,i,A){return new an({id:t,type:ze.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/A.frameData.width,scaleY:e.height/A.frameData.height,path:A.frameData.path,dataWidth:A.frameData.width,dataHeight:A.frameData.height,stepRegion:e,stepName:A.stepName,disablePlaceholder:A.disablePlaceholder,focalBlur:A.focalBlur,focalBlurStrength:A.focalBlurStrength,focalBlurRadius:A.focalBlurRadius,pattern:A.pattern,immutable:e.immutable},i)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const i=await Gn(t),A=i.width,n=i.height,r={src:t,width:A,height:n,aspect:A/n};bn.set(t,r),e.setPatternData(r)}else{const i=await Ki(t),A=await Sn(i),n={src:t,width:A.width,height:A.height,aspect:A.width/A.height};bn.set(t,n),e.setPatternData(n)}}async selectVariantCommand(t,e,i,A,n,r){const a=A.getStepSpecificServices(t.stepName)?.frameService;if(!a)throw new Error("Frame service unavailable, cannot load pattern!");const s=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));n&&n(!0);const o=await Promise.all(t.data.regions.map((async(e,n)=>{const r=await kn(s[n]),o=a.getImageData(),c=i.map((t=>new sn(t.id))),l=o?Hn(o,r):void 0,g=o?{id:Te(),src:o.src,x:l?.x||0,y:l?.y||0,width:o.width,height:o.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,h=Te(),d=A.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new er(e);return{command:this.getCreateElementCommand(h,e,d,{frameData:r,pattern:g,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:h,region:e},removeExistingCommands:c}}))),c=o.map((t=>t.command)),l=o.map((t=>t.removeExistingCommands)).flat();return{command:new An([...c,...l]),followup:async()=>{n&&n(!1),await A.setSelectionsAndElements(t.stepName,e?[e]:[],[...o.map((t=>t.regionEl))],(async()=>{if(A.updateStorage(t.stepName,{currentFrameSources:s}),r){const e=A.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(r,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const i=t.fileLink;if(i)return i;throw new Ar(t)}async loadPatternFromAsset(t,e,i){const A=this.patternSource(t),n=i.markUpdatePending(),r=i.getStepSpecificServices(e.stepName)?.frameService;if(!r)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,r),i.updateMetadata(e.stepName,{image:A}),i.updateStorage(e.stepName,{framePatternSrc:A}),i.markUpdateCompleted(n)}};const no=new class{async getIllustrationBody(t){return new Promise((e=>{Wi(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,i,A){return new an({stepRegion:e,stepName:A.stepName,colors:A.svg.colors,id:t,src:A.src,svg:A.svg.svg,cachedObjectURL:A.objectURL,type:ze.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},i)}getColors(t,e){const i=e.getRegionElements(t.stepName)||[];if(0===i.length)return[];try{return KA(i[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,i){const A=t.option;if(!A)return null;if(i)return this.reload(t,e,i);{const i=Ur.getDefaultVariant(A);if(i)return await this.selectVariantCommand(t,i,[],(()=>{}),e)}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(!r||!i)throw new Error("Required illustration variant no longer available");{const a=r.variants?.find((t=>t.id===i));if(a){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[a],i,(async()=>{e.updateMetadata(t.stepName,{colors:A.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const i=t.data.colorOption;return i&&i?i.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,i,A,n){const r={};for(const[t,e]of n.entries())r[t]={browserValue:e,spotColor:r[t]?.spotColor};const a=GA(t,e,i,r),s=await Wn(a),o=[];for(const t of A){for(const[e,i]of n.entries())o.push(new pn(t,e,i));o.push(new En(t,a,s))}return new An(o)}async changeColors(t,e,i,A,n){if(0===e.length)return;const r=KA(e[0].id,A().map((t=>t.layoutState))),a={...r.colors},s={};Object.entries(a).forEach((([t,e])=>{const i={browserValue:e.browserValue},A=e.spotColor;A&&(i.spotColor={profileName:A.profileName,namedColor:A.namedColor}),s[t]=i}));for(const[t,e]of n.entries())a[t]={browserValue:e,spotColor:a[t]?.spotColor},s[t]={browserValue:e};let o=Array.from(Object.values(a)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{o=o.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),i.updateMetadata(t.stepName,{colors:o});const l=new Map;if(Object.entries(a).forEach((([t,e])=>{l.set(t,e.browserValue)})),!r.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const g=await this.changeColorsCommand(r.svg,r.width,r.height,e.map((t=>t.id)),l);i.updateStorage(t.stepName,{colors:s}),i.getCommandDispatcher()(g)}async selectVariant(t,e,i,A,n){const r=await this.selectVariantCommand(t,e,i,A,n);r&&(r.command&&n.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async selectVariantCommand(t,e,i,A,n){if(!t.data||!t.data.regions)throw new nr(t,"Missing regions.");A(!0);const r=i.map((t=>new sn(t.id)));n.setMandatoryFulfilled(t.stepName,!1);const a=e.asset;if(!a)throw new ir(e);const s=a.fileLink;if(!s)throw new Ar(a);const o=await TA(await this.getIllustrationBody(s)),c=await Wn(o.svg),l=t.data.regions.map((e=>{const i=n.getLayouts().find((t=>t.panelId===e.panelId));if(!i)throw new er(e);const A=Te();return{regionElement:{id:A,region:e},command:this.getCreateElementCommand(A,e,i,{stepName:t.stepName,src:s,objectURL:c,svg:o})}})),g=[...l.map((t=>t.command)),...r];let h=Array.from(Object.values(o.colors)).map((t=>t.browserValue));const d=t.data.colorOption;return d&&d.variants?.forEach((t=>{h=h.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),n.updateMetadata(t.stepName,{colors:h}),{command:new An(g),followup:async()=>{await n.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{n.setMandatoryFulfilled(t.stepName,!0),A(!1)}))}}}};const ro=new class{async init(t,e,i){const A=t.option;if(!A)throw new tr(t);if(i)await this.reload(t,e,i);else{const i=Ur.getDefaultVariant(A);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(!r)throw new tr(t);if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(i){const A=r.variants?.find((t=>t.id===i));if(A){const i=A.material,a=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],a,(async()=>{const A=e.getModelContainer();if(A){const n=t.data.targetMaterials.map((t=>A.applyMaterialVariant(t,r.id||"",i||{})));Promise.all(n).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantLambda(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i,A){const n=i.getModelContainer();A(!0);const r=e.material;if(!r)throw A(!1),new ir(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{n&&t.data.targetMaterials.forEach((e=>{t.option&&n.applyMaterialVariant(e,t.option.id||"",r)})),i.setMandatoryFulfilled(t.stepName,!0)}finally{A(!1)}}))}}}};const ao=new class{async init(t,e,i){const A=t.option;if(!A)throw new tr(t);if(i)await this.reload(t,e,i);else{const i=Ur.getDefaultVariant(A);if(i)return await this.selectVariantLambda(t,i,e,(()=>{}))}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const A=r.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{const i=e.getModelContainer();if(i&&t.option){const n=A.asset?.fileLink;if(!n)throw new ir(A);await i.applyModelVariant(t.option.id||"",{model:n,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantLambda(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,i,A){A(!0);const n=e.asset?.fileLink;if(!n)throw new ir(e);return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=i.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:n,contextService:i.getLayoutPreviewService()},t.data.replaceProductModel||!1),i.setMandatoryFulfilled(t.stepName,!0)}finally{A(!1)}}))}}}};const so=new class{async init(t,e,i){return i?(await this.reload(t,e,i),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],n,(async()=>{e.updateStorage(t.stepName,{text:A?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==A?.storage?.text)}))}async changeText(t,e,i,A,n){const r=await this.changeTextCommand(t,e,i,A,n);r&&(r.command&&i.getCommandDispatcher()(r.command),r.followup&&await r.followup())}async changeTextCommand(t,e,i,A,n){const r=i.getRegionElements(t.stepName),a=i.getStepSpecificServices(t.stepName)?.module;if(!a)return console.error("Missing module."),null;const s=i.getProfanities();if(!this.validateInput(t,e,s,n))return i.setMandatoryFulfilled(t.stepName,!1),console.error(A),null;if(i.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;i.updateStorage(t.stepName,{text:e});const o=(e,A,n)=>{const r=n||Te(),a=i.getLayouts().find((t=>t.panelId===A.panelId));if(!a)return console.error(`Can not find layout for region: ${A.panelId}`),null;const s=[];return n&&s.push(new sn(r)),s.push(new an({stepRegion:A,stepName:t.stepName,colors:{},id:r,svg:e,type:ze.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable},a)),{id:r,region:A,command:new An(s)}};if(r.length>0){const t=r.map((t=>{if(!t.region)return null;const i=a.svgPrint(e,t.region);return o(i,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new An(t),followup:async()=>{}}}{const A=t.data.regions.map((t=>o(a.svgPrint(e,t),t))),n=A.filter((t=>!!t)).map((t=>t&&t.command));return{command:new An(n),followup:async()=>{const e=A.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await i.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,i,A){if(t.data&&t.data.maxLength){const i=t.data.maxLength;if(e.length>i)return A("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return A("Unsupported characters."),!1;const n=(0,x.split)(e.toLowerCase());for(const t of n)for(const e in i){if(t===i[e].toLowerCase().replace(/\s/g,""))return A("Blocked profanity."),!1}return A(""),!0}};const oo=new class{async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else if(A.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,A.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const A=r.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantCommand(t,e,i,A);n&&(n.command&&i.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantCommand(t,e,i,A){const n=e.asset;if(!n)throw new ir(e);const r=n?.fileLink;if(!r)return console.error("No URL for picture!"),null;A(!0),i.setMandatoryFulfilled(t.stepName,!1);const a=i.getRegionElements(t.stepName).map((t=>new sn(t.id))),s=t.data.regions.map((e=>{const A=i.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new er(e);const n=Te();return{regionElement:{id:n,region:e},command:new an({stepName:t.stepName,stepRegion:e,id:n,src:r,type:ze.Image,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,preserveAspectRatio:"none"},A)}}));return{command:new An([...a,...s.map((t=>t.command))]),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],s.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),A(!1)}))}}}};const co=new class{async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else{const i=A.variants;if(Ur.getDefaultVariant(A)){const n=i?.find((t=>t.id===A.defaultVariant?.id));return this.selectVariantLambda(t,n?.id||"",e)}}return null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(n&&i){const A=n.variants?.find((t=>t.id===i));A&&await e.setSelectionsAndElements(t.stepName,[A],[])}}}async selectVariant(t,e,i){await i.getInitializationPromise();const A=await this.selectVariantLambda(t,e,i);A&&(A.command&&i.getCommandDispatcher()(A.command),A.followup&&await A.followup())}async selectVariantLambda(t,e,i){const A=t.option;if(!A)return null;const n=A.variants;if(!n)return null;const r=n.length>1?n.find((t=>t.id===e)):n[0];if(!r)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await i.setSelectionsAndElements(t.stepName,[r],[],(async()=>{i.setMandatoryFulfilled(t.stepName,!0)}))}}}};const lo=new class{async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}async init(t,e,i){const A=t.option;if(!A)throw new tr(t);if(!i){const i=Ur.getDefaultVariant(A);if(!i)return null;const n={fill:i.color,stroke:i.color,variant:i};return this.selectVariantCommand(t,n,[],e)}return await this.reload(t,e,i),null}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const A=r.variants?.find((t=>t.id===i));if(A){const i=n.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[A],i,(async()=>{e.updateStorage(t.stepName,{colour:A.color||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,i,A){const n=await this.selectVariantCommand(t,e,i,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantCommand(t,e,i,A){const n=A.getLayouts();if(i.length>0){const r=t=>{const i=t.region;if(!n.find((t=>t.panelId===i?.panelId)))throw new er(i);const A=e.variant?.color;return A?new pn(t.id,"spiff-fill-shape",A):(console.error("Failed to change color."),null)},a=i.map(r).filter((t=>!!t));return{command:new An(a),followup:async()=>{await A.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],i),A.updateStorage(t.stepName,{colour:e.fill||""})}}}{const i=i=>{const A=n.find((t=>t.panelId===i.panelId));if(!A)throw new er(i);const r=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${e.variant?.color}"\n />\n </svg>\n `,a={};a["spiff-fill-shape"]={browserValue:e.variant.color};const s=Te();return{id:s,region:i,command:new an({stepRegion:i,stepName:t.stepName,colors:a,id:s,svg:r,type:ze.Illustration,y:i.top,x:i.left,rotation:i.rotation,width:i.width,height:i.height,layer:i.layer,layerIndex:i.layerIndex,immutable:i.immutable,excludeFromExport:t.data.excludeFromPrint},A)}},r=t.data.regions.map(i),a=r.filter((t=>!!t)).map((t=>t?.command)),s=r.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new An(a),followup:async()=>{await A.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],s,(async()=>{A.updateStorage(t.stepName,{colour:e.fill||""})}))}}}}};function go(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class ho extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=ho.name}}const uo=["‘","’","“","”","\n"];class wo extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=wo.name}}const Bo=new class{constructor(){go(this,"cachedColors",new Map),go(this,"filterUnsupportedCharacters",((t,e)=>{let i=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const A=[],n=e?cA(e):void 0;if(n){const t=i.split("").filter((t=>!uo.includes(t))).join(""),e=t.split("").map((t=>n.getFont().charToGlyph(t)));for(let i=0;i<e.length;i++){".notdef"===e[i].name&&A.push(String.fromCharCode(t.charCodeAt(i)))}}for(let t=0;t<A.length;t++)i=i.replaceAll(A[t],"");return i})),go(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),go(this,"getErrorsForText",((t,e,i)=>{const A=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&A.push({localizationKey:"workflow.steps.text.characterLimit"});const n=i.getProfanities(),r=(0,x.split)(t.toLowerCase());for(const t of r)for(const e in n){if(t===n[e].toLowerCase().replace(/\s/g,"")){A.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&A.push({localizationKey:"workflow.steps.text.multipleLines"}),A}))}async init(t,e,i){const A=t.option;if(!A)return null;if(i)await this.reload(t,e,i);else{const i=this.getDefaultImageFillVariant(t.data),n=i?.asset?.fileLink,r=n?await Un(n):void 0,a=r?{src:r.src,height:r.height,width:r.width,scale:t.data.imageFillScale||1}:void 0;e.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:a}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:i?.name});const s=Ur.getDefaultVariant(A);if(s)return this.selectVariantCommand(t,s,{},[],e,(()=>{}),(()=>{}),a)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>KA(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const i=t.data.colorOption;if(i){const e=i.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,i,A){if(!t.data||!t.data.regions)return;const n=A.getCommandDispatcher();e.variant?A.updateMetadata(t.stepName,{color:e.variant.name}):A.updateMetadata(t.stepName,{color:e.fill});const r=t.data.colorOption,a=r?this.createTextFillSpotColor(r,e.variant):void 0;r?A.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:r.colorProfile?.key}):A.updateStorage(t.stepName,{color:e.fill});for(const t of i){if(!e.fill)throw new Error("Fill not set on new color selection!");n(new cn(t.id,e.fill,a))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const i=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(i.map((async e=>{const i=await Un(e);return{src:e,width:i.width,height:i.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,i,A){if(!t.data||!t.data.regions)return;const n=A.getCommandDispatcher(),r=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));A.updateMetadata(t.stepName,{fillImage:r?.name}),A.updateStorage(t.stepName,{fillImage:e});for(const t of i){n(new ln(t.id,e))}}getProcessedInput(t,e,i){const A=i?t:this.injectReplaceableText(t,e);return QA(A,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,i,A){const n=A.getStepStorage(i.stepName),r=this.getProcessedInput(t,i.data,!!n.customiseAllText),a={command:void 0,helperText:"",errors:this.getErrorsForText(t,i,A)};if(a.errors.length>0)return a.helperText=a.errors[0].localizationKey,a;const s=(i.data.maxLength-r.length).toString();a.helperText=`${s} characters remaining`;const o=A.getTransaction().bulk&&i.data.varyText||!1,c=[],l=new Map,g=new Map;for(const t of e){if(!t.fontData)throw new ar("Failed to resolve font data for text.");const[e,A]=Ln(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[r],{size:i.data.size,minSize:i.data.minSize,maxSize:i.data.maxSize});l.set(t.id,e),g.set(t.id,A);const n=i.data.curved?r:(A||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,i.data,t.id,n,o))}if(!i.data.curved&&e.length>0){if(!Array.from(g.values()).every((t=>t)))return a.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),a}return A.updateStorage(i.stepName,{text:t}),A.updateMetadata(i.stepName,{text:r}),n.defaultCleared&&A.setMandatoryFulfilled(i.stepName,!0),a.command=new An(c),a.command.varying=o,a}async selectVariant(t,e,i,A,n){const r=await this.selectVariantCommand(t,e,i.getStepStorage(t.stepName)||{},i.getRegionElements(t.stepName),i,A,n);r&&(r.command&&i.getCommandDispatcher()(r.command),r.followup&&await r.followup())}createTextFillSpotColor(t,e){const i=t.colorProfile;if(i){const t=(i.name||"").replace(/\s/g,"-"),A=t.lastIndexOf("/"),n=t.slice(A+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:n,namedColor:e.namedColor}}}async reload(t,e,i){const A=e.getSerializedStep(t.stepName,i.serializableWorkflow.steps),n=Object.values(i.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),r=t.option;if(A?.selectedVariants){const i=A.selectedVariants[0].id;if(r&&i){const a=r.variants?.find((t=>t.id===i));if(a){const i=await this.fontDataFromVariant(a),r=n.map((t=>({id:t.id,region:t.stepRegion}))),s=A.storage?.color,o=A.storage?.text;await e.setSelectionsAndElements(t.stepName,[a],r,(async()=>{e.updateMetadata(t.stepName,{color:s,text:o}),e.updateStorage(t.stepName,{text:o,inputText:o});const A=n.map((t=>new dn(t.id,i))),r=new An(A);e.getCommandDispatcher()(r),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=Bo.updateInputText(o||"",n,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return Ur.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return Ur.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return Ur.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ir(t);const i=e.fileLink;if(!i)throw new Ar(e);return{assetUrl:i,name:(await sA(i)).names.fullName.en}}async selectVariantCommand(t,e,i,A,n,r,a,s){const o=n.markUpdatePending(),c=await this.fontDataFromVariant(e);if(A.length>0){const l=A.map((t=>new dn(t.id,c)));if(s){const t=A.map((t=>new ln(t.id,s)));l.push(...t)}const g=await this.changeInputTextWithRegion(t,t.data.size||30,c,i.text||"",i,n,!!i.customiseAllText,r,a);g&&l.push(g);return{command:new An(l),followup:async()=>{n.markUpdateCompleted(o),await n.setSelectionsAndElements(t.stepName,[e],A)}}}{const A=await this.createTextboxRegions(t.stepName,e,t.data,c,i,n),l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A[0]?.newElement.input||i.text||t.data.defaultText||"",i,n,!!i.customiseAllText,r,a),g=A.flatMap((t=>t.commands));if(s){const t=A.map((t=>new ln(t.regionElement.id,s)));g.push(...t)}l&&g.push(l);return{command:new An(g),followup:async()=>{n.markUpdateCompleted(o)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,i,A,n,r){if(!i||!i.regions)throw new Error("Step data not supplied");const a=r.getTransaction().bulk&&i.varyText||!1,s=a?"":n.text||i.defaultText||"",o=this.getProcessedInput(s,i,!1),c=await Promise.all(i.regions.map((async e=>{const c=r.getLayouts().find((t=>t.panelId===e.panelId)),l=Te();try{if(!c)throw new wo("Failed to find layout for region: "+e.panelId);const g=i.colorOption;let h;if(g&&g.variants){const e=g.variants.find((t=>t.id===g.defaultVariant?.id))||g.variants[0];h=this.createTextFillSpotColor(g,e),r.updateStorage(t,{colorProfileAssetKey:g.colorProfile?.key})}const d=await this.getDefaultColor(i),u=d||"#000000",w={stepRegion:e,stepName:t,align:this.textAlign(i),fill:n.color?n.color:u,fontSize:i.size||30,fontData:A,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:o,input:s,type:ze.Textbox,vertical:i.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:i.verticalAlign||"middle",curved:i.curved,paths:i.paths,fillSpotColorDefinition:h},B=[],p=new Map,E=new Map;if(!w.fontData)throw new ar("Failed to resolve font data for text.");const[m,f]=Ln(w.fontSize,w.fontData,{left:w.x,top:w.y,width:w.width,height:w.height,rotation:w.rotation,panelId:""},[o],{size:i.size,minSize:i.minSize,maxSize:i.maxSize});p.set(w.id,m),E.set(w.id,f);const C=i.curved||i.vertical?o:(f||[]).join("\n");B.push(this.generateTextChangeCommandsForRegion(m,i,w.id,C,a));const Q=new an(w,c);return Q.varying=a,{regionElement:{id:l,region:e},commands:[Q,...B],newElement:w,fontData:A}}catch(t){throw console.log(t),new ho("Error adding font to region")}}))).catch((t=>{throw t instanceof ho?(ca.setLatestToast("Failed to load font.",Eo.Error),t):t instanceof wo?t:new Error(t)}));return await r.setSelectionsAndElements(t,[e],c.map((t=>t.regionElement)),(async()=>{r.updateMetadata(t,{text:s}),r.updateStorage(t,{text:s})})),c}generateTextChangeCommandsForRegion(t,e,i,A,n){const r=[],a=new Bn(i,A);if(a.varying=n,r.push(a),!e.size){const e=new gn(i,t);e.varying=n,r.push(e)}const s=new An(r);return s.varying=n,s}async changeInputTextWithRegion(t,e,i,A,n,r,a,s,o,c){const l=(A||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),g=this.getProcessedInput(l,t.data,a),h=r.getRegionElements(t.stepName),d=new Map,u=new Map;for(const A of h)if(A.region){const[n,r]=Ln(e,i,A.region,[g],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(A.id,n),u.set(A.id,r)}const w=(()=>{if(t.data&&t.data.maxLength&&g.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=r.getProfanities(),i=(0,x.split)(g.toLowerCase());for(const t of i)for(const i in e){if(t===e[i].toLowerCase().replace(/\s/g,""))return s(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(g.includes("\n")||g.includes("\r")))return s(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(u.values()).every((t=>t)))return s(!0),{error:"Does not fit."}}return s(!1),{info:(t.data.maxLength-g.length).toString()}})();if(w.error)return void o(w.error);if(o(`${w.info} characters remaining`||""),c)return;r.updateStorage(t.stepName,{text:l}),r.updateMetadata(t.stepName,{text:this.injectReplaceableText(l,t.data)});const B=r.getTransaction().bulk&&t.data.varyText||!1;n.defaultCleared&&r.setMandatoryFulfilled(t.stepName,!0);const p=[];for(const e of h){const i=t.data.curved?g:(u.get(e.id)||[]).join("\n");p.push(this.generateTextChangeCommandsForRegion(d.get(e.id)||1,t.data,e.id,i,B))}const E=new An(p);return E.varying=B,E}};function po(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}let Eo;var mo;(mo=Eo||(Eo={})).Error="Error",mo.Warning="Warning",mo.Info="Info";class fo extends Ja{constructor(t){super(),po(this,"update",void 0),po(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Co{constructor(t,e,i,A,n,r,a,s,o,c,l=!1,g,h=!1){po(this,"reloadedState",void 0),po(this,"transaction",void 0),po(this,"ownerCustomer",void 0),po(this,"updateTransaction",void 0),po(this,"confirmedDesign",void 0),po(this,"editedSteps",void 0),po(this,"informationResults",void 0),po(this,"layouts",void 0),po(this,"mandatorySteps",void 0),po(this,"pendingUpdates",void 0),po(this,"selectionCost",void 0),po(this,"workflow",void 0),po(this,"stepSpecificServices",void 0),po(this,"previewService",void 0),po(this,"profanityFilter",void 0),po(this,"pollers",void 0),po(this,"commandContext",void 0),po(this,"stepElements",void 0),po(this,"stepInitialised",void 0),po(this,"stepMetadata",void 0),po(this,"stepSelections",void 0),po(this,"storage",void 0),po(this,"confirmCallbacks",void 0),po(this,"editedCallbacks",void 0),po(this,"elementsCallbacks",void 0),po(this,"informationResultCallbacks",void 0),po(this,"initCallbacks",void 0),po(this,"makingAdjustmentsCallback",void 0),po(this,"mandatoryCallbacks",void 0),po(this,"metadataCallbacks",void 0),po(this,"selectionCallbacks",void 0),po(this,"stepSpecificStorageCallbacks",void 0),po(this,"storageCallbacks",void 0),po(this,"currentVariationRecordCallbacks",void 0),po(this,"variationRecordCallbacks",void 0),po(this,"allScenes",void 0),po(this,"product",void 0),po(this,"invalidModelVariants",void 0),po(this,"currentAdjustingStepId",void 0),po(this,"renderableContextService",void 0),po(this,"workflowStatePromiseQueue",new La(1)),po(this,"variationRecords",[]),po(this,"currentVariationRecord",void 0),po(this,"initializationPromise",void 0),po(this,"initialized",!1),po(this,"readOnly",!1),po(this,"modelContainer",void 0),po(this,"isReloadedTransaction",!1),po(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,i]of e)i.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=n,this.commandContext=A,this.reloadedState=c,this.transaction=r,this.readOnly=l,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=e,this.pollers=[],this.allScenes=[],this.layouts=i,this.product=a,this.previewService=s,this.modelContainer=g,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=o,this.currentVariationRecord=null,this.isReloadedTransaction=h,this.initializationPromise=this.initializeDefaultWorkflowState(t,r),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((t=>{throw console.error(t),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>{this.updateStateWithServer(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,e){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await Os(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const i=zs(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:A,commands:n}=await this.stepElementsForIntroducedSilentSteps(i,!!this.reloadedState);this.commandContext.apply(new An(n),!0),this.stepElements={...this.stepElements,...A},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,i=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),i&&this.modelContainer?.executeAnimation(i)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const e={...t,recordNumber:this.variationRecords.reduce(((t,e)=>e.recordNumber>t?e.recordNumber:t),0)+1};return this.variationRecords.push(e),this.onVariationRecordsChange(),e}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((e=>e.recordNumber!==t)),this.variationRecords.forEach(((t,e)=>t.recordNumber=e+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,e=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(e||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(t){this.variationRecords=t,this.onVariationRecordsChange(),0===t.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(t[0])}setCurrentVariationRecord(t){if(this.currentVariationRecord=t,this.onCurrentVariationRecordChange(),t){const e=this.variationRecords.find((e=>e.recordNumber===t.recordNumber));e&&(e.values=t.values,this.onVariationRecordsChange())}}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addCurrentVariationCallback(t){t(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(t)}addVariationRecordsCallback(t){t(this.variationRecords),this.variationRecordCallbacks.push(t)}addPoller(t){this.pollers.push(t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((t=>t.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t)}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach((e=>{const i=this.stepSelections[e.stepName];i&&i.selectedVariants&&i.selectedVariants.length>0&&(t[e.stepName]={selections:i.selectedVariants})})),t}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach((t=>{e[t]=!0})),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((e=>e!==t))}markUpdatePending(){const t=Te();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const e=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()});this.setModelContainer(e),await e.getInitializationPromise(),this.render3DScene()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}async updateStorage(t,e){const i={...this.storage,[t]:{...this.storage[t],...e}};if(!F(C)(i,this.storage)){this.storage=i;const e=new $A(this.constructSerializableWorkflow());this.commandContext.apply(e,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((e=>{e.renderableSteps.forEach((e=>{const i={stepName:e.stepName};i.storage=this.storage[e.stepName],i.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(i)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new fo((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new fo((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new ar("Attempted to serialize state before it was initialized.");const i=JSON.stringify(this.dehydrateState(F(e)(t.transaction))),A=t.variation;if(!A)return{transaction:i};const n={layouts:{},serializableWorkflow:{steps:[]},...F(e)(A)||{}};return{transaction:i,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(t){for(const e of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===e.type&&(delete e.cachedObjectURL,e.src&&delete e.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,e)=>Object.keys(t).reduce(((i,A)=>{const n=[...t[A]||[]];return e.forEach((t=>{const e=n.findIndex((e=>e.id===t.id));e>-1&&n.splice(e,1)})),i[A]=n,i}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(Ls(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach((e=>t.push(e))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,e)=>("Model"===e.type&&e.option?.id&&!Ls(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const i=this.product;if(!i)return Promise.resolve({stepElements:{},commands:[]});const A=async(t,e,i)=>{if(t.type===si.SilentIllustration){return{step:t,results:await new Zs(t,e).trigger()}}if(t.type===si.ProductOverlay){return{step:t,results:await new Zs(t,e,i).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},n=t.filter((t=>!this.stepInitialised[t.stepName])),r={stepElements:{},commands:[]},a=[];for(const t of n)this.markStepsAsInitialised([t.stepName]),e||a.push(A(t,this.layouts,i));const s=await Promise.all(a);for(const t of s)r.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),r.commands=[...r.commands,...t.results.map((t=>t.command))];return r}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,e){return e.find((e=>e.stepName===t))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((t=>t.layoutState.elements.forEach((t=>{this.getCommandDispatcher()(new sn(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,i,A){const n=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,e)=>t+e.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,e)=>t+e),0)),0),this.workflow.steps.forEach((t=>{Ls(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const r=this.allScenes,a=zs(r,n),s=zs(r,this.stepSelections),o=a.map((t=>t.silentSteps)).flat(),c=s.map((t=>t.silentSteps)).flat().filter((t=>!o.some((e=>e.stepName===t.stepName))));o.forEach((t=>{Ls(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:g,commands:h}=await this.stepElementsForIntroducedSilentSteps(c,!1);this.stepElements={...this.stepElements,...g,[t]:i},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===si.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(i.map((t=>t.id)))}const d=[...h,...l.map((t=>new sn(t.id))),new $A(this.constructSerializableWorkflow())];d.length>0&&this.commandContext.apply(new An(d),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),A&&await A()}async ensureStepsAreLoaded(){const t=[],e=zs(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const i of e)if(!this.stepInitialised[i.stepName])switch(this.stepInitialised[i.stepName]=!0,i.type){case si.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case si.DigitalContent:t.push(eo.init(i,this,this.reloadedState));break;case si.Frame:case si.Photo:{const e=new Xs(i.data.forceImageCover);e.connectWorkflowManager(this,i.stepName),this.stepSpecificServices[i.stepName]={frameService:e},t.push(Ao.init(i,this,this.reloadedState))}break;case si.Illustration:t.push(no.init(i,this,this.reloadedState));break;case si.Material:t.push(ro.init(i,this,this.reloadedState));break;case si.Model:t.push(ao.init(i,this,this.reloadedState));break;case si.Module:this.stepSpecificServices[i.stepName]={module:await cs(i.data.module)},t.push(so.init(i,this,this.reloadedState));break;case si.Picture:t.push(oo.init(i,this,this.reloadedState));break;case si.Question:t.push(co.init(i,this,this.reloadedState));break;case si.Shape:t.push(lo.init(i,this,this.reloadedState));break;case si.Text:t.push(Bo.init(i,this,this.reloadedState))}const i=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),A=i.filter((t=>!!t&&!!t.command)).map((t=>t.command)),n=i.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));A&&A.length>0&&this.commandContext.apply(new An(A),!0);for(const t of n)await t();n.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((t=>t(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((t=>t(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((t=>t(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((t=>t(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((t=>t(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((t=>{t(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((t=>t(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((t=>{t(this.stepMetadata)}))}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach((e=>e(this.storage[t])))}onStorageChange(){this.storageCallbacks.forEach((t=>t(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((t=>{t(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((t=>{t(this.variationRecords)})),this.render3DScene()}traversableScenes(){return js(this.allScenes,this.stepSelections)}}function Qo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class yo{constructor(t){Qo(this,"variantData",void 0),this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.thumbnail?.versions?.find((t=>"cdn"===t.name))?.link}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find((t=>"thumbnail"===t.name));return t?t.link:this.variantData.asset?.versions?.find((t=>"thumbnail"===t.name))?.link}getDisplayImage(){return this.variantData.displayImage?.versions?.find((t=>"medium"===t.name))?.link}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}function Do(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}class Io{constructor(t,e){Do(this,"manager",void 0),Do(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Io.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Io.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new yo(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new yo(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new yo(t)))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),i=this.step.data.modelAnimation,A=this.step.data.lookAtAnimation;t&&A&&t.executeCameraAnimation(A),e&&i&&e.executeAnimation(i)}}function xo(t,e,i){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var i=t[Symbol.toPrimitive];if(void 0!==i){var A=i.call(t,e||"default");if("object"!=typeof A)return A;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:i,enumerable:!0,configurable:!0,writable:!0}):t[e]=i,t}Do(Io,"updateState",new Map);const vo=t.gql`
471
471
  mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
472
472
  transactionAddStakeholder(id: $id, details: $details, type: $type) {
473
473
  id
package/dist/module.js CHANGED
@@ -467,7 +467,7 @@ import{CommandContext as t,AssetType as e,BringForwardCommand as A,BringToFrontC
467
467
  workflowState
468
468
  }
469
469
  }
470
- `,Ln=t=>{const e=[];for(const A of t.steps)switch(A.type){case m.DigitalContent:A.data.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Frame:const t=A.data;t.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),t.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Illustration:const n=A.data;n.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),n.varyColors&&n.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Colors});break;case m.Material:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Model:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Picture:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Question:A.data.varySelections&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selections});break;case m.Shape:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Text:const i=A.data;i.varyText&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Text}),i.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),i.varyColor&&i.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Color})}return e},Tn=[m.SilentIllustration,m.ProductOverlay],On=async(t,e,A)=>{const n=[];t.introduction&&n.push({name:"Introduction",title:t.name,renderableSteps:[{type:m.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const A of t.steps){if(e.bulkScene){let t=!1;switch(A.type){case m.DigitalContent:A.data.varyUpload&&(t=!0);break;case m.Frame:{const e=A.data;!e.varyUpload||!e.varySelection&&A.option||(t=!0)}break;case m.Illustration:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case m.Material:A.data.varySelection&&(t=!0);break;case m.Model:A.data.varySelection&&(t=!0);break;case m.Picture:A.data.varySelection&&(t=!0);break;case m.Question:A.data.varySelections&&(t=!0);break;case m.Shape:A.data.varySelection&&(t=!0);break;case m.Text:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const i=zn(A.stepName,t.stepGroups);if(i){const t=n.find((t=>t.name===i.name));t?Tn.includes(A.type)?t.silentSteps.push(A):t.renderableSteps.push(A):n.push({name:i.name,title:i.name,renderableSteps:Tn.includes(A.type)?[]:[A],silentSteps:Tn.includes(A.type)?[A]:[]})}else n.push({name:A.stepName,title:A.stepTitle,renderableSteps:Tn.includes(A.type)?[]:[A],silentSteps:Tn.includes(A.type)?[A]:[]})}if(e.bulkScene){const i=A?.product?.bulkConfiguration;n.push({name:"Bulk",title:i?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:m.Bulk,stepName:"Bulk",stepTitle:i?.stepTitle??e.bulkSceneTitle,helpText:i?.helpText,data:{aspects:Ln(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&n.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:m.Finish,stepName:"Finish",stepTitle:e.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),n},zn=(t,e)=>e.find((e=>e.stepNames.includes(t))),jn=(t,e)=>(t.conditions||[]).every((t=>{const A=e[t.targetStepName];if(A&&A.selectedVariants){const e=A.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),Kn=(t,e)=>t.map((t=>((t,e)=>{const A={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>jn(t,e))),silentSteps:t.silentSteps.filter((t=>jn(t,e)))};return 0===A.silentSteps.length&&0===A.renderableSteps.length?null:A})(t,e))).filter((t=>null!==t)),Vn=async(t,e)=>{const A=Kn(t,e),n=[];for(const t of A)for(const e of t.renderableSteps)if(e.type===m.Model||e.type===m.Material||e.type===m.Picture||e.type===m.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&n.push(e.stepName)}else n.push(e.stepName);const i=A.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of i)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return i};function Wn(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}function Xn(t,e,A,n){const i=A.width*t.zoom,a=A.height*t.zoom;if(n){const n=t,i=Math.max(e.width/A.width,e.height/A.height);n.zoom=Math.max(i,t.zoom);const a=A.width*n.zoom,o=A.height*n.zoom;return n.x=qn(t.x,e.width-a,0),n.y=qn(t.y,e.height-o,0),n}const o=t;return o.x=qn(o.x,-i,e.width),o.y=qn(o.y,-a,e.height),o}function qn(t,e,A){return Math.min(Math.max(t,e),A)}class Zn{constructor(t){Wn(this,"offsets",void 0),Wn(this,"forceImageCover",void 0),Wn(this,"targetElements",void 0),Wn(this,"imageData",void 0),Wn(this,"frameData",void 0),Wn(this,"_debouncedUpdateFrameOffsets",void 0),Wn(this,"minZoomScale",[.03]),Wn(this,"maxZoomScale",[20]),Wn(this,"onFrameDataChangeListeners",void 0),Wn(this,"onZoomChangeListeners",void 0),Wn(this,"workflowManager",void 0),Wn(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=Xt(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback((async t=>{if(t){const e=t;if(e.currentFrameSources){let t=!1;for(let A=0;A<e.currentFrameSources.length;A++){const n=e.currentFrameSources[A],i=await N(n);Ot(i,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[A]=i,t=!0)}t&&(this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){t?t.forEach(((e,A)=>{const n=M.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[A]=n)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,A,n){if(this.imageData&&this.offsets&&this.frameData){this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length));const i=this.frameData.map(((n,i)=>{const a=(e[i]-this.offsets[i].x)/this.offsets[i].zoom,o=(A[i]-this.offsets[i].y)/this.offsets[i].zoom;return{x:e[i]-a*t[i],y:A[i]-o*t[i],zoom:this.imageData.width*t[i]/this.imageData.width}}));this.updateOffsets(i,n),this.onZoomChangeListeners.forEach((e=>e(t)))}}setPatternData(t){this.imageData=t,t&&this.frameData&&(this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,A){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new re("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,A)=>t[A].x!==e.x||t[A].y!==e.y||t[A].zoom!==e.zoom))||A?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=Xn(t[A],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.targetElements,e)):e&&e()}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,A,n,i){if(!A||0===A.length||A.some((t=>!t)))throw new re("Frame data not set. This is a bug");if(!this.workflowManager)throw new re("No workflow manager set, cannot update offsets.");const a=this.workflowManager.getCommandDispatcher();n.forEach(((A,n)=>{a(new et(A,e,t[n]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){this.minZoomScale.length===e.length&&this.maxZoomScale.length===e.length||(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach(((e,A)=>{const n=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[A]=n,this.maxZoomScale[A]=2.5*n):(this.minZoomScale[A]=n/10,this.maxZoomScale[A]=2.5*n)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=tt(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function $n(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class _n{constructor(t,e,A){$n(this,"configuration",void 0),$n(this,"layouts",void 0),$n(this,"product",void 0),$n(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new Ae(t);let A="";if(this.configuration.type===m.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),A=t,!t)throw new ae(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===h.Image){const A=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!A)throw new Error("Undefined raster silent step source");const i={stepName:this.configuration.stepName,id:F(),src:A,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,productOverlay:this.configuration.type===m.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:i.id,region:t},command:new o(i,e)}}{const i=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:A,a=async()=>new Promise(((t,e)=>{i?nt(i).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),r=await S(await a()),s={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await dt(r.svg),src:i,svg:r.svg,colors:r.colors,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,immutable:t.immutable,productOverlay:this.configuration.type===m.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new o(s,e)}}})),this.configuration=t,this.layouts=e,this.product=A||void 0}async trigger(){if(!this.configuration.data.regions)throw new ae(this.configuration,"Missing regions.");if(this.configuration.type===m.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===m.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new Ae(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===m.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?h.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),h.Illustration)}}const ti=async t=>{const e=`${Ee.getServicesApiUrl()}/shortener`;try{const A=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await A.json()).shortUrl}catch(t){throw console.error(t),new ge("Failed to shorten URL, see console.")}};function ei(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Ai{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(t){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,A,n=3e3,i=10){ei(this,"pollingId",void 0),ei(this,"attempts",void 0),ei(this,"interval",void 0),ei(this,"maxAttempts",void 0),ei(this,"predicate",void 0),ei(this,"onSuccess",void 0),ei(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=A,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=i,this.poll()}}const ni=new class{async init(t,e,A){return A&&await this.reload(t,e,A),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],i,(async()=>{const A=n?.storage?.videoShortUrl,i=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:A,videoUrl:i})}))}async regenerateQRCode(t,e,A,n,i,a,o,r,c){if(e||""===A||""!==n)c(!1);else{const e=async()=>{const t=(await Ne([A]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},g=await new Promise(((t,A)=>{new Ai((async()=>!!(await e()).link),(async()=>{const A=await e();if(!A.link||!A.link)throw new ie(A.asset);t({rel:"mpeg4",href:A.link})}),(()=>{A("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>r(new s(t.id))));const l="http"===a.data.baseUrl.slice(0,4)?"":"https://",B=new URL(l+a.data.baseUrl);B.searchParams.append("video",btoa(JSON.stringify([g]))),B.pathname=B.pathname+("/"===B.pathname.slice(-1)?"":"/");const w=B.toString();if(w.length>=2e3)throw new ge("Cannot create QR code, URL too long.");const d=await ti(w);if(o(d),!a.data||!a.data.regions)throw new ae(a,"Missing regions.");const h=await this.regionElements(a),E=await this.command(d,h,i,a.stepName);E&&(E.command&&i.getCommandDispatcher()(E.command),E.followup&&await E.followup()),await i.setSelectionsAndElements(a.stepName,[],h,(async()=>{i.updateStorage(a.stepName,{videoShortUrl:d,videoUrl:n}),c(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:F(),region:t})))}async command(t,e,A,n){const i=A.getLayouts(),a=`data:image/svg+xml;base64,${btoa(await Vt(t,{type:"svg"}))}`,r=e.map((t=>{const e=t.region,A=i.find((t=>t.panelId===e?.panelId));if(!A&&e)throw new Ae(e);if(A&&!e)throw new Error("Region not found");if(!A||!e)throw new Error("Neither a region or layout found!");return new o({stepRegion:e,stepName:n,id:t.id,src:a,type:h.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},A)}));return{command:new w(r),followup:async()=>{}}}};function ii(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const ai=new class{constructor(){ii(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Et(e);const A=t.asset;if(!A)throw new ne(t);const n=A.fileLink;if(n)return nt(n);throw new ie(A)}))}async init(t,e,A){if(A)return await this.reload(t,e,A),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const A=t.option,n=ke.getDefaultVariant(A);return n?this.selectVariantCommand(t,n,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const A=t.data.regions.map((t=>Et(t)));e.updateStorage(t.stepName,{currentFrameSources:A})}if(n){const A=async()=>{const A=n.storage?.framePatternSrc,i=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:i,framePatternSrc:A}),A){const n=e.getStepSpecificServices(t.stepName)?.frameService;if(!n)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,n),e.updateMetadata(t.stepName,{image:A}),e.updateStorage(t.stepName,{framePatternSrc:A})}if(i?.some((t=>t.zoom))){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");A.updateOffsets(i)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const a=n.selectedVariants[0].id;if(t.option&&a){const n=t.option.variants?.find((t=>t.id===a));n&&await e.setSelectionsAndElements(t.stepName,[n],i,(async()=>{const i=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(n,t))));e.updateStorage(t.stepName,{currentFrameSources:i}),await A()}))}}else await e.setSelectionsAndElements(t.stepName,[],i,A)}}selectImage(t,e,A){A.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?A.addPoller(new Ai((async()=>{const t=(await He.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{He.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,A)}))}),(()=>{throw new ge("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,A)}async selectVariant(t,e,A,n,i){const a=await this.selectVariantCommand(t,e,A,n,i);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}getCreateElementCommand(t,e,A,n){return new o({id:t,type:h.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:e.immutable},A)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const A=await Ct(t),n=A.width,i=A.height,a={src:t,width:n,height:i,aspect:n/i};b.set(t,a),e.setPatternData(a)}else{const A=await st(t),n=await v(A),i={src:t,width:n.width,height:n.height,aspect:n.width/n.height};b.set(t,i),e.setPatternData(i)}}async selectVariantCommand(t,e,A,n,i,a){const o=n.getStepSpecificServices(t.stepName)?.frameService;if(!o)throw new Error("Frame service unavailable, cannot load pattern!");const r=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));i&&i(!0);const c=await Promise.all(t.data.regions.map((async(e,i)=>{const a=await N(r[i]),c=o.getImageData(),g=A.map((t=>new s(t.id))),l=c?tt(c,a):void 0,B=c?{id:F(),src:c.src,x:l?.x||0,y:l?.y||0,width:c.width,height:c.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,w=F(),d=n.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new Ae(e);return{command:this.getCreateElementCommand(w,e,d,{frameData:a,pattern:B,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:w,region:e},removeExistingCommands:g}}))),g=c.map((t=>t.command)),l=c.map((t=>t.removeExistingCommands)).flat();return{command:new w([...g,...l]),followup:async()=>{i&&i(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...c.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:r}),a){const e=n.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(a,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const A=t.fileLink;if(A)return A;throw new ie(t)}async loadPatternFromAsset(t,e,A){const n=this.patternSource(t),i=A.markUpdatePending(),a=A.getStepSpecificServices(e.stepName)?.frameService;if(!a)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(n,a),A.updateMetadata(e.stepName,{image:n}),A.updateStorage(e.stepName,{framePatternSrc:n}),A.markUpdateCompleted(i)}};const oi=new class{async getIllustrationBody(t){return new Promise((e=>{nt(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,A,n){return new o({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:h.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},A)}getColors(t,e){const A=e.getRegionElements(t.stepName)||[];if(0===A.length)return[];try{return y(A[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,A){const n=t.option;if(!n)return null;if(A)return this.reload(t,e,A);{const A=ke.getDefaultVariant(n);if(A)return await this.selectVariantCommand(t,A,[],(()=>{}),e)}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(!a||!A)throw new Error("Required illustration variant no longer available");{const o=a.variants?.find((t=>t.id===A));if(o){const A=i.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[o],A,(async()=>{e.updateMetadata(t.stepName,{colors:n.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const A=t.data.colorOption;return A&&A?A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,A,n,i){const a={};for(const[t,e]of i.entries())a[t]={browserValue:e,spotColor:a[t]?.spotColor};const o=ut(t,e,A,a),r=await dt(o),s=[];for(const t of n){for(const[e,A]of i.entries())s.push(new Qt(t,e,A));s.push(new pt(t,o,r))}return new w(s)}async changeColors(t,e,A,n,i){if(0===e.length)return;const a=y(e[0].id,n().map((t=>t.layoutState))),o={...a.colors},r={};Object.entries(o).forEach((([t,e])=>{const A={browserValue:e.browserValue},n=e.spotColor;n&&(A.spotColor={profileName:n.profileName,namedColor:n.namedColor}),r[t]=A}));for(const[t,e]of i.entries())o[t]={browserValue:e,spotColor:o[t]?.spotColor},r[t]={browserValue:e};let s=Array.from(Object.values(o)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{s=s.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),A.updateMetadata(t.stepName,{colors:s});const g=new Map;if(Object.entries(o).forEach((([t,e])=>{g.set(t,e.browserValue)})),!a.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const l=await this.changeColorsCommand(a.svg,a.width,a.height,e.map((t=>t.id)),g);A.updateStorage(t.stepName,{colors:r}),A.getCommandDispatcher()(l)}async selectVariant(t,e,A,n,i){const a=await this.selectVariantCommand(t,e,A,n,i);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,A,n,i){if(!t.data||!t.data.regions)throw new ae(t,"Missing regions.");n(!0);const a=A.map((t=>new s(t.id)));i.setMandatoryFulfilled(t.stepName,!1);const o=e.asset;if(!o)throw new ne(e);const r=o.fileLink;if(!r)throw new ie(o);const c=await S(await this.getIllustrationBody(r)),g=await dt(c.svg),l=t.data.regions.map((e=>{const A=i.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new Ae(e);const n=F();return{regionElement:{id:n,region:e},command:this.getCreateElementCommand(n,e,A,{stepName:t.stepName,src:r,objectURL:g,svg:c})}})),B=[...l.map((t=>t.command)),...a];let d=Array.from(Object.values(c.colors)).map((t=>t.browserValue));const h=t.data.colorOption;return h&&h.variants?.forEach((t=>{d=d.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),i.updateMetadata(t.stepName,{colors:d}),{command:new w(B),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const ri=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=ke.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(!a)throw new ee(t);if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(A){const n=a.variants?.find((t=>t.id===A));if(n){const A=n.material,o=i.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],o,(async()=>{const n=e.getModelContainer();if(n){const i=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,a.id||"",A||{})));Promise.all(i).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,A,n){const i=await this.selectVariantLambda(t,e,A,n);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,A,n){const i=A.getModelContainer();n(!0);const a=e.material;if(!a)throw n(!1),new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{i&&t.data.targetMaterials.forEach((e=>{t.option&&i.applyMaterialVariant(e,t.option.id||"",a)})),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const si=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=ke.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const n=a.variants?.find((t=>t.id===A));if(n){const A=i.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{const A=e.getModelContainer();if(A&&t.option){const i=n.asset?.fileLink;if(!i)throw new ne(n);await A.applyModelVariant(t.option.id||"",{model:i,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,A,n){const i=await this.selectVariantLambda(t,e,A,n);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,A,n){n(!0);const i=e.asset?.fileLink;if(!i)throw new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=A.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:i,contextService:A.getLayoutPreviewService()},t.data.replaceProductModel||!1),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const ci=new class{async init(t,e,A){return A?(await this.reload(t,e,A),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],i,(async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,e,A,n,i){const a=await this.changeTextCommand(t,e,A,n,i);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async changeTextCommand(t,e,A,n,i){const a=A.getRegionElements(t.stepName),r=A.getStepSpecificServices(t.stepName)?.module;if(!r)return console.error("Missing module."),null;const c=A.getProfanities();if(!this.validateInput(t,e,c,i))return A.setMandatoryFulfilled(t.stepName,!1),console.error(n),null;if(A.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;A.updateStorage(t.stepName,{text:e});const g=(e,n,i)=>{const a=i||F(),r=A.getLayouts().find((t=>t.panelId===n.panelId));if(!r)return console.error(`Can not find layout for region: ${n.panelId}`),null;const c=[];return i&&c.push(new s(a)),c.push(new o({stepRegion:n,stepName:t.stepName,colors:{},id:a,svg:e,type:h.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},r)),{id:a,region:n,command:new w(c)}};if(a.length>0){const t=a.map((t=>{if(!t.region)return null;const A=r.svgPrint(e,t.region);return g(A,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new w(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>g(r.svgPrint(e,t),t))),i=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new w(i),followup:async()=>{const e=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await A.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,A,n){if(t.data&&t.data.maxLength){const A=t.data.maxLength;if(e.length>A)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),!1;const i=qt(e.toLowerCase());for(const t of i)for(const e in A){if(t===A[e].toLowerCase().replace(/\s/g,""))return n("Blocked profanity."),!1}return n(""),!0}};const gi=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const n=a.variants?.find((t=>t.id===A));if(n){const A=i.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,A,n){const i=await this.selectVariantCommand(t,e,A,n);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,A,n){const i=e.asset;if(!i)throw new ne(e);const a=i?.fileLink;if(!a)return console.error("No URL for picture!"),null;n(!0),A.setMandatoryFulfilled(t.stepName,!1);const r=A.getRegionElements(t.stepName).map((t=>new s(t.id))),c=t.data.regions.map((e=>{const n=A.getLayouts().find((t=>t.panelId===e.panelId));if(!n)throw new Ae(e);const i=F();return{regionElement:{id:i,region:e},command:new o({stepName:t.stepName,stepRegion:e,id:i,src:a,type:h.Image,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,preserveAspectRatio:"none"},n)}}));return{command:new w([...r,...c.map((t=>t.command))]),followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],c.map((t=>t.regionElement)),(async()=>{A.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const li=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=n.variants;if(ke.getDefaultVariant(n)){const i=A?.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,i?.id||"",e)}}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));n&&await e.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,e,A){await A.getInitializationPromise();const n=await this.selectVariantLambda(t,e,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,A){const n=t.option;if(!n)return null;const i=n.variants;if(!i)return null;const a=i.length>1?i.find((t=>t.id===e)):i[0];if(!a)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[a],[],(async()=>{A.setMandatoryFulfilled(t.stepName,!0)}))}}}};const Bi=new class{async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(!A){const A=ke.getDefaultVariant(n);if(!A)return null;const i={fill:A.color,stroke:A.color,variant:A};return this.selectVariantCommand(t,i,[],e)}return await this.reload(t,e,A),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const n=a.variants?.find((t=>t.id===A));if(n){const A=i.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{e.updateStorage(t.stepName,{colour:n.color||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,A,n){const i=await this.selectVariantCommand(t,e,A,n);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,A,n){const i=n.getLayouts();if(A.length>0){const a=t=>{const A=t.region;if(!i.find((t=>t.panelId===A?.panelId)))throw new Ae(A);const n=e.variant?.color;return n?new Qt(t.id,"spiff-fill-shape",n):(console.error("Failed to change color."),null)},o=A.map(a).filter((t=>!!t));return{command:new w(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],A),n.updateStorage(t.stepName,{colour:e.fill||""})}}}{const A=A=>{const n=i.find((t=>t.panelId===A.panelId));if(!n)throw new Ae(A);const a=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${e.variant?.color}"\n />\n </svg>\n `,r={};r["spiff-fill-shape"]={browserValue:e.variant.color};const s=F();return{id:s,region:A,command:new o({stepRegion:A,stepName:t.stepName,colors:r,id:s,svg:a,type:h.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,excludeFromExport:t.data.excludeFromPrint},n)}},a=t.data.regions.map(A),r=a.filter((t=>!!t)).map((t=>t?.command)),s=a.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new w(r),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],s,(async()=>{n.updateStorage(t.stepName,{colour:e.fill||""})}))}}}}};function wi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class di extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=di.name}}const hi=["‘","’","“","”","\n"];class Ei extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ei.name}}const Ci=new class{constructor(){wi(this,"cachedColors",new Map),wi(this,"filterUnsupportedCharacters",((t,e)=>{let A=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],i=e?mt(e):void 0;if(i){const t=A.split("").filter((t=>!hi.includes(t))).join(""),e=t.split("").map((t=>i.getFont().charToGlyph(t)));for(let A=0;A<e.length;A++){".notdef"===e[A].name&&n.push(String.fromCharCode(t.charCodeAt(A)))}}for(let t=0;t<n.length;t++)A=A.replaceAll(n[t],"");return A})),wi(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),wi(this,"getErrorsForText",((t,e,A)=>{const n=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const i=A.getProfanities(),a=qt(t.toLowerCase());for(const t of a)for(const e in i){if(t===i[e].toLowerCase().replace(/\s/g,"")){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=this.getDefaultImageFillVariant(t.data),i=A?.asset?.fileLink,a=i?await Z(i):void 0,o=a?{src:a.src,height:a.height,width:a.width,scale:t.data.imageFillScale||1}:void 0;e.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:o}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:A?.name});const r=ke.getDefaultVariant(n);if(r)return this.selectVariantCommand(t,r,{},[],e,(()=>{}),(()=>{}),o)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>y(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const A=t.data.colorOption;if(A){const e=A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,A,n){if(!t.data||!t.data.regions)return;const i=n.getCommandDispatcher();e.variant?n.updateMetadata(t.stepName,{color:e.variant.name}):n.updateMetadata(t.stepName,{color:e.fill});const a=t.data.colorOption,o=a?this.createTextFillSpotColor(a,e.variant):void 0;a?n.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:a.colorProfile?.key}):n.updateStorage(t.stepName,{color:e.fill});for(const t of A){if(!e.fill)throw new Error("Fill not set on new color selection!");i(new g(t.id,e.fill,o))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const A=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(A.map((async e=>{const A=await Z(e);return{src:e,width:A.width,height:A.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,A,n){if(!t.data||!t.data.regions)return;const i=n.getCommandDispatcher(),a=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));n.updateMetadata(t.stepName,{fillImage:a?.name}),n.updateStorage(t.stepName,{fillImage:e});for(const t of A){i(new Dt(t.id,e))}}getProcessedInput(t,e,A){const n=A?t:this.injectReplaceableText(t,e);return lt(n,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,A,n){const i=n.getStepStorage(A.stepName),a=this.getProcessedInput(t,A.data,!!i.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(t,A,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const r=(A.data.maxLength-a.length).toString();o.helperText=`${r} characters remaining`;const s=n.getTransaction().bulk&&A.data.varyText||!1,c=[],g=new Map,l=new Map;for(const t of e){if(!t.fontData)throw new re("Failed to resolve font data for text.");const[e,n]=U(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[a],{size:A.data.size,minSize:A.data.minSize,maxSize:A.data.maxSize});g.set(t.id,e),l.set(t.id,n);const i=A.data.curved?a:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,A.data,t.id,i,s))}if(!A.data.curved&&e.length>0){if(!Array.from(l.values()).every((t=>t)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(A.stepName,{text:t}),n.updateMetadata(A.stepName,{text:a}),i.defaultCleared&&n.setMandatoryFulfilled(A.stepName,!0),o.command=new w(c),o.command.varying=s,o}async selectVariant(t,e,A,n,i){const a=await this.selectVariantCommand(t,e,A.getStepStorage(t.stepName)||{},A.getRegionElements(t.stepName),A,n,i);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}createTextFillSpotColor(t,e){const A=t.colorProfile;if(A){const t=(A.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),i=t.slice(n+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:i,namedColor:e.namedColor}}}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const o=a.variants?.find((t=>t.id===A));if(o){const A=await this.fontDataFromVariant(o),a=i.map((t=>({id:t.id,region:t.stepRegion}))),r=n.storage?.color,s=n.storage?.text;await e.setSelectionsAndElements(t.stepName,[o],a,(async()=>{e.updateMetadata(t.stepName,{color:r,text:s}),e.updateStorage(t.stepName,{text:s,inputText:s});const n=i.map((t=>new B(t.id,A))),a=new w(n);e.getCommandDispatcher()(a),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=Ci.updateInputText(s||"",i,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return ke.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return ke.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return ke.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ne(t);const A=e.fileLink;if(!A)throw new ie(e);return{assetUrl:A,name:(await H(A)).names.fullName.en}}async selectVariantCommand(t,e,A,n,i,a,o,r){const s=i.markUpdatePending(),c=await this.fontDataFromVariant(e);if(n.length>0){const g=n.map((t=>new B(t.id,c)));if(r){const t=n.map((t=>new Dt(t.id,r)));g.push(...t)}const l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A.text||"",A,i,!!A.customiseAllText,a,o);l&&g.push(l);return{command:new w(g),followup:async()=>{i.markUpdateCompleted(s),await i.setSelectionsAndElements(t.stepName,[e],n)}}}{const n=await this.createTextboxRegions(t.stepName,e,t.data,c,A,i),g=await this.changeInputTextWithRegion(t,t.data.size||30,c,n[0]?.newElement.input||A.text||t.data.defaultText||"",A,i,!!A.customiseAllText,a,o),l=n.flatMap((t=>t.commands));if(r){const t=n.map((t=>new Dt(t.regionElement.id,r)));l.push(...t)}g&&l.push(g);return{command:new w(l),followup:async()=>{i.markUpdateCompleted(s)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,A,n,i,a){if(!A||!A.regions)throw new Error("Step data not supplied");const r=a.getTransaction().bulk&&A.varyText||!1,s=r?"":i.text||A.defaultText||"",c=this.getProcessedInput(s,A,!1),g=await Promise.all(A.regions.map((async e=>{const g=a.getLayouts().find((t=>t.panelId===e.panelId)),l=F();try{if(!g)throw new Ei("Failed to find layout for region: "+e.panelId);const B=A.colorOption;let w;if(B&&B.variants){const e=B.variants.find((t=>t.id===B.defaultVariant?.id))||B.variants[0];w=this.createTextFillSpotColor(B,e),a.updateStorage(t,{colorProfileAssetKey:B.colorProfile?.key})}const d=await this.getDefaultColor(A),E=d||"#000000",C={stepRegion:e,stepName:t,align:this.textAlign(A),fill:i.color?i.color:E,fontSize:A.size||30,fontData:n,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:c,input:s,type:h.Textbox,vertical:A.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:A.verticalAlign||"middle",curved:A.curved,paths:A.paths,fillSpotColorDefinition:w},u=[],Q=new Map,p=new Map;if(!C.fontData)throw new re("Failed to resolve font data for text.");const[m,D]=U(C.fontSize,C.fontData,{left:C.x,top:C.y,width:C.width,height:C.height,rotation:C.rotation,panelId:""},[c],{size:A.size,minSize:A.minSize,maxSize:A.maxSize});Q.set(C.id,m),p.set(C.id,D);const I=A.curved||A.vertical?c:(D||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(m,A,C.id,I,r));const f=new o(C,g);return f.varying=r,{regionElement:{id:l,region:e},commands:[f,...u],newElement:C,fontData:n}}catch(t){throw console.log(t),new di("Error adding font to region")}}))).catch((t=>{throw t instanceof di?(gA.setLatestToast("Failed to load font.",Qi.Error),t):t instanceof Ei?t:new Error(t)}));return await a.setSelectionsAndElements(t,[e],g.map((t=>t.regionElement)),(async()=>{a.updateMetadata(t,{text:s}),a.updateStorage(t,{text:s})})),g}generateTextChangeCommandsForRegion(t,e,A,n,i){const a=[],o=new D(A,n);if(o.varying=i,a.push(o),!e.size){const e=new l(A,t);e.varying=i,a.push(e)}const r=new w(a);return r.varying=i,r}async changeInputTextWithRegion(t,e,A,n,i,a,o,r,s,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),l=this.getProcessedInput(g,t.data,o),B=a.getRegionElements(t.stepName),d=new Map,h=new Map;for(const n of B)if(n.region){const[i,a]=U(e,A,n.region,[l],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(n.id,i),h.set(n.id,a)}const E=(()=>{if(t.data&&t.data.maxLength&&l.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=a.getProfanities(),A=qt(l.toLowerCase());for(const t of A)for(const A in e){if(t===e[A].toLowerCase().replace(/\s/g,""))return r(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(l.includes("\n")||l.includes("\r")))return r(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(h.values()).every((t=>t)))return r(!0),{error:"Does not fit."}}return r(!1),{info:(t.data.maxLength-l.length).toString()}})();if(E.error)return void s(E.error);if(s(`${E.info} characters remaining`||""),c)return;a.updateStorage(t.stepName,{text:g}),a.updateMetadata(t.stepName,{text:this.injectReplaceableText(g,t.data)});const C=a.getTransaction().bulk&&t.data.varyText||!1;i.defaultCleared&&a.setMandatoryFulfilled(t.stepName,!0);const u=[];for(const e of B){const A=t.data.curved?l:(h.get(e.id)||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(d.get(e.id)||1,t.data,e.id,A,C))}const Q=new w(u);return Q.varying=C,Q}};function ui(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let Qi;var pi;(pi=Qi||(Qi={})).Error="Error",pi.Warning="Warning",pi.Info="Info";class mi extends OA{constructor(t){super(),ui(this,"update",void 0),ui(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Di{constructor(t,e,A,n,i,a,o,r,s,c,g=!1,l,B=!1){ui(this,"reloadedState",void 0),ui(this,"transaction",void 0),ui(this,"ownerCustomer",void 0),ui(this,"updateTransaction",void 0),ui(this,"confirmedDesign",void 0),ui(this,"editedSteps",void 0),ui(this,"informationResults",void 0),ui(this,"layouts",void 0),ui(this,"mandatorySteps",void 0),ui(this,"pendingUpdates",void 0),ui(this,"selectionCost",void 0),ui(this,"workflow",void 0),ui(this,"stepSpecificServices",void 0),ui(this,"previewService",void 0),ui(this,"profanityFilter",void 0),ui(this,"pollers",void 0),ui(this,"commandContext",void 0),ui(this,"stepElements",void 0),ui(this,"stepInitialised",void 0),ui(this,"stepMetadata",void 0),ui(this,"stepSelections",void 0),ui(this,"storage",void 0),ui(this,"confirmCallbacks",void 0),ui(this,"editedCallbacks",void 0),ui(this,"elementsCallbacks",void 0),ui(this,"informationResultCallbacks",void 0),ui(this,"initCallbacks",void 0),ui(this,"makingAdjustmentsCallback",void 0),ui(this,"mandatoryCallbacks",void 0),ui(this,"metadataCallbacks",void 0),ui(this,"selectionCallbacks",void 0),ui(this,"stepSpecificStorageCallbacks",void 0),ui(this,"storageCallbacks",void 0),ui(this,"currentVariationRecordCallbacks",void 0),ui(this,"variationRecordCallbacks",void 0),ui(this,"allScenes",void 0),ui(this,"product",void 0),ui(this,"invalidModelVariants",void 0),ui(this,"currentAdjustingStepId",void 0),ui(this,"renderableContextService",void 0),ui(this,"workflowStatePromiseQueue",new zA(1)),ui(this,"variationRecords",[]),ui(this,"currentVariationRecord",void 0),ui(this,"initializationPromise",void 0),ui(this,"initialized",!1),ui(this,"readOnly",!1),ui(this,"modelContainer",void 0),ui(this,"isReloadedTransaction",!1),ui(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,A]of e)A.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=i,this.commandContext=n,this.reloadedState=c,this.transaction=a,this.readOnly=g,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=e,this.pollers=[],this.allScenes=[],this.layouts=A,this.product=o,this.previewService=r,this.modelContainer=l,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=s,this.currentVariationRecord=null,this.isReloadedTransaction=B,this.initializationPromise=this.initializeDefaultWorkflowState(t,a),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((t=>{throw console.error(t),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>{this.updateStateWithServer(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,e){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await On(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const A=Kn(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:i}=await this.stepElementsForIntroducedSilentSteps(A,!!this.reloadedState);this.commandContext.apply(new w(i),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,A=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),A&&this.modelContainer?.executeAnimation(A)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const e={...t,recordNumber:this.variationRecords.reduce(((t,e)=>e.recordNumber>t?e.recordNumber:t),0)+1};return this.variationRecords.push(e),this.onVariationRecordsChange(),e}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((e=>e.recordNumber!==t)),this.variationRecords.forEach(((t,e)=>t.recordNumber=e+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,e=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(e||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(t){this.variationRecords=t,this.onVariationRecordsChange(),0===t.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(t[0])}setCurrentVariationRecord(t){if(this.currentVariationRecord=t,this.onCurrentVariationRecordChange(),t){const e=this.variationRecords.find((e=>e.recordNumber===t.recordNumber));e&&(e.values=t.values,this.onVariationRecordsChange())}}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addCurrentVariationCallback(t){t(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(t)}addVariationRecordsCallback(t){t(this.variationRecords),this.variationRecordCallbacks.push(t)}addPoller(t){this.pollers.push(t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((t=>t.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t)}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach((e=>{const A=this.stepSelections[e.stepName];A&&A.selectedVariants&&A.selectedVariants.length>0&&(t[e.stepName]={selections:A.selectedVariants})})),t}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach((t=>{e[t]=!0})),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((e=>e!==t))}markUpdatePending(){const t=F();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t){if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const e=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()});this.setModelContainer(e),await e.getInitializationPromise(),this.render3DScene()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}async updateStorage(t,e){const A={...this.storage,[t]:{...this.storage[t],...e}};if(!Ot(A,this.storage)){this.storage=A;const e=new ht(this.constructSerializableWorkflow());this.commandContext.apply(e,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((e=>{e.renderableSteps.forEach((e=>{const A={stepName:e.stepName};A.storage=this.storage[e.stepName],A.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(A)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new mi((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new mi((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new re("Attempted to serialize state before it was initialized.");const e=JSON.stringify(this.dehydrateState(zt(t.transaction))),A=t.variation;if(!A)return{transaction:e};const n={layouts:{},serializableWorkflow:{steps:[]},...zt(A)||{}};return{transaction:e,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(t){for(const e of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===e.type&&(delete e.cachedObjectURL,e.src&&delete e.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,e)=>Object.keys(t).reduce(((A,n)=>{const i=[...t[n]||[]];return e.forEach((t=>{const e=i.findIndex((e=>e.id===t.id));e>-1&&i.splice(e,1)})),A[n]=i,A}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(jn(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach((e=>t.push(e))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,e)=>("Model"===e.type&&e.option?.id&&!jn(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const A=this.product;if(!A)return Promise.resolve({stepElements:{},commands:[]});const n=async(t,e,A)=>{if(t.type===m.SilentIllustration){return{step:t,results:await new _n(t,e).trigger()}}if(t.type===m.ProductOverlay){return{step:t,results:await new _n(t,e,A).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter((t=>!this.stepInitialised[t.stepName])),a={stepElements:{},commands:[]},o=[];for(const t of i)this.markStepsAsInitialised([t.stepName]),e||o.push(n(t,this.layouts,A));const r=await Promise.all(o);for(const t of r)a.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),a.commands=[...a.commands,...t.results.map((t=>t.command))];return a}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,e){return e.find((e=>e.stepName===t))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((t=>t.layoutState.elements.forEach((t=>{this.getCommandDispatcher()(new s(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,A,n){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,e)=>t+e.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,e)=>t+e),0)),0),this.workflow.steps.forEach((t=>{jn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const a=this.allScenes,o=Kn(a,i),r=Kn(a,this.stepSelections),c=o.map((t=>t.silentSteps)).flat(),g=r.map((t=>t.silentSteps)).flat().filter((t=>!c.some((e=>e.stepName===t.stepName))));c.forEach((t=>{jn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:B,commands:d}=await this.stepElementsForIntroducedSilentSteps(g,!1);this.stepElements={...this.stepElements,...B,[t]:A},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===m.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(A.map((t=>t.id)))}const h=[...d,...l.map((t=>new s(t.id))),new ht(this.constructSerializableWorkflow())];h.length>0&&this.commandContext.apply(new w(h),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],e=Kn(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const A of e)if(!this.stepInitialised[A.stepName])switch(this.stepInitialised[A.stepName]=!0,A.type){case m.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case m.DigitalContent:t.push(ni.init(A,this,this.reloadedState));break;case m.Frame:case m.Photo:{const e=new Zn(A.data.forceImageCover);e.connectWorkflowManager(this,A.stepName),this.stepSpecificServices[A.stepName]={frameService:e},t.push(ai.init(A,this,this.reloadedState))}break;case m.Illustration:t.push(oi.init(A,this,this.reloadedState));break;case m.Material:t.push(ri.init(A,this,this.reloadedState));break;case m.Model:t.push(si.init(A,this,this.reloadedState));break;case m.Module:this.stepSpecificServices[A.stepName]={module:await ln(A.data.module)},t.push(ci.init(A,this,this.reloadedState));break;case m.Picture:t.push(gi.init(A,this,this.reloadedState));break;case m.Question:t.push(li.init(A,this,this.reloadedState));break;case m.Shape:t.push(Bi.init(A,this,this.reloadedState));break;case m.Text:t.push(Ci.init(A,this,this.reloadedState))}const A=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),n=A.filter((t=>!!t&&!!t.command)).map((t=>t.command)),i=A.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new w(n),!0);for(const t of i)await t();i.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((t=>t(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((t=>t(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((t=>t(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((t=>t(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((t=>t(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((t=>{t(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((t=>t(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((t=>{t(this.stepMetadata)}))}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach((e=>e(this.storage[t])))}onStorageChange(){this.storageCallbacks.forEach((t=>t(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((t=>{t(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((t=>{t(this.variationRecords)})),this.render3DScene()}traversableScenes(){return Vn(this.allScenes,this.stepSelections)}}function Ii(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class fi{constructor(t){Ii(this,"variantData",void 0),this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.thumbnail?.versions?.find((t=>"cdn"===t.name))?.link}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find((t=>"thumbnail"===t.name));return t?t.link:this.variantData.asset?.versions?.find((t=>"thumbnail"===t.name))?.link}getDisplayImage(){return this.variantData.displayImage?.versions?.find((t=>"medium"===t.name))?.link}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}function yi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Mi{constructor(t,e){yi(this,"manager",void 0),yi(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Mi.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Mi.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new fi(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new fi(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new fi(t)))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),A=this.step.data.modelAnimation,n=this.step.data.lookAtAnimation;t&&n&&t.executeCameraAnimation(n),e&&A&&e.executeAnimation(A)}}function Fi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}yi(Mi,"updateState",new Map);const Yi=ft`
470
+ `,Ln=t=>{const e=[];for(const A of t.steps)switch(A.type){case m.DigitalContent:A.data.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Frame:const t=A.data;t.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),t.varyUpload&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Upload});break;case m.Illustration:const n=A.data;n.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),n.varyColors&&n.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Colors});break;case m.Material:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Model:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Picture:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Question:A.data.varySelections&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selections});break;case m.Shape:A.data.varySelection&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection});break;case m.Text:const i=A.data;i.varyText&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Text}),i.varySelection&&A.option&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Selection}),i.varyColor&&i.colorPickerEnabled&&e.push({stepName:A.stepName,stepType:A.type,aspectType:p.Color})}return e},Tn=[m.SilentIllustration,m.ProductOverlay],On=async(t,e,A)=>{const n=[];t.introduction&&n.push({name:"Introduction",title:t.name,renderableSteps:[{type:m.Introduction,stepName:"Introduction",stepTitle:t.name,helpText:t.introduction,data:{},conditions:[]}],silentSteps:[]});for(const A of t.steps){if(e.bulkScene){let t=!1;switch(A.type){case m.DigitalContent:A.data.varyUpload&&(t=!0);break;case m.Frame:{const e=A.data;!e.varyUpload||!e.varySelection&&A.option||(t=!0)}break;case m.Illustration:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColors&&e.colorPickerEnabled||(t=!0)}break;case m.Material:A.data.varySelection&&(t=!0);break;case m.Model:A.data.varySelection&&(t=!0);break;case m.Picture:A.data.varySelection&&(t=!0);break;case m.Question:A.data.varySelections&&(t=!0);break;case m.Shape:A.data.varySelection&&(t=!0);break;case m.Text:{const e=A.data;!e.varySelection&&A.option&&1!==(A.option.variants||[]).length||!e.varyColor&&e.colorPickerEnabled&&e.colorOption||!e.varyText||(t=!0)}}if(t)continue}const i=zn(A.stepName,t.stepGroups);if(i){const t=n.find((t=>t.name===i.name));t?Tn.includes(A.type)?t.silentSteps.push(A):t.renderableSteps.push(A):n.push({name:i.name,title:i.name,renderableSteps:Tn.includes(A.type)?[]:[A],silentSteps:Tn.includes(A.type)?[A]:[]})}else n.push({name:A.stepName,title:A.stepTitle,renderableSteps:Tn.includes(A.type)?[]:[A],silentSteps:Tn.includes(A.type)?[A]:[]})}if(e.bulkScene){const i=A?.product?.bulkConfiguration;n.push({name:"Bulk",title:i?.sceneTitle??e.bulkSceneTitle,renderableSteps:[{type:m.Bulk,stepName:"Bulk",stepTitle:i?.stepTitle??e.bulkSceneTitle,helpText:i?.helpText,data:{aspects:Ln(t)},conditions:[]}],silentSteps:[]})}return e.finishScene&&n.push({name:"Finish",title:e.finishSceneTitle,renderableSteps:[{type:m.Finish,stepName:"Finish",stepTitle:e.finishSceneTitle,helpText:"",data:{modelAnimation:t.finalizeStepConfig?t.finalizeStepConfig.modelAnimation:void 0,lookAtAnimation:t.finalizeStepConfig?t.finalizeStepConfig.lookAtAnimation:void 0},conditions:[]}],silentSteps:[]}),n},zn=(t,e)=>e.find((e=>e.stepNames.includes(t))),jn=(t,e)=>(t.conditions||[]).every((t=>{const A=e[t.targetStepName];if(A&&A.selectedVariants){const e=A.selectedVariants;return t.requiredVariantSelections.some((t=>void 0!==e.find((e=>e.id===t))))}return!1})),Kn=(t,e)=>t.map((t=>((t,e)=>{const A={name:t.name,title:t.title,renderableSteps:t.renderableSteps.filter((t=>jn(t,e))),silentSteps:t.silentSteps.filter((t=>jn(t,e)))};return 0===A.silentSteps.length&&0===A.renderableSteps.length?null:A})(t,e))).filter((t=>null!==t)),Vn=async(t,e)=>{const A=Kn(t,e),n=[];for(const t of A)for(const e of t.renderableSteps)if(e.type===m.Model||e.type===m.Material||e.type===m.Picture||e.type===m.Shape){const t=(e.option?.variants||[]).length;t&&t>1&&n.push(e.stepName)}else n.push(e.stepName);const i=A.filter((t=>t.renderableSteps.filter((t=>n.includes(t.stepName))).length>0));for(const t of i)t.renderableSteps=t.renderableSteps.filter((t=>n.includes(t.stepName)));return i};function Wn(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}function Xn(t,e,A,n){const i=A.width*t.zoom,a=A.height*t.zoom;if(n){const n=t,i=Math.max(e.width/A.width,e.height/A.height);n.zoom=Math.max(i,t.zoom);const a=A.width*n.zoom,o=A.height*n.zoom;return n.x=qn(t.x,e.width-a,0),n.y=qn(t.y,e.height-o,0),n}const o=t;return o.x=qn(o.x,-i,e.width),o.y=qn(o.y,-a,e.height),o}function qn(t,e,A){return Math.min(Math.max(t,e),A)}class Zn{constructor(t){Wn(this,"offsets",void 0),Wn(this,"forceImageCover",void 0),Wn(this,"targetElements",void 0),Wn(this,"imageData",void 0),Wn(this,"frameData",void 0),Wn(this,"_debouncedUpdateFrameOffsets",void 0),Wn(this,"minZoomScale",[.03]),Wn(this,"maxZoomScale",[20]),Wn(this,"onFrameDataChangeListeners",void 0),Wn(this,"onZoomChangeListeners",void 0),Wn(this,"workflowManager",void 0),Wn(this,"stepName",void 0),this._debouncedUpdateFrameOffsets=Xt(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback((async t=>{if(t){const e=t;if(e.currentFrameSources){let t=!1;for(let A=0;A<e.currentFrameSources.length;A++){const n=e.currentFrameSources[A],i=await N(n);Ot(i,this.frameData)||(this.frameData||(this.frameData=new Array(e.currentFrameSources.length)),this.frameData[A]=i,t=!0)}t&&(this.onFrameDataChangeListeners.forEach((t=>t(this.frameData))),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}}),e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){t?t.forEach(((e,A)=>{const n=M.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[A]=n)})):this.frameData=void 0}getImageData(){return this.imageData}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,A,n){if(this.imageData&&this.offsets&&this.frameData){this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length));const i=this.frameData.map(((n,i)=>{const a=(e[i]-this.offsets[i].x)/this.offsets[i].zoom,o=(A[i]-this.offsets[i].y)/this.offsets[i].zoom;return{x:e[i]-a*t[i],y:A[i]-o*t[i],zoom:this.imageData.width*t[i]/this.imageData.width}}));this.updateOffsets(i,n),this.onZoomChangeListeners.forEach((e=>e(t)))}}setPatternData(t){this.imageData=t,t&&this.frameData&&(this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,A){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new re("Frame data and offsets are not the same length. This is a bug. Please report it.");this.offsets.some(((e,A)=>t[A].x!==e.x||t[A].y!==e.y||t[A].zoom!==e.zoom))||A?(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=Xn(t[A],e,this.imageData,this.forceImageCover)})),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.targetElements,e)):e&&e()}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,A,n,i){if(!A||0===A.length||A.some((t=>!t)))throw new re("Frame data not set. This is a bug");if(!this.workflowManager)throw new re("No workflow manager set, cannot update offsets.");const a=this.workflowManager.getCommandDispatcher();n.forEach(((A,n)=>{a(new et(A,e,t[n]))})),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){this.minZoomScale.length===e.length&&this.maxZoomScale.length===e.length||(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach(((e,A)=>{const n=Math.max(e.width/t.width,e.height/t.height);this.forceImageCover?(this.minZoomScale[A]=n,this.maxZoomScale[A]=2.5*n):(this.minZoomScale[A]=n/10,this.maxZoomScale[A]=2.5*n)}))}recalculateOffsets(t){this.frameData&&(this.offsets&&this.offsets.length===this.frameData.length||(this.offsets=new Array(this.frameData.length)),this.frameData.forEach(((e,A)=>{this.offsets[A]=tt(t,e)})),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.targetElements))}}function $n(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class _n{constructor(t,e,A){$n(this,"configuration",void 0),$n(this,"layouts",void 0),$n(this,"product",void 0),$n(this,"processRegion",(async t=>{const e=this.layouts.find((e=>e.panelId===t.panelId));if(!e)throw new Ae(t);let A="";if(this.configuration.type===m.ProductOverlay){let t="";if(this.product?.overlayImageUrl&&(t=this.product.overlayImageUrl),A=t,!t)throw new ae(this.configuration,"Couldn't find an asset for product overlay step")}const n=this.evaluateAssetType();if(n===h.Image){const A=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:this.product?.overlayImageUrl;if(!A)throw new Error("Undefined raster silent step source");const i={stepName:this.configuration.stepName,id:F(),src:A,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,immutable:t.immutable,productOverlay:this.configuration.type===m.ProductOverlay||void 0,rotation:t.rotation,excludeFromExport:this.configuration.data.excludeFromPrint,preserveAspectRatio:"none"};return{regionElement:{id:i.id,region:t},command:new o(i,e)}}{const i=this.configuration.type===m.SilentIllustration?this.configuration.data.asset?.fileLink:A,a=async()=>new Promise(((t,e)=>{i?nt(i).then((e=>{t(e)})).catch((t=>console.error(t))):e("Undefined vector silent step source")})),r=await S(await a()),s={stepName:this.configuration.stepName,id:F(),cachedObjectURL:await dt(r.svg),src:i,svg:r.svg,colors:r.colors,type:n,y:t.top,x:t.left,width:t.width,height:t.height,layer:t.layer,layerIndex:t.layerIndex,rotation:t.rotation,immutable:t.immutable,productOverlay:this.configuration.type===m.ProductOverlay||void 0,excludeFromExport:this.configuration.data.excludeFromPrint};return{regionElement:{id:s.id,region:t},command:new o(s,e)}}})),this.configuration=t,this.layouts=e,this.product=A||void 0}async trigger(){if(!this.configuration.data.regions)throw new ae(this.configuration,"Missing regions.");if(this.configuration.type===m.SilentIllustration){const t=this.configuration.data.regions.map(this.processRegion);return Promise.all(t)}return this.configuration.type===m.ProductOverlay?Promise.all(this.configuration.data.regions.map((t=>{if(!this.layouts.find((e=>t.panelId===e.panelId)))throw new Ae(t);return this.processRegion(t)}))):Promise.reject("Unknown silent step. This is a bug")}evaluateAssetType(){const t=this.configuration.type===m.ProductOverlay&&this.product?.overlayImageUrl?this.product.overlayImageUrl.toLowerCase():this.configuration.data.asset?.fileLink?.toLowerCase().split("?")[0];return t?.startsWith("data:image/png")||t?.endsWith(".jpeg")||t?.endsWith(".jpg")||t?.endsWith(".png")?h.Image:(t?.endsWith(".svg")||t?.startsWith("image/svg+xml"),h.Illustration)}}const ti=async t=>{const e=`${Ee.getServicesApiUrl()}/shortener`;try{const A=await fetch(e,{method:"POST",body:JSON.stringify({longUrl:t}),headers:{"Content-Type":"application/json"}});return(await A.json()).shortUrl}catch(t){throw console.error(t),new ge("Failed to shorten URL, see console.")}};function ei(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Ai{async poll(){try{if(await this.predicate())return this.onSuccess(),void(this.pollingId>-1&&window.clearInterval(this.pollingId))}catch(t){}this.attempts+=1,this.attempts<this.maxAttempts?this.pollingId=window.setTimeout(this.poll.bind(this),this.interval):this.onFailure()}constructor(t,e,A,n=3e3,i=10){ei(this,"pollingId",void 0),ei(this,"attempts",void 0),ei(this,"interval",void 0),ei(this,"maxAttempts",void 0),ei(this,"predicate",void 0),ei(this,"onSuccess",void 0),ei(this,"onFailure",void 0),this.onSuccess=e,this.onFailure=A,this.predicate=t,this.attempts=0,this.pollingId=-1,this.interval=n,this.maxAttempts=i,this.poll()}}const ni=new class{async init(t,e,A){return A&&await this.reload(t,e,A),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],i,(async()=>{const A=n?.storage?.videoShortUrl,i=n?.storage?.videoUrl;e.updateStorage(t.stepName,{videoShortUrl:A,videoUrl:i})}))}async regenerateQRCode(t,e,A,n,i,a,o,r,c){if(e||""===A||""!==n)c(!1);else{const e=async()=>{const t=(await Ne([A]))[0],e=t?.versions?.find((t=>"mpeg4"===t.name))?.link;return{asset:t,link:e}},g=await new Promise(((t,A)=>{new Ai((async()=>!!(await e()).link),(async()=>{const A=await e();if(!A.link||!A.link)throw new ie(A.asset);t({rel:"mpeg4",href:A.link})}),(()=>{A("Poller timed out with 40 attempts @ 3 second interval")}),3e3,40)}));t.forEach((t=>r(new s(t.id))));const l="http"===a.data.baseUrl.slice(0,4)?"":"https://",B=new URL(l+a.data.baseUrl);B.searchParams.append("video",btoa(JSON.stringify([g]))),B.pathname=B.pathname+("/"===B.pathname.slice(-1)?"":"/");const w=B.toString();if(w.length>=2e3)throw new ge("Cannot create QR code, URL too long.");const d=await ti(w);if(o(d),!a.data||!a.data.regions)throw new ae(a,"Missing regions.");const h=await this.regionElements(a),E=await this.command(d,h,i,a.stepName);E&&(E.command&&i.getCommandDispatcher()(E.command),E.followup&&await E.followup()),await i.setSelectionsAndElements(a.stepName,[],h,(async()=>{i.updateStorage(a.stepName,{videoShortUrl:d,videoUrl:n}),c(!1)}))}}async regionElements(t){return t.data.regions.map((t=>({id:F(),region:t})))}async command(t,e,A,n){const i=A.getLayouts(),a=`data:image/svg+xml;base64,${btoa(await Vt(t,{type:"svg"}))}`,r=e.map((t=>{const e=t.region,A=i.find((t=>t.panelId===e?.panelId));if(!A&&e)throw new Ae(e);if(A&&!e)throw new Error("Region not found");if(!A||!e)throw new Error("Neither a region or layout found!");return new o({stepRegion:e,stepName:n,id:t.id,src:a,type:h.Image,y:e.top,x:e.left,width:e.width,height:e.height,rotation:0},A)}));return{command:new w(r),followup:async()=>{}}}};function ii(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}const ai=new class{constructor(){ii(this,"frameSourceSvg",(async(t,e)=>{if(!t)return Et(e);const A=t.asset;if(!A)throw new ne(t);const n=A.fileLink;if(n)return nt(n);throw new ie(A)}))}async init(t,e,A){if(A)return await this.reload(t,e,A),null;if(e.setMandatoryFulfilled(t.stepName,!1),e.markStepsAsInitialised([t.stepName]),t.option&&t.option.variants&&t.option.variants.length>0){const A=t.option,n=ke.getDefaultVariant(A);return n?this.selectVariantCommand(t,n,[],e,void 0,t.data.placeholderImageUrl):null}return this.selectVariantCommand(t,void 0,[],e,void 0,t.data.placeholderImageUrl)}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));if(!t.option||0===(t.option.variants||[]).length){const A=t.data.regions.map((t=>Et(t)));e.updateStorage(t.stepName,{currentFrameSources:A})}if(n){const A=async()=>{const A=n.storage?.framePatternSrc,i=n.storage?.frameOffsetsList;if(e.updateMetadata(t.stepName,{frameOffsetsList:i,framePatternSrc:A}),A){const n=e.getStepSpecificServices(t.stepName)?.frameService;if(!n)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(A,n),e.updateMetadata(t.stepName,{image:A}),e.updateStorage(t.stepName,{framePatternSrc:A})}if(i?.some((t=>t.zoom))){const A=e.getStepSpecificServices(t.stepName)?.frameService;if(!A)throw new Error("Frame service unavailable, cannot load pattern!");A.updateOffsets(i)}e.setMandatoryFulfilled(t.stepName,!0)};if(n.selectedVariants&&n.selectedVariants.length>0){const a=n.selectedVariants[0].id;if(t.option&&a){const n=t.option.variants?.find((t=>t.id===a));n&&await e.setSelectionsAndElements(t.stepName,[n],i,(async()=>{const i=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(n,t))));e.updateStorage(t.stepName,{currentFrameSources:i}),await A()}))}}else await e.setSelectionsAndElements(t.stepName,[],i,A)}}selectImage(t,e,A){A.setEditedStatus(t.stepName,!0);(e.fileLink||"").endsWith("pdf")?A.addPoller(new Ai((async()=>{const t=(await He.getLocalOrFromServer(e.key||"")).versions?.find((t=>"svg"===t.name));if(!t)return!1;return 200===(await fetch(t.link)).status}),(()=>{He.getLocalOrFromServer(e.key||"").then((e=>{this.loadPatternFromAsset(e,t,A)}))}),(()=>{throw new ge("Failed to resolve transcoded PDF")}))):this.loadPatternFromAsset(e,t,A)}async selectVariant(t,e,A,n,i){const a=await this.selectVariantCommand(t,e,A,n,i);a&&(a.command&&n.getCommandDispatcher()(a.command),a.followup&&await a.followup())}getCreateElementCommand(t,e,A,n){return new o({id:t,type:h.Frame,x:e.left,y:e.top,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,scaleX:e.width/n.frameData.width,scaleY:e.height/n.frameData.height,path:n.frameData.path,dataWidth:n.frameData.width,dataHeight:n.frameData.height,stepRegion:e,stepName:n.stepName,disablePlaceholder:n.disablePlaceholder,focalBlur:n.focalBlur,focalBlurStrength:n.focalBlurStrength,focalBlurRadius:n.focalBlurRadius,pattern:n.pattern,immutable:e.immutable},A)}async loadPatternFromString(t,e){if(t.endsWith("svg")){const A=await Ct(t),n=A.width,i=A.height,a={src:t,width:n,height:i,aspect:n/i};b.set(t,a),e.setPatternData(a)}else{const A=await st(t),n=await v(A),i={src:t,width:n.width,height:n.height,aspect:n.width/n.height};b.set(t,i),e.setPatternData(i)}}async selectVariantCommand(t,e,A,n,i,a){const o=n.getStepSpecificServices(t.stepName)?.frameService;if(!o)throw new Error("Frame service unavailable, cannot load pattern!");const r=await Promise.all(t.data.regions.map((t=>this.frameSourceSvg(e,t))));i&&i(!0);const c=await Promise.all(t.data.regions.map((async(e,i)=>{const a=await N(r[i]),c=o.getImageData(),g=A.map((t=>new s(t.id))),l=c?tt(c,a):void 0,B=c?{id:F(),src:c.src,x:l?.x||0,y:l?.y||0,width:c.width,height:c.height,scaleX:l?.zoom||1,scaleY:l?.zoom||1,rotation:0}:void 0,w=F(),d=n.getLayouts().find((t=>t.panelId===e.panelId));if(!d)throw new Ae(e);return{command:this.getCreateElementCommand(w,e,d,{frameData:a,pattern:B,disablePlaceholder:t.data.disablePlaceholder,focalBlur:t.data.focalBlur,focalBlurStrength:t.data.focalBlurStrength,focalBlurRadius:t.data.focalBlurRadius,stepName:t.stepName}),regionEl:{id:w,region:e},removeExistingCommands:g}}))),g=c.map((t=>t.command)),l=c.map((t=>t.removeExistingCommands)).flat();return{command:new w([...g,...l]),followup:async()=>{i&&i(!1),await n.setSelectionsAndElements(t.stepName,e?[e]:[],[...c.map((t=>t.regionEl))],(async()=>{if(n.updateStorage(t.stepName,{currentFrameSources:r}),a){const e=n.getStepSpecificServices(t.stepName)?.frameService;if(!e)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(a,e)}}))}}}patternSource(t){const e=t.versions?.find((t=>"svg"===t.name));if(e)return e.link;const A=t.fileLink;if(A)return A;throw new ie(t)}async loadPatternFromAsset(t,e,A){const n=this.patternSource(t),i=A.markUpdatePending(),a=A.getStepSpecificServices(e.stepName)?.frameService;if(!a)throw new Error("Frame service unavailable, cannot load pattern!");await this.loadPatternFromString(n,a),A.updateMetadata(e.stepName,{image:n}),A.updateStorage(e.stepName,{framePatternSrc:n}),A.markUpdateCompleted(i)}};const oi=new class{async getIllustrationBody(t){return new Promise((e=>{nt(t).then((t=>{e(t)})).catch((t=>console.error(t)))}))}getCreateElementCommand(t,e,A,n){return new o({stepRegion:e,stepName:n.stepName,colors:n.svg.colors,id:t,src:n.src,svg:n.svg.svg,cachedObjectURL:n.objectURL,type:h.Illustration,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable},A)}getColors(t,e){const A=e.getRegionElements(t.stepName)||[];if(0===A.length)return[];try{return y(A[0].id,e.getAllLayoutData()).colors}catch(t){return[]}}async init(t,e,A){const n=t.option;if(!n)return null;if(A)return this.reload(t,e,A);{const A=ke.getDefaultVariant(n);if(A)return await this.selectVariantCommand(t,A,[],(()=>{}),e)}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(!a||!A)throw new Error("Required illustration variant no longer available");{const o=a.variants?.find((t=>t.id===A));if(o){const A=i.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[o],A,(async()=>{e.updateMetadata(t.stepName,{colors:n.storage?.colors}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}return null}async availableColors(t,e){const A=t.data.colorOption;return A&&A?A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t}))):[]}async changeColorsCommand(t,e,A,n,i){const a={};for(const[t,e]of i.entries())a[t]={browserValue:e,spotColor:a[t]?.spotColor};const o=ut(t,e,A,a),r=await dt(o),s=[];for(const t of n){for(const[e,A]of i.entries())s.push(new Qt(t,e,A));s.push(new pt(t,o,r))}return new w(s)}async changeColors(t,e,A,n,i){if(0===e.length)return;const a=y(e[0].id,n().map((t=>t.layoutState))),o={...a.colors},r={};Object.entries(o).forEach((([t,e])=>{const A={browserValue:e.browserValue},n=e.spotColor;n&&(A.spotColor={profileName:n.profileName,namedColor:n.namedColor}),r[t]=A}));for(const[t,e]of i.entries())o[t]={browserValue:e,spotColor:o[t]?.spotColor},r[t]={browserValue:e};let s=Array.from(Object.values(o)).map((t=>t.browserValue));const c=t.data.colorOption;c&&c.variants?.forEach((t=>{s=s.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),A.updateMetadata(t.stepName,{colors:s});const g=new Map;if(Object.entries(o).forEach((([t,e])=>{g.set(t,e.browserValue)})),!a.svg)throw new Error("Colors changed before SVG loaded. This should never happen!");const l=await this.changeColorsCommand(a.svg,a.width,a.height,e.map((t=>t.id)),g);A.updateStorage(t.stepName,{colors:r}),A.getCommandDispatcher()(l)}async selectVariant(t,e,A,n,i){const a=await this.selectVariantCommand(t,e,A,n,i);a&&(a.command&&i.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async selectVariantCommand(t,e,A,n,i){if(!t.data||!t.data.regions)throw new ae(t,"Missing regions.");n(!0);const a=A.map((t=>new s(t.id)));i.setMandatoryFulfilled(t.stepName,!1);const o=e.asset;if(!o)throw new ne(e);const r=o.fileLink;if(!r)throw new ie(o);const c=await S(await this.getIllustrationBody(r)),g=await dt(c.svg),l=t.data.regions.map((e=>{const A=i.getLayouts().find((t=>t.panelId===e.panelId));if(!A)throw new Ae(e);const n=F();return{regionElement:{id:n,region:e},command:this.getCreateElementCommand(n,e,A,{stepName:t.stepName,src:r,objectURL:g,svg:c})}})),B=[...l.map((t=>t.command)),...a];let d=Array.from(Object.values(c.colors)).map((t=>t.browserValue));const h=t.data.colorOption;return h&&h.variants?.forEach((t=>{d=d.map((e=>e.toLowerCase()===t.color?.toLowerCase()?t.name:e))})),i.updateMetadata(t.stepName,{colors:d}),{command:new w(B),followup:async()=>{await i.setSelectionsAndElements(t.stepName,[e],l.map((t=>t.regionElement)),(async()=>{i.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const ri=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=ke.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(!a)throw new ee(t);if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(A){const n=a.variants?.find((t=>t.id===A));if(n){const A=n.material,o=i.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],o,(async()=>{const n=e.getModelContainer();if(n){const i=t.data.targetMaterials.map((t=>n.applyMaterialVariant(t,a.id||"",A||{})));Promise.all(i).then((()=>e.setMandatoryFulfilled(t.stepName,!0)))}}))}}}}async selectVariant(t,e,A,n){const i=await this.selectVariantLambda(t,e,A,n);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,A,n){const i=A.getModelContainer();n(!0);const a=e.material;if(!a)throw n(!1),new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{i&&t.data.targetMaterials.forEach((e=>{t.option&&i.applyMaterialVariant(e,t.option.id||"",a)})),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const si=new class{async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(A)await this.reload(t,e,A);else{const A=ke.getDefaultVariant(n);if(A)return await this.selectVariantLambda(t,A,e,(()=>{}))}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const n=a.variants?.find((t=>t.id===A));if(n){const A=i.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{const A=e.getModelContainer();if(A&&t.option){const i=n.asset?.fileLink;if(!i)throw new ne(n);await A.applyModelVariant(t.option.id||"",{model:i,contextService:e.getLayoutPreviewService()},t.data.replaceProductModel||!1),e.setMandatoryFulfilled(t.stepName,!0)}}))}}}}async selectVariant(t,e,A,n){const i=await this.selectVariantLambda(t,e,A,n);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantLambda(t,e,A,n){n(!0);const i=e.asset?.fileLink;if(!i)throw new ne(e);return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],[],(async()=>{try{const e=A.getModelContainer();e&&t.option&&e.applyModelVariant(t.option.id||"",{model:i,contextService:A.getLayoutPreviewService()},t.data.replaceProductModel||!1),A.setMandatoryFulfilled(t.stepName,!0)}finally{n(!1)}}))}}}};const ci=new class{async init(t,e,A){return A?(await this.reload(t,e,A),null):(e.updateMetadata(t.stepName,{text:""}),this.changeTextCommand(t,"",e,"",(()=>{})))}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)).map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[],i,(async()=>{e.updateStorage(t.stepName,{text:n?.storage?.text}),e.setMandatoryFulfilled(t.stepName,""!==n?.storage?.text)}))}async changeText(t,e,A,n,i){const a=await this.changeTextCommand(t,e,A,n,i);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}async changeTextCommand(t,e,A,n,i){const a=A.getRegionElements(t.stepName),r=A.getStepSpecificServices(t.stepName)?.module;if(!r)return console.error("Missing module."),null;const c=A.getProfanities();if(!this.validateInput(t,e,c,i))return A.setMandatoryFulfilled(t.stepName,!1),console.error(n),null;if(A.setMandatoryFulfilled(t.stepName,""!==e),!t.data||!t.data.regions||t.data.regions.length<=0)return console.error("Missing configuration."),null;A.updateStorage(t.stepName,{text:e});const g=(e,n,i)=>{const a=i||F(),r=A.getLayouts().find((t=>t.panelId===n.panelId));if(!r)return console.error(`Can not find layout for region: ${n.panelId}`),null;const c=[];return i&&c.push(new s(a)),c.push(new o({stepRegion:n,stepName:t.stepName,colors:{},id:a,svg:e,type:h.Illustration,y:n.top,x:n.left,rotation:n.rotation,width:n.width,height:n.height,layer:n.layer,layerIndex:n.layerIndex,immutable:n.immutable},r)),{id:a,region:n,command:new w(c)}};if(a.length>0){const t=a.map((t=>{if(!t.region)return null;const A=r.svgPrint(e,t.region);return g(A,t.region,t.id)})).filter((t=>!!t)).filter((t=>!!t)).map((t=>t&&t.command));return{command:new w(t),followup:async()=>{}}}{const n=t.data.regions.map((t=>g(r.svgPrint(e,t),t))),i=n.filter((t=>!!t)).map((t=>t&&t.command));return{command:new w(i),followup:async()=>{const e=n.filter((t=>t)).map((t=>t&&{id:t.id,region:t.region}));await A.setSelectionsAndElements(t.stepName,[],e)}}}}validateInput(t,e,A,n){if(t.data&&t.data.maxLength){const A=t.data.maxLength;if(e.length>A)return n("Too many characters."),!1}if(!/^$|^[a-zA-Z0-9 ]+$/.test(e))return n("Unsupported characters."),!1;const i=qt(e.toLowerCase());for(const t of i)for(const e in A){if(t===A[e].toLowerCase().replace(/\s/g,""))return n("Blocked profanity."),!1}return n(""),!0}};const gi=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else if(n.defaultVariant)return e.markStepsAsInitialised([t.stepName]),this.selectVariantCommand(t,n.defaultVariant,e,(()=>{}));return e.markStepsAsInitialised([t.stepName]),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const n=a.variants?.find((t=>t.id===A));if(n){const A=i.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,A,n){const i=await this.selectVariantCommand(t,e,A,n);i&&(i.command&&A.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,A,n){const i=e.asset;if(!i)throw new ne(e);const a=i?.fileLink;if(!a)return console.error("No URL for picture!"),null;n(!0),A.setMandatoryFulfilled(t.stepName,!1);const r=A.getRegionElements(t.stepName).map((t=>new s(t.id))),c=t.data.regions.map((e=>{const n=A.getLayouts().find((t=>t.panelId===e.panelId));if(!n)throw new Ae(e);const i=F();return{regionElement:{id:i,region:e},command:new o({stepName:t.stepName,stepRegion:e,id:i,src:a,type:h.Image,y:e.top,x:e.left,rotation:e.rotation,width:e.width,height:e.height,layer:e.layer,layerIndex:e.layerIndex,immutable:e.immutable,preserveAspectRatio:"none"},n)}}));return{command:new w([...r,...c.map((t=>t.command))]),followup:async()=>{await A.setSelectionsAndElements(t.stepName,[e],c.map((t=>t.regionElement)),(async()=>{A.setMandatoryFulfilled(t.stepName,!0),n(!1)}))}}}};const li=new class{async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=n.variants;if(ke.getDefaultVariant(n)){const i=A?.find((t=>t.id===n.defaultVariant?.id));return this.selectVariantLambda(t,i?.id||"",e)}}return null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(i&&A){const n=i.variants?.find((t=>t.id===A));n&&await e.setSelectionsAndElements(t.stepName,[n],[])}}}async selectVariant(t,e,A){await A.getInitializationPromise();const n=await this.selectVariantLambda(t,e,A);n&&(n.command&&A.getCommandDispatcher()(n.command),n.followup&&await n.followup())}async selectVariantLambda(t,e,A){const n=t.option;if(!n)return null;const i=n.variants;if(!i)return null;const a=i.length>1?i.find((t=>t.id===e)):i[0];if(!a)throw new Error("Failed to find selected variant in step variants, this should never happen!");return{command:void 0,followup:async()=>{await A.setSelectionsAndElements(t.stepName,[a],[],(async()=>{A.setMandatoryFulfilled(t.stepName,!0)}))}}}};const Bi=new class{async availableColours(t){const e=t.option;return e&&e.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[]}async init(t,e,A){const n=t.option;if(!n)throw new ee(t);if(!A){const A=ke.getDefaultVariant(n);if(!A)return null;const i={fill:A.color,stroke:A.color,variant:A};return this.selectVariantCommand(t,i,[],e)}return await this.reload(t,e,A),null}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const n=a.variants?.find((t=>t.id===A));if(n){const A=i.map((t=>({id:t.id,region:t.stepRegion})));await e.setSelectionsAndElements(t.stepName,[n],A,(async()=>{e.updateStorage(t.stepName,{colour:n.color||""}),e.setMandatoryFulfilled(t.stepName,!0)}))}}}}async selectVariant(t,e,A,n){const i=await this.selectVariantCommand(t,e,A,n);i&&(i.command&&n.getCommandDispatcher()(i.command),i.followup&&await i.followup())}async selectVariantCommand(t,e,A,n){const i=n.getLayouts();if(A.length>0){const a=t=>{const A=t.region;if(!i.find((t=>t.panelId===A?.panelId)))throw new Ae(A);const n=e.variant?.color;return n?new Qt(t.id,"spiff-fill-shape",n):(console.error("Failed to change color."),null)},o=A.map(a).filter((t=>!!t));return{command:new w(o),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],A),n.updateStorage(t.stepName,{colour:e.fill||""})}}}{const A=A=>{const n=i.find((t=>t.panelId===A.panelId));if(!n)throw new Ae(A);const a=`\n <svg\n xmlns="http://www.w3.org/2000/svg"\n xmlnsXlink="http://www.w3.org/1999/xlink"\n xmlSpace="preserve"\n preserveAspectRatio="none"\n version="1.1"\n width="1"\n height="1"\n viewBox="0 0 1 1"\n >\n <rect\n x="0"\n y="0"\n width="1"\n height="1"\n class="spiff-fill-shape"\n fill="${e.variant?.color}"\n />\n </svg>\n `,r={};r["spiff-fill-shape"]={browserValue:e.variant.color};const s=F();return{id:s,region:A,command:new o({stepRegion:A,stepName:t.stepName,colors:r,id:s,svg:a,type:h.Illustration,y:A.top,x:A.left,rotation:A.rotation,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,immutable:A.immutable,excludeFromExport:t.data.excludeFromPrint},n)}},a=t.data.regions.map(A),r=a.filter((t=>!!t)).map((t=>t?.command)),s=a.filter((t=>!!t)).map((t=>({id:t.id,region:t.region})));return{command:new w(r),followup:async()=>{await n.setSelectionsAndElements(t.stepName,e.variant?[e.variant]:[],s,(async()=>{n.updateStorage(t.stepName,{colour:e.fill||""})}))}}}}};function wi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class di extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=di.name}}const hi=["‘","’","“","”","\n"];class Ei extends Error{constructor(t){super(t),Object.setPrototypeOf(this,new.target.prototype),this.name=Ei.name}}const Ci=new class{constructor(){wi(this,"cachedColors",new Map),wi(this,"filterUnsupportedCharacters",((t,e)=>{let A=t.replace(/(\r\n|\r|(\u00a9|\u00ae|[\u2000-\u2017]|[\u201E-\u3300]]|\ud83c[\ud000-\udfff]|\ud83d[\ud000-\udfff]|\ud83e[\ud000-\udfff]))/gm,"");const n=[],i=e?mt(e):void 0;if(i){const t=A.split("").filter((t=>!hi.includes(t))).join(""),e=t.split("").map((t=>i.getFont().charToGlyph(t)));for(let A=0;A<e.length;A++){".notdef"===e[A].name&&n.push(String.fromCharCode(t.charCodeAt(A)))}}for(let t=0;t<n.length;t++)A=A.replaceAll(n[t],"");return A})),wi(this,"textAlign",(t=>t.vertical?"center":t.textAlign||"center")),wi(this,"getErrorsForText",((t,e,A)=>{const n=[];e.data&&e.data.maxLength&&t.length>e.data.maxLength&&n.push({localizationKey:"workflow.steps.text.characterLimit"});const i=A.getProfanities(),a=qt(t.toLowerCase());for(const t of a)for(const e in i){if(t===i[e].toLowerCase().replace(/\s/g,"")){n.push({localizationKey:"workflow.steps.text.blockedProfanity"});break}}return!e.data.allowNewlines&&(t.includes("\n")||t.includes("\r"))&&n.push({localizationKey:"workflow.steps.text.multipleLines"}),n}))}async init(t,e,A){const n=t.option;if(!n)return null;if(A)await this.reload(t,e,A);else{const A=this.getDefaultImageFillVariant(t.data),i=A?.asset?.fileLink,a=i?await Z(i):void 0,o=a?{src:a.src,height:a.height,width:a.width,scale:t.data.imageFillScale||1}:void 0;e.updateStorage(t.stepName,{inputText:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.color||await this.getDefaultColor(t.data),fillImage:o}),e.updateMetadata(t.stepName,{text:t.data.defaultText||"",color:(await this.getDefaultColorVariant(t.data))?.name||await this.getDefaultColor(t.data),fillImage:A?.name});const r=ke.getDefaultVariant(n);if(r)return this.selectVariantCommand(t,r,{},[],e,(()=>{}),(()=>{}),o)}return null}findLayoutElements(t,e){return t.getRegionElements(e.stepName).map((e=>y(e.id,t.getAllLayoutData())))}availableFillColors(t){const e=this.cachedColors.get(t.stepName);if(e)return e;const A=t.data.colorOption;if(A){const e=A.variants?.map((t=>({fill:t.color,stroke:t.color,variant:t})))||[];return this.cachedColors.set(t.stepName,e),e}return[]}async changeFillColor(t,e,A,n){if(!t.data||!t.data.regions)return;const i=n.getCommandDispatcher();e.variant?n.updateMetadata(t.stepName,{color:e.variant.name}):n.updateMetadata(t.stepName,{color:e.fill});const a=t.data.colorOption,o=a?this.createTextFillSpotColor(a,e.variant):void 0;a?n.updateStorage(t.stepName,{color:e.fill,colorProfileAssetKey:a.colorProfile?.key}):n.updateStorage(t.stepName,{color:e.fill});for(const t of A){if(!e.fill)throw new Error("Fill not set on new color selection!");i(new g(t.id,e.fill,o))}}async availableFillImages(t){const e=t.data.imageFillOption;if(e){const A=e.variants?.map((t=>t.asset?.fileLink))?.filter((t=>!!t))||[];return Promise.all(A.map((async e=>{const A=await Z(e);return{src:e,width:A.width,height:A.height,scale:t.data.imageFillScale||1}})))}return Promise.resolve([])}async changeFillImage(t,e,A,n){if(!t.data||!t.data.regions)return;const i=n.getCommandDispatcher(),a=t.option?.variants?.find((t=>t.asset?.fileLink===e.src));n.updateMetadata(t.stepName,{fillImage:a?.name}),n.updateStorage(t.stepName,{fillImage:e});for(const t of A){i(new Dt(t.id,e))}}getProcessedInput(t,e,A){const n=A?t:this.injectReplaceableText(t,e);return lt(n,{vertical:e.vertical,uppercase:e.uppercase})}updateInputText(t,e,A,n){const i=n.getStepStorage(A.stepName),a=this.getProcessedInput(t,A.data,!!i.customiseAllText),o={command:void 0,helperText:"",errors:this.getErrorsForText(t,A,n)};if(o.errors.length>0)return o.helperText=o.errors[0].localizationKey,o;const r=(A.data.maxLength-a.length).toString();o.helperText=`${r} characters remaining`;const s=n.getTransaction().bulk&&A.data.varyText||!1,c=[],g=new Map,l=new Map;for(const t of e){if(!t.fontData)throw new re("Failed to resolve font data for text.");const[e,n]=U(t.fontSize,t.fontData,{left:t.x,top:t.y,width:t.width,height:t.height,rotation:t.rotation,panelId:""},[a],{size:A.data.size,minSize:A.data.minSize,maxSize:A.data.maxSize});g.set(t.id,e),l.set(t.id,n);const i=A.data.curved?a:(n||[]).join("\n");c.push(this.generateTextChangeCommandsForRegion(e,A.data,t.id,i,s))}if(!A.data.curved&&e.length>0){if(!Array.from(l.values()).every((t=>t)))return o.errors.push({localizationKey:"workflow.steps.text.doesNotFit"}),o}return n.updateStorage(A.stepName,{text:t}),n.updateMetadata(A.stepName,{text:a}),i.defaultCleared&&n.setMandatoryFulfilled(A.stepName,!0),o.command=new w(c),o.command.varying=s,o}async selectVariant(t,e,A,n,i){const a=await this.selectVariantCommand(t,e,A.getStepStorage(t.stepName)||{},A.getRegionElements(t.stepName),A,n,i);a&&(a.command&&A.getCommandDispatcher()(a.command),a.followup&&await a.followup())}createTextFillSpotColor(t,e){const A=t.colorProfile;if(A){const t=(A.name||"").replace(/\s/g,"-"),n=t.lastIndexOf("/"),i=t.slice(n+1).slice(0,-4);if(!e.namedColor)throw new Error("variant named color not set!");return{profileName:i,namedColor:e.namedColor}}}async reload(t,e,A){const n=e.getSerializedStep(t.stepName,A.serializableWorkflow.steps),i=Object.values(A.layouts).map((t=>t.elements)).flat().filter((e=>e.stepName===t.stepName)),a=t.option;if(n?.selectedVariants){const A=n.selectedVariants[0].id;if(a&&A){const o=a.variants?.find((t=>t.id===A));if(o){const A=await this.fontDataFromVariant(o),a=i.map((t=>({id:t.id,region:t.stepRegion}))),r=n.storage?.color,s=n.storage?.text;await e.setSelectionsAndElements(t.stepName,[o],a,(async()=>{e.updateMetadata(t.stepName,{color:r,text:s}),e.updateStorage(t.stepName,{text:s,inputText:s});const n=i.map((t=>new B(t.id,A))),a=new w(n);e.getCommandDispatcher()(a),e.setMandatoryFulfilled(t.stepName,!0)}));const{command:c}=Ci.updateInputText(s||"",i,t,e);c&&e.getCommandDispatcher()(c)}}}}async getDefaultColorVariant(t){const e=t.colorOption;if(e)return ke.getDefaultVariant(e)}async getDefaultColor(t){const e=t.colorOption;if(!e)return;return ke.getDefaultVariant(e)?.color}getDefaultImageFillVariant(t){const e=t.imageFillOption;if(e)return ke.getDefaultVariant(e)}async fontDataFromVariant(t){const e=t.asset;if(!e)throw new ne(t);const A=e.fileLink;if(!A)throw new ie(e);return{assetUrl:A,name:(await H(A)).names.fullName.en}}async selectVariantCommand(t,e,A,n,i,a,o,r){const s=i.markUpdatePending(),c=await this.fontDataFromVariant(e);if(n.length>0){const g=n.map((t=>new B(t.id,c)));if(r){const t=n.map((t=>new Dt(t.id,r)));g.push(...t)}const l=await this.changeInputTextWithRegion(t,t.data.size||30,c,A.text||"",A,i,!!A.customiseAllText,a,o);l&&g.push(l);return{command:new w(g),followup:async()=>{i.markUpdateCompleted(s),await i.setSelectionsAndElements(t.stepName,[e],n)}}}{const n=await this.createTextboxRegions(t.stepName,e,t.data,c,A,i),g=await this.changeInputTextWithRegion(t,t.data.size||30,c,n[0]?.newElement.input||A.text||t.data.defaultText||"",A,i,!!A.customiseAllText,a,o),l=n.flatMap((t=>t.commands));if(r){const t=n.map((t=>new Dt(t.regionElement.id,r)));l.push(...t)}g&&l.push(g);return{command:new w(l),followup:async()=>{i.markUpdateCompleted(s)}}}}injectReplaceableText(t,e){return e.replaceableText?e.replaceableText.replace("{{}}",t):t}async createTextboxRegions(t,e,A,n,i,a){if(!A||!A.regions)throw new Error("Step data not supplied");const r=a.getTransaction().bulk&&A.varyText||!1,s=r?"":i.text||A.defaultText||"",c=this.getProcessedInput(s,A,!1),g=await Promise.all(A.regions.map((async e=>{const g=a.getLayouts().find((t=>t.panelId===e.panelId)),l=F();try{if(!g)throw new Ei("Failed to find layout for region: "+e.panelId);const B=A.colorOption;let w;if(B&&B.variants){const e=B.variants.find((t=>t.id===B.defaultVariant?.id))||B.variants[0];w=this.createTextFillSpotColor(B,e),a.updateStorage(t,{colorProfileAssetKey:B.colorProfile?.key})}const d=await this.getDefaultColor(A),E=d||"#000000",C={stepRegion:e,stepName:t,align:this.textAlign(A),fill:i.color?i.color:E,fontSize:A.size||30,fontData:n,id:l,layer:e.layer,layerIndex:e.layerIndex,rotation:e.rotation,text:c,input:s,type:h.Textbox,vertical:A.vertical,x:e.left,y:e.top,height:e.height,width:e.width,immutable:e.immutable,verticalAlign:A.verticalAlign||"middle",curved:A.curved,paths:A.paths,fillSpotColorDefinition:w},u=[],Q=new Map,p=new Map;if(!C.fontData)throw new re("Failed to resolve font data for text.");const[m,D]=U(C.fontSize,C.fontData,{left:C.x,top:C.y,width:C.width,height:C.height,rotation:C.rotation,panelId:""},[c],{size:A.size,minSize:A.minSize,maxSize:A.maxSize});Q.set(C.id,m),p.set(C.id,D);const I=A.curved||A.vertical?c:(D||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(m,A,C.id,I,r));const f=new o(C,g);return f.varying=r,{regionElement:{id:l,region:e},commands:[f,...u],newElement:C,fontData:n}}catch(t){throw console.log(t),new di("Error adding font to region")}}))).catch((t=>{throw t instanceof di?(gA.setLatestToast("Failed to load font.",Qi.Error),t):t instanceof Ei?t:new Error(t)}));return await a.setSelectionsAndElements(t,[e],g.map((t=>t.regionElement)),(async()=>{a.updateMetadata(t,{text:s}),a.updateStorage(t,{text:s})})),g}generateTextChangeCommandsForRegion(t,e,A,n,i){const a=[],o=new D(A,n);if(o.varying=i,a.push(o),!e.size){const e=new l(A,t);e.varying=i,a.push(e)}const r=new w(a);return r.varying=i,r}async changeInputTextWithRegion(t,e,A,n,i,a,o,r,s,c){const g=(n||"").replace(/^(?![\u000A\u000D])[\u0000-\u001F\u007F-\u009F]/g,""),l=this.getProcessedInput(g,t.data,o),B=a.getRegionElements(t.stepName),d=new Map,h=new Map;for(const n of B)if(n.region){const[i,a]=U(e,A,n.region,[l],{size:t.data.size,minSize:t.data.minSize,maxSize:t.data.maxSize});d.set(n.id,i),h.set(n.id,a)}const E=(()=>{if(t.data&&t.data.maxLength&&l.length>t.data.maxLength)return c&&c(!0),{info:"0"};const e=a.getProfanities(),A=qt(l.toLowerCase());for(const t of A)for(const A in e){if(t===e[A].toLowerCase().replace(/\s/g,""))return r(!0),{error:"Blocked profanity."}}if(!t.data.vertical&&!t.data.allowNewlines&&(l.includes("\n")||l.includes("\r")))return r(!0),{error:"Cannot span multiple lines."};if(!t.data.curved){if(!Array.from(h.values()).every((t=>t)))return r(!0),{error:"Does not fit."}}return r(!1),{info:(t.data.maxLength-l.length).toString()}})();if(E.error)return void s(E.error);if(s(`${E.info} characters remaining`||""),c)return;a.updateStorage(t.stepName,{text:g}),a.updateMetadata(t.stepName,{text:this.injectReplaceableText(g,t.data)});const C=a.getTransaction().bulk&&t.data.varyText||!1;i.defaultCleared&&a.setMandatoryFulfilled(t.stepName,!0);const u=[];for(const e of B){const A=t.data.curved?l:(h.get(e.id)||[]).join("\n");u.push(this.generateTextChangeCommandsForRegion(d.get(e.id)||1,t.data,e.id,A,C))}const Q=new w(u);return Q.varying=C,Q}};function ui(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}let Qi;var pi;(pi=Qi||(Qi={})).Error="Error",pi.Warning="Warning",pi.Info="Info";class mi extends OA{constructor(t){super(),ui(this,"update",void 0),ui(this,"createdAt",new Date),this.update=t}async execute(){await this.update(),await new Promise((t=>{window.setTimeout((()=>{t()}),1e3)}))}}class Di{constructor(t,e,A,n,i,a,o,r,s,c,g=!1,l,B=!1){ui(this,"reloadedState",void 0),ui(this,"transaction",void 0),ui(this,"ownerCustomer",void 0),ui(this,"updateTransaction",void 0),ui(this,"confirmedDesign",void 0),ui(this,"editedSteps",void 0),ui(this,"informationResults",void 0),ui(this,"layouts",void 0),ui(this,"mandatorySteps",void 0),ui(this,"pendingUpdates",void 0),ui(this,"selectionCost",void 0),ui(this,"workflow",void 0),ui(this,"stepSpecificServices",void 0),ui(this,"previewService",void 0),ui(this,"profanityFilter",void 0),ui(this,"pollers",void 0),ui(this,"commandContext",void 0),ui(this,"stepElements",void 0),ui(this,"stepInitialised",void 0),ui(this,"stepMetadata",void 0),ui(this,"stepSelections",void 0),ui(this,"storage",void 0),ui(this,"confirmCallbacks",void 0),ui(this,"editedCallbacks",void 0),ui(this,"elementsCallbacks",void 0),ui(this,"informationResultCallbacks",void 0),ui(this,"initCallbacks",void 0),ui(this,"makingAdjustmentsCallback",void 0),ui(this,"mandatoryCallbacks",void 0),ui(this,"metadataCallbacks",void 0),ui(this,"selectionCallbacks",void 0),ui(this,"stepSpecificStorageCallbacks",void 0),ui(this,"storageCallbacks",void 0),ui(this,"currentVariationRecordCallbacks",void 0),ui(this,"variationRecordCallbacks",void 0),ui(this,"allScenes",void 0),ui(this,"product",void 0),ui(this,"invalidModelVariants",void 0),ui(this,"currentAdjustingStepId",void 0),ui(this,"renderableContextService",void 0),ui(this,"workflowStatePromiseQueue",new zA(1)),ui(this,"variationRecords",[]),ui(this,"currentVariationRecord",void 0),ui(this,"initializationPromise",void 0),ui(this,"initialized",!1),ui(this,"readOnly",!1),ui(this,"modelContainer",void 0),ui(this,"isReloadedTransaction",!1),ui(this,"render3DScene",(()=>{if(!this.previewService)return;const t=this.getCommandContext().getAllLayouts(),e=this.getLayoutPreviewService()?.getAll();if(e)for(const[,A]of e)A.render(this.getWorkflow(),t,this.getCurrentVariationRecord(),this.getProduct().overlayImageUrl)})),this.updateTransaction=i,this.commandContext=n,this.reloadedState=c,this.transaction=a,this.readOnly=g,this.confirmedDesign=!1,this.editedSteps={},this.informationResults=[],this.mandatorySteps={},this.pendingUpdates=[],this.selectionCost=0,this.workflow=t,this.stepSpecificServices={},this.profanityFilter=e,this.pollers=[],this.allScenes=[],this.layouts=A,this.product=o,this.previewService=r,this.modelContainer=l,this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.confirmCallbacks=[],this.editedCallbacks=[],this.elementsCallbacks=[],this.informationResultCallbacks=[],this.initCallbacks=[],this.mandatoryCallbacks=[],this.makingAdjustmentsCallback=[],this.metadataCallbacks=[],this.selectionCallbacks=[],this.stepSpecificStorageCallbacks={},this.storageCallbacks=[],this.currentVariationRecordCallbacks=[],this.variationRecordCallbacks=[],this.invalidModelVariants=[],this.currentAdjustingStepId="",this.renderableContextService=s,this.currentVariationRecord=null,this.isReloadedTransaction=B,this.initializationPromise=this.initializeDefaultWorkflowState(t,a),this.initializationPromise.then((()=>{this.initialized=!0})),this.initializationPromise.catch((t=>{throw console.error(t),this.initialized=!1,new Error("Workflow initialization failed due to an error. See console.")})),this.initializationPromise.finally((()=>this.getCommandContext().registerStateCallback((()=>{this.updateStateWithServer(),this.render3DScene()}))))}async initializeDefaultWorkflowState(t,e){this.reloadedState&&this.reloadedState.serializableWorkflow.steps.forEach((t=>{this.storage[t.stepName]=t.storage||{}})),this.allScenes=await On(t,{bulkScene:e.bulk||!1,bulkSceneTitle:"workflow.steps.bulk.title",finishScene:!0,finishSceneTitle:"workflow.steps.finish.confirmDesign"},e);const A=Kn(this.allScenes,this.stepSelections).map((t=>t.silentSteps)).flat(),{stepElements:n,commands:i}=await this.stepElementsForIntroducedSilentSteps(A,!!this.reloadedState);this.commandContext.apply(new w(i),!0),this.stepElements={...this.stepElements,...n},await this.ensureStepsAreLoaded(),!this.isReloadedTransaction&&this.updateStateWithServer(),this.render3DScene(),this.reloadedState&&(()=>{const t=this.workflow.finalizeStepConfig;if(!t)return;const e=t.lookAtAnimation,A=t.modelAnimation;e&&this.previewService?.executeCameraAnimation(e),A&&this.modelContainer?.executeAnimation(A)})()}getProduct(){return this.product}getInitializationPromise(){return this.initializationPromise}isInitialized(){return this.initialized}addVariationRecord(t){const e={...t,recordNumber:this.variationRecords.reduce(((t,e)=>e.recordNumber>t?e.recordNumber:t),0)+1};return this.variationRecords.push(e),this.onVariationRecordsChange(),e}removeVariationRecord(t){if(this.variationRecords=this.variationRecords.filter((e=>e.recordNumber!==t)),this.variationRecords.forEach(((t,e)=>t.recordNumber=e+1)),this.currentVariationRecord&&this.currentVariationRecord.recordNumber===t){const t=this.currentVariationRecord.recordNumber,e=t>1?this.variationRecords[t-2]:this.variationRecords[0];this.setCurrentVariationRecord(e||null)}return this.onVariationRecordsChange(),this.variationRecords}setVariationRecords(t){this.variationRecords=t,this.onVariationRecordsChange(),0===t.length?this.setCurrentVariationRecord(null):this.setCurrentVariationRecord(t[0])}setCurrentVariationRecord(t){if(this.currentVariationRecord=t,this.onCurrentVariationRecordChange(),t){const e=this.variationRecords.find((e=>e.recordNumber===t.recordNumber));e&&(e.values=t.values,this.onVariationRecordsChange())}}addConfirmCallback(t){t(this.confirmedDesign),this.confirmCallbacks.push(t)}addEditedCallback(t){t(this.editedSteps),this.editedCallbacks.push(t)}addElementsCallback(t){t(this.stepElements),this.elementsCallbacks.push(t)}addInformationResultCallback(t){t(this.informationResults),this.informationResultCallbacks.push(t)}addInitCallback(t){t(this.stepInitialised),this.initCallbacks.push(t)}addMandatoryCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}addMetadataCallback(t){t(this.stepMetadata),this.metadataCallbacks.push(t)}async addSelectionCallback(t){t({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:await this.traversableScenes()}),this.selectionCallbacks.push(t)}addStepSpecificStorageCallback(t,e){Object.keys(this.storage).includes(e)||(this.storage[e]={}),t(this.storage[e]),Object.keys(this.stepSpecificStorageCallbacks).includes(e)||(this.stepSpecificStorageCallbacks[e]=[]),this.stepSpecificStorageCallbacks[e].push(t)}addStorageCallback(t){t(this.storage),this.storageCallbacks.push(t)}addMakingAdjustmentsCallback(t){t(this.currentAdjustingStepId),this.makingAdjustmentsCallback.push(t)}addCurrentVariationCallback(t){t(this.currentVariationRecord),this.currentVariationRecordCallbacks.push(t)}addVariationRecordsCallback(t){t(this.variationRecords),this.variationRecordCallbacks.push(t)}addPoller(t){this.pollers.push(t)}getLayouts(){return this.layouts}getAllLayoutData(){return this.commandContext.getAllLayouts().map((t=>t.layoutState))}getLayoutPreviewService(){return this.renderableContextService}getInformationResults(){return this.informationResults}getPreviewService(){return this.previewService}getProfanities(){return this.profanityFilter}getCommandContext(){return this.commandContext}getRegionElements(t){return this.stepElements[t]||[]}getStepSpecificServices(t){return this.stepSpecificServices[t]}getTransaction(){return this.transaction}getTransactionCustomer(){return this.ownerCustomer}setTransactionCustomer(t){this.ownerCustomer=t}setTransactionCustomerDetails(t){this.ownerCustomer={...this.ownerCustomer,emailAddress:t.email}}getModelContainer(){return this.modelContainer}setModelContainer(t){(!t||this.previewService&&this.previewService.getAllModels().includes(t))&&(this.modelContainer=t)}setTransaction(t){this.transaction=t}getWorkflow(){return this.workflow}getCommandDispatcher(){return t=>this.commandContext.apply(t,!this.initialized)}getWorkflowSelections(){const t={};return this.workflow.steps.forEach((e=>{const A=this.stepSelections[e.stepName];A&&A.selectedVariants&&A.selectedVariants.length>0&&(t[e.stepName]={selections:A.selectedVariants})})),t}markStepsAsInitialised(t){const e={...this.stepInitialised};t.forEach((t=>{e[t]=!0})),this.stepInitialised=e,this.onInitChange()}getUpdatesPending(){return this.pendingUpdates.length>0}markUpdateCompleted(t){this.pendingUpdates=this.pendingUpdates.filter((e=>e!==t))}markUpdatePending(){const t=F();return this.pendingUpdates=[...this.pendingUpdates,t],t}setEditedStatus(t,e){this.editedSteps={...this.editedSteps,[t]:e},this.onEditedChange()}setInformationResults(t){this.informationResults=[...t],this.onInformationResultChange()}setCurrentAdjustingStepId(t){this.currentAdjustingStepId=t,this.onMakingAdjustmentsChange()}setMandatoryFulfilled(t,e){this.mandatorySteps[t]!==e&&(this.mandatorySteps={...this.mandatorySteps,[t]:e},this.onMandatoryChange())}toggleDesignConfirmed(){this.confirmedDesign=!this.confirmedDesign,this.onConfirmChange()}toggleMakingAdjustmentsCallback(t){t(this.mandatorySteps),this.mandatoryCallbacks.push(t)}async injectIntoPreviewService(t){if(this.modelContainer)throw new Error("You must eject from the preview service before injecting again.");if(this.previewService=t,!this.getProduct().modelUrl||!this.previewService)return;const e=t.loadModel({model:this.getProduct().modelUrl,contextService:this.getLayoutPreviewService()});this.setModelContainer(e),await e.getInitializationPromise(),this.render3DScene()}ejectFromPreviewService(){if(this.modelContainer){if(!this.modelContainer.dispose)throw new Error("This feature is not supported in the current preview service.");this.modelContainer.dispose(),this.modelContainer=void 0}this.previewService=void 0}async updateStorage(t,e){const A={...this.storage,[t]:{...this.storage[t],...e}};if(!Ot(A,this.storage)){this.storage=A;const e=new ht(this.constructSerializableWorkflow());this.commandContext.apply(e,!0),this.onStepSpecificStorageChange(t),this.onStorageChange()}}constructSerializableWorkflow(){const t=[];return this.allScenes.forEach((e=>{e.renderableSteps.forEach((e=>{const A={stepName:e.stepName};A.storage=this.storage[e.stepName],A.selectedVariants=this.stepSelections[e.stepName]?.selectedVariants?.map((t=>({id:t.id,priceModifier:t.priceModifier}))),t.push(A)}))})),{steps:t}}updateStateWithServer(){if(this.readOnly)return;const t=this.serialize();this.workflowStatePromiseQueue.enqueue(new mi((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})))}async updateStateWithServerImmediate(){if(this.readOnly)return;const t=this.serialize();return new mi((async()=>{await this.updateTransaction({variables:{id:this.transaction.id,workflowState:t.transaction}})})).execute()}serialize(){const t=this.getCommandContext().getState();if(!t)throw new re("Attempted to serialize state before it was initialized.");const e=JSON.stringify(this.dehydrateState(zt(t.transaction))),A=t.variation;if(!A)return{transaction:e};const n={layouts:{},serializableWorkflow:{steps:[]},...zt(A)||{}};return{transaction:e,variation:JSON.stringify(this.dehydrateState(n))}}dehydrateState(t){for(const e of Object.values(t.layouts).map((t=>t.elements)).flat())"illustration"===e.type&&(delete e.cachedObjectURL,e.src&&delete e.svg);return t}async outstandingRequestsPromise(){return this.workflowStatePromiseQueue.finalize()}updateMetadata(t,e){this.stepMetadata={...this.stepMetadata,[t]:{...this.stepMetadata[t],...e}},this.onMetadataChange()}removeElements(t){this.stepElements=((t,e)=>Object.keys(t).reduce(((A,n)=>{const i=[...t[n]||[]];return e.forEach((t=>{const e=i.findIndex((e=>e.id===t.id));e>-1&&i.splice(e,1)})),A[n]=i,A}),{}))(this.stepElements,t)}getInvalidCanvasRegions(){return this.workflow.steps.reduce(((t,e)=>(jn(e,this.stepSelections)||this.stepElements[e.stepName]&&this.stepElements[e.stepName].forEach((e=>t.push(e))),t)),[])}getInvalidModelVariants(){return this.workflow.steps.reduce(((t,e)=>("Model"===e.type&&e.option?.id&&!jn(e,this.stepSelections)&&t.push(e.option.id),t)),[])}async stepElementsForIntroducedSilentSteps(t,e){const A=this.product;if(!A)return Promise.resolve({stepElements:{},commands:[]});const n=async(t,e,A)=>{if(t.type===m.SilentIllustration){return{step:t,results:await new _n(t,e).trigger()}}if(t.type===m.ProductOverlay){return{step:t,results:await new _n(t,e,A).trigger()}}return Promise.reject("Unknown silent step. This is a bug")},i=t.filter((t=>!this.stepInitialised[t.stepName])),a={stepElements:{},commands:[]},o=[];for(const t of i)this.markStepsAsInitialised([t.stepName]),e||o.push(n(t,this.layouts,A));const r=await Promise.all(o);for(const t of r)a.stepElements[t.step.stepName]=t.results.map((t=>t.regionElement)),a.commands=[...a.commands,...t.results.map((t=>t.command))];return a}getStepStorage(t){return this.storage[t]}getMetadata(t){return this.stepMetadata[t]}getWorkflowMetadata(){return this.stepMetadata}getSerializedStep(t,e){return e.find((e=>e.stepName===t))}getCurrentVariationRecord(){return this.currentVariationRecord||void 0}getVariationRecords(){return this.variationRecords}async reset(){this.commandContext.getAllLayouts().forEach((t=>t.layoutState.elements.forEach((t=>{this.getCommandDispatcher()(new s(t.id))})))),this.stepElements={},this.stepInitialised={},this.stepMetadata={},this.stepSelections={},this.storage={},this.currentVariationRecord=null,await this.ensureStepsAreLoaded()}async setSelectionsAndElements(t,e,A,n){const i=this.stepSelections;this.stepSelections={...this.stepSelections,[t]:{selectedVariants:e}},this.selectionCost=Object.values(this.stepSelections).reduce(((t,e)=>t+e.selectedVariants.map((t=>t.priceModifier||0)).reduce(((t,e)=>t+e),0)),0),this.workflow.steps.forEach((t=>{jn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1,delete this.stepMetadata[t.stepName],delete this.stepSelections[t.stepName],delete this.storage[t.stepName])}));const a=this.allScenes,o=Kn(a,i),r=Kn(a,this.stepSelections),c=o.map((t=>t.silentSteps)).flat(),g=r.map((t=>t.silentSteps)).flat().filter((t=>!c.some((e=>e.stepName===t.stepName))));c.forEach((t=>{jn(t,this.stepSelections)||(this.stepInitialised[t.stepName]=!1)})),this.invalidModelVariants=this.getInvalidModelVariants();const l=this.getInvalidCanvasRegions(),{stepElements:B,commands:d}=await this.stepElementsForIntroducedSilentSteps(g,!1);this.stepElements={...this.stepElements,...B,[t]:A},this.removeElements(l);if(this.workflow.steps.find((e=>e.stepName===t))?.type===m.Frame){this.getStepSpecificServices(t)?.frameService?.setTargetElements(A.map((t=>t.id)))}const h=[...d,...l.map((t=>new s(t.id))),new ht(this.constructSerializableWorkflow())];h.length>0&&this.commandContext.apply(new w(h),!0),await this.ensureStepsAreLoaded(),this.onElementsChange(),await this.onSelectionChange(),n&&await n()}async ensureStepsAreLoaded(){const t=[],e=Kn(this.allScenes,this.stepSelections).map((t=>t.renderableSteps)).flat();for(const A of e)if(!this.stepInitialised[A.stepName])switch(this.stepInitialised[A.stepName]=!0,A.type){case m.Bulk:this.updateStorage("Bulk",this.reloadedState?.serializableWorkflow.steps.find((t=>"Bulk"===t.stepName))?.storage||{});break;case m.DigitalContent:t.push(ni.init(A,this,this.reloadedState));break;case m.Frame:case m.Photo:{const e=new Zn(A.data.forceImageCover);e.connectWorkflowManager(this,A.stepName),this.stepSpecificServices[A.stepName]={frameService:e},t.push(ai.init(A,this,this.reloadedState))}break;case m.Illustration:t.push(oi.init(A,this,this.reloadedState));break;case m.Material:t.push(ri.init(A,this,this.reloadedState));break;case m.Model:t.push(si.init(A,this,this.reloadedState));break;case m.Module:this.stepSpecificServices[A.stepName]={module:await ln(A.data.module)},t.push(ci.init(A,this,this.reloadedState));break;case m.Picture:t.push(gi.init(A,this,this.reloadedState));break;case m.Question:t.push(li.init(A,this,this.reloadedState));break;case m.Shape:t.push(Bi.init(A,this,this.reloadedState));break;case m.Text:t.push(Ci.init(A,this,this.reloadedState))}const A=(await Promise.allSettled(t)).map((t=>{if("rejected"===t.status)throw new Error(`Step initialization failed: ${t.reason}`);return t.value})),n=A.filter((t=>!!t&&!!t.command)).map((t=>t.command)),i=A.filter((t=>!!t&&!!t.followup)).map((t=>t.followup));n&&n.length>0&&this.commandContext.apply(new w(n),!0);for(const t of i)await t();i.length>0&&await this.ensureStepsAreLoaded(),this.onInitChange()}onConfirmChange(){this.confirmCallbacks.forEach((t=>t(this.confirmedDesign)))}onEditedChange(){this.editedCallbacks.forEach((t=>t(this.editedSteps)))}onElementsChange(){this.elementsCallbacks.forEach((t=>t(this.stepElements)))}onInformationResultChange(){this.informationResultCallbacks.forEach((t=>t(this.informationResults)))}onInitChange(){this.initCallbacks.forEach((t=>t(this.stepInitialised)))}onMakingAdjustmentsChange(){this.makingAdjustmentsCallback.forEach((t=>{t(this.currentAdjustingStepId)}))}onMandatoryChange(){this.mandatoryCallbacks.forEach((t=>t(this.mandatorySteps)))}onMetadataChange(){this.metadataCallbacks.forEach((t=>{t(this.stepMetadata)}))}async onSelectionChange(){const t=await this.traversableScenes();for(const e of this.selectionCallbacks)e({invalidModelVariants:this.invalidModelVariants,selectionCost:this.selectionCost,selections:this.stepSelections,traversableScenes:t})}onStepSpecificStorageChange(t){Object.keys(this.stepSpecificStorageCallbacks).includes(t)||(this.stepSpecificStorageCallbacks[t]=[]),this.stepSpecificStorageCallbacks[t].forEach((e=>e(this.storage[t])))}onStorageChange(){this.storageCallbacks.forEach((t=>t(this.storage)))}onCurrentVariationRecordChange(){this.currentVariationRecordCallbacks.forEach((t=>{t(this.currentVariationRecord)}))}onVariationRecordsChange(){this.variationRecordCallbacks.forEach((t=>{t(this.variationRecords)})),this.render3DScene()}traversableScenes(){return Vn(this.allScenes,this.stepSelections)}}function Ii(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class fi{constructor(t){Ii(this,"variantData",void 0),this.variantData=t}getType(){return this.variantData.asset?.type}getId(){return this.variantData.id}getName(){return this.variantData.name}getPriceFormatted(t,e){return this.variantData.priceModifier.toLocaleString(t||"en-US",{style:"currency",currency:"USD",...e})}getPrice(){return this.variantData.priceModifier}getAsset(){return this.variantData.thumbnail?.versions?.find((t=>"cdn"===t.name))?.link}getThumbnail(){const t=this.variantData.thumbnail?.versions?.find((t=>"thumbnail"===t.name));return t?t.link:this.variantData.asset?.versions?.find((t=>"thumbnail"===t.name))?.link}getDisplayImage(){return this.variantData.displayImage?.versions?.find((t=>"medium"===t.name))?.link}getColor(){return this.variantData.color}isDefault(){return!!this.variantData.default}getResource(){return this.variantData}isEnabled(){return this.variantData.enabled}}function yi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}class Mi{constructor(t,e){yi(this,"manager",void 0),yi(this,"step",void 0),this.manager=t,this.step=e}setUpdateState(t){Mi.updateState.set(this.step.stepName,t)}getUpdateState(){return!!Mi.updateState.get(this.step.stepName)}getCurrentVariant(){const t=this.manager.getWorkflowSelections()[this.step.stepName]?.selections[0];if(t)return new fi(t)}getAvailableVariants(){return(this.step.option?.variants?.filter((t=>t.enabled))||[]).map((t=>new fi(t)))}getAllVariants(){return(this.step.option?.variants||[]).map((t=>new fi(t)))}getId(){return this.step.stepName}getName(){return this.step.stepTitle}getHelpText(){return this.step.helpText}getType(){return this.step.type}getRaw(){return this.step}executeAnimations(){const t=this.manager.getPreviewService(),e=this.manager.getModelContainer(),A=this.step.data.modelAnimation,n=this.step.data.lookAtAnimation;t&&n&&t.executeCameraAnimation(n),e&&A&&e.executeAnimation(A)}}function Fi(t,e,A){return(e=function(t){var e=function(t,e){if("object"!=typeof t||null===t)return t;var A=t[Symbol.toPrimitive];if(void 0!==A){var n=A.call(t,e||"default");if("object"!=typeof n)return n;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===e?String:Number)(t)}(t,"string");return"symbol"==typeof e?e:String(e)}(e))in t?Object.defineProperty(t,e,{value:A,enumerable:!0,configurable:!0,writable:!0}):t[e]=A,t}yi(Mi,"updateState",new Map);const Yi=ft`
471
471
  mutation AddTransactionStakeholder($id: String!, $type: String!, $details: CustomerDetailsInput!) {
472
472
  transactionAddStakeholder(id: $id, details: $details, type: $type) {
473
473
  id
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@spiffcommerce/core",
3
- "version": "14.3.0",
3
+ "version": "14.3.1",
4
4
  "description": "Core client API for interacting with the Spiff Commerce backend.",
5
5
  "source": "src/index.ts",
6
6
  "main": "dist/main.js",