@spiffcommerce/core 29.1.2 → 29.2.0-beta.75bdea81-46bb-57ec-a9e3-e7dff64e45a7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +6 -0
- package/dist/index.d.ts +31 -4
- package/dist/index.js +7 -3
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +227 -164
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -14,6 +14,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
14
14
|
- `Fixed` for any bug fixes.
|
|
15
15
|
- `Security` in case of vulnerabilities.
|
|
16
16
|
|
|
17
|
+
## [29.2.0] - 25-08-2025
|
|
18
|
+
|
|
19
|
+
## Added
|
|
20
|
+
|
|
21
|
+
- Added the function `TextGlobalPropertyHandle.isTemplatingEnabled(): boolean`. Use this to determine whether you should display any templating tools.
|
|
22
|
+
|
|
17
23
|
## [29.1.2] - 25-08-2025
|
|
18
24
|
|
|
19
25
|
## Changed
|
package/dist/index.d.ts
CHANGED
|
@@ -1365,11 +1365,11 @@ declare abstract class GlobalPropertyHandle {
|
|
|
1365
1365
|
*/
|
|
1366
1366
|
getName(): string;
|
|
1367
1367
|
/**
|
|
1368
|
-
* @returns A human
|
|
1368
|
+
* @returns A human-friendly title.
|
|
1369
1369
|
*/
|
|
1370
1370
|
getTitle(): string;
|
|
1371
1371
|
/**
|
|
1372
|
-
* @returns A human
|
|
1372
|
+
* @returns A human-friendly description.
|
|
1373
1373
|
*/
|
|
1374
1374
|
getDescription(): string;
|
|
1375
1375
|
/**
|
|
@@ -1380,6 +1380,14 @@ declare abstract class GlobalPropertyHandle {
|
|
|
1380
1380
|
* @returns The underlying property data object.
|
|
1381
1381
|
*/
|
|
1382
1382
|
getRawProperty(): GlobalPropertyConfigurationAspect;
|
|
1383
|
+
/**
|
|
1384
|
+
* @returns Whether this aspect has been marked as required to be completed before the user can continue.
|
|
1385
|
+
*/
|
|
1386
|
+
isMandatory(): boolean;
|
|
1387
|
+
/**
|
|
1388
|
+
* @returns Whether this aspect has been marked as `completed` for mandatory checks. Note that this function always returns `true` if the aspect has not been marked as mandatory.
|
|
1389
|
+
*/
|
|
1390
|
+
isMandatoryFulfilled(): boolean;
|
|
1383
1391
|
/**
|
|
1384
1392
|
* Applies the global state to all shared steps, if the state is set.
|
|
1385
1393
|
* @param targetExperiences Optionally filter the workflow experiences it should be applied to.
|
|
@@ -1454,6 +1462,11 @@ declare class FileUploadGlobalPropertyHandle extends GlobalPropertyHandle {
|
|
|
1454
1462
|
}
|
|
1455
1463
|
declare class TextGlobalPropertyHandle extends GlobalPropertyHandle {
|
|
1456
1464
|
constructor(bundle: Bundle$1, property: GlobalPropertyConfigurationAspect);
|
|
1465
|
+
/**
|
|
1466
|
+
* If this returns false, you should not display any templating tools.
|
|
1467
|
+
* Note: Templates will currently still be rendered, regardless of what this function returns.
|
|
1468
|
+
*/
|
|
1469
|
+
isTemplatingEnabled(): boolean;
|
|
1457
1470
|
/**
|
|
1458
1471
|
* Gets the current text
|
|
1459
1472
|
*/
|
|
@@ -1526,12 +1539,15 @@ interface GlobalPropertyStateManager {
|
|
|
1526
1539
|
setGlobalPropertyState(state: GlobalPropertyState): Promise<void>;
|
|
1527
1540
|
getAspect(name: string, channel?: number): string | undefined;
|
|
1528
1541
|
getAspectStorage<S extends GlobalPropertyStateAspectStorage>(name: string, channel?: number): S | undefined;
|
|
1542
|
+
getAspectMandatoryFulfilled(name: string): boolean | undefined;
|
|
1543
|
+
setAspectMandatoryFulfilled(name: string, fulfilled: boolean): Promise<void>;
|
|
1529
1544
|
/**
|
|
1530
1545
|
* Updates the value of a named aspect in the state.
|
|
1531
1546
|
* @param name The name (key) of the aspect. This must match the key in the associated Global Property Config
|
|
1532
1547
|
* @param value The value, represented as a string.
|
|
1533
1548
|
* @param storage Optional: Additional data storage for the aspect. Not specifying this parameter, or providing `undefined`, will not update the
|
|
1534
1549
|
* storage (if it already exists). Providing `null` will clear the existing storage.
|
|
1550
|
+
* @param channel Optional: Additional sub-identifier.
|
|
1535
1551
|
*/
|
|
1536
1552
|
setAspect(name: string, value: string, storage?: GlobalPropertyStateAspectStorage | null, channel?: number): Promise<void>;
|
|
1537
1553
|
setAspectStorage<S extends GlobalPropertyStateAspectStorage>(name: string, storage: S | null, channel?: number): Promise<void>;
|
|
@@ -1766,6 +1782,11 @@ declare const getProductCollections: (ids: string[]) => Promise<ProductCollectio
|
|
|
1766
1782
|
interface ConditionalGlobalPropertiesChangedEventData {
|
|
1767
1783
|
globalProperties: GlobalPropertyHandle[];
|
|
1768
1784
|
}
|
|
1785
|
+
interface GlobalPropertiesMandatoryChangedEventData {
|
|
1786
|
+
changed: GlobalPropertyHandle[];
|
|
1787
|
+
completed: GlobalPropertyHandle[];
|
|
1788
|
+
remaining: GlobalPropertyHandle[];
|
|
1789
|
+
}
|
|
1769
1790
|
interface WorkflowExperienceHoverEventData {
|
|
1770
1791
|
workflowExperience: WorkflowExperience;
|
|
1771
1792
|
}
|
|
@@ -1776,6 +1797,7 @@ interface WorkflowExperienceRemovedEventData extends WorkflowExperienceAddedEven
|
|
|
1776
1797
|
}
|
|
1777
1798
|
type BundleEventMap = {
|
|
1778
1799
|
"conditional-global-properties-changed": ConditionalGlobalPropertiesChangedEventData;
|
|
1800
|
+
"global-properties-mandatory-changed": GlobalPropertiesMandatoryChangedEventData;
|
|
1779
1801
|
"workflow-experience-hover-enter": WorkflowExperienceHoverEventData;
|
|
1780
1802
|
"workflow-experience-hover-exit": WorkflowExperienceHoverEventData;
|
|
1781
1803
|
"workflow-experience-added": WorkflowExperienceAddedEventData;
|
|
@@ -2895,15 +2917,20 @@ interface GlobalPropertyConfigurationAspect {
|
|
|
2895
2917
|
entityId?: string;
|
|
2896
2918
|
conditions?: GlobalPropertyConfigurationAspectCondition[];
|
|
2897
2919
|
data?: GlobalPropertyConfigurationAspectData;
|
|
2920
|
+
mandatory?: boolean;
|
|
2898
2921
|
}
|
|
2899
2922
|
interface GlobalPropertyConfigurationAspectData {
|
|
2900
|
-
fileUpload
|
|
2923
|
+
fileUpload?: GlobalPropertyConfigurationAspectFileUploadData;
|
|
2924
|
+
text?: GlobalPropertyConfigurationAspectTextData;
|
|
2901
2925
|
}
|
|
2902
2926
|
interface GlobalPropertyConfigurationAspectFileUploadData {
|
|
2903
2927
|
colorPickerEnabled?: boolean;
|
|
2904
2928
|
pmsPickerEnabled?: boolean;
|
|
2905
2929
|
colorOptionId?: string;
|
|
2906
2930
|
}
|
|
2931
|
+
interface GlobalPropertyConfigurationAspectTextData {
|
|
2932
|
+
templatingEnabled?: boolean;
|
|
2933
|
+
}
|
|
2907
2934
|
interface GlobalPropertyConfigurationAspectCondition {
|
|
2908
2935
|
targetAspectName?: string;
|
|
2909
2936
|
action: AspectConditionAction;
|
|
@@ -5925,4 +5952,4 @@ declare const validateWorkflowExperienceRecipients: (workflowExperiences: Workfl
|
|
|
5925
5952
|
*/
|
|
5926
5953
|
declare const getGlobalPropertyStateForBundle: (bundleId: string) => Promise<GlobalPropertyState | undefined>;
|
|
5927
5954
|
|
|
5928
|
-
export { AddonHandle, AddressComponent, AddressValidationJob, AddressValidationJobStatus, AddressValidationResult, AddressValidationResultConfirmationLevel, Animatable, AnyStepData, ArrayInput, AspectType, Asset, AssetConfiguration, AssetNotFoundError, AssetObjectVersion, AssetType, BringForwardCommand, BringToBackCommand, BringToFrontCommand, Bundle$1 as Bundle, BundleDesignCreationCartAddMode, BundleDesignCreationMessage, BundleEvent, BundleEventData, BundleEventType, Bundle as BundleRaw, BundleStakeholder, CanvasCommand, CollectionProduct, ColorDefinition, ColorOption, ColorOptionGlobalPropertyHandle, ColorProfileProps, CommandContext, CommandState, Condition, ConditionalGlobalPropertiesChangedEventData, CreateElementCommand, CreateLayoutCommand, CurrencyContext, CurrencyService, Customer, CustomerDetailsInput, DeleteElementCommand, DesignCreationMessage, DesignCreationProgressUpdate, DesignInputStep, DigitalContentStepData, DigitalContentStepHandle, EditedSteps, ExportedStepData, ExportedStepDataProperty, ExportedStepDataPropertyType, FileUploadGlobalPropertyHandle, FlowExecutionNodeResult, FlowExecutionResult, FlowService, FontAlignmentCommand, FontColorCommand, FontSizeCommand, FontSourceCommand, FrameElement, FrameService, FrameStep, FrameStepData, FrameStepHandle, FrameThresholdSettings, GetNewWorkflowOptions, GetWorkflowOptions, GlobalPropertyConfiguration, GlobalPropertyHandle, GroupCommand, ILayout, IllustrationElement, IllustrationStepData, IllustrationStepHandle, ImageElement, InformationMessageType, InformationResult, InformationStepData, InformationStepHandle, Integration, IntegrationOptionResource, IntegrationProduct, IntegrationType, LayoutComponentConfiguration, LayoutData, LayoutElement, LayoutElementFactory, LayoutElementType, LayoutNotFoundError, LayoutRenderingPurpose, LayoutState, LayoutsState, MandatorySteps, MaterialEffectMode, MaterialStepData, MaterialStepHandle, MisconfigurationError, MockWorkflowManager, ModelStepData, ModelStepHandle, ModuleStepData, ModuleStepHandle, MoveCommand, NodeType, ObjectInput, ObjectInputType, OptionGlobalPropertyHandle, OptionNotFoundError, OptionResource, Order, OrderItem, PapyrusComponent, ParseError, PictureStepData, PictureStepHandle, Placeable, PmsSearchResult, Point, Product, ProductCameraRig, ProductCollection, ProductCollectionProductSortKey, ProductWorkflow$1 as ProductWorkflow, promiseCache as PromiseCache, PromiseQueue, QuestionStepData, QuestionStepHandle, QueueablePromise, Recipient, Region, RegionElement, RenderableScene, ResizeCommand, ResourceNotFoundError, RotateCommand, SavedDesign, ScaleAxis, SelectionStorage, SendBackwardsCommand, ShapeStepData, ShapeStepHandle, ShareAction, ShareActionType, SilentIllustrationStepData, SpiffCommerceClient, Stakeholder, StakeholderType, StateMutationFunc, Step, StepAspect, StepAspectType, StepElements, StepGroup, StepHandle, StepStorage, StepType, TextAlgorithm, TextChangeCommand, TextChangeResult, TextGlobalPropertyHandle, TextInput, TextStepData, TextStepHandle, TextStepStorage, TextboxElement, Theme, ToastCallback, Transaction, Transform, TransformCollection$1 as TransformCollection, UnhandledBehaviorError, UnitOfMeasurement, UpdateImageSourceCommand, Variant, VariantResource, Vector3, Workflow, WorkflowExperience, WorkflowExperienceEventType, WorkflowExperienceHoverEventData, WorkflowExperienceImpl, WorkflowManager, WorkflowMetadata, WorkflowPanel, WorkflowScene, WorkflowSelections, WorkflowStorage, assetService, browserColorToHex, cmPerPixel, createDesign, currentDirection, dataUrlFromExternalUrl, designService, determineCorrectFontSizeAndLines, digitalContentStepService, domParser, duplicateBundle, duplicateTransaction, fetchAsString, findAngle, findElement, findPmsColors, frameDataCache, frameStepService, generate, generateCommands, generateSVGWithUnknownColors, generateStateFromDesignInputSteps, getAddressValidationJobs, getAttributesFromArrayBuffer, getAxisAlignedBoundingBox, getBoundedOffsets, getBundleThemeConfiguration, getCustomer, getCustomerBundles, getElementVertices, getFrameData, getGlobalPropertyStateForBundle, getIntegration, getNEPoint, getNWPoint, getOrderedTransactions, getOverrideThemeConfiguration, getPointOfRotation, getProductCollections, getSEPoint, getSvgElement, getTemplateBundles, getTemplateTransactions, getTransaction, getTransactionThemeConfiguration, getTransactionsForBundle, getTrueCoordinates, getUnorderedTransactions, getValidationJobsForWorkflowExperiences, getWorkflow, getWorkflows, graphQlManager, illustrationStepService, isCloseToValue, loadFont, matchHexToPms, materialStepService, metafieldManager, mmPerPixel, modelStepService, modifySVGColors, moduleStepService, nameBundle, nameTransaction, optionService, outlineFontsInSvg, patternImageDataCache, persistenceService, pictureStepService, pmsToRgb, questionStepService, registerFetchImplementation, registerWindowImplementation, rehydrateSerializedLayout, rgbToPms, rotateAroundPoint, sanitizeSvgTree, setBearerAuthenticationToken, setCanvasModule, shapeStepService, shortenUrl, spiffCoreConfiguration, stepAspectValuesToDesignInputSteps, svgColorValueToDefinition, svgStringDimensions, svgToDataUrl, textStepService, toast, validateWorkflowExperienceRecipient, validateWorkflowExperienceRecipients, xmlSerializer };
|
|
5955
|
+
export { AddonHandle, AddressComponent, AddressValidationJob, AddressValidationJobStatus, AddressValidationResult, AddressValidationResultConfirmationLevel, Animatable, AnyStepData, ArrayInput, AspectType, Asset, AssetConfiguration, AssetNotFoundError, AssetObjectVersion, AssetType, BringForwardCommand, BringToBackCommand, BringToFrontCommand, Bundle$1 as Bundle, BundleDesignCreationCartAddMode, BundleDesignCreationMessage, BundleEvent, BundleEventData, BundleEventType, Bundle as BundleRaw, BundleStakeholder, CanvasCommand, CollectionProduct, ColorDefinition, ColorOption, ColorOptionGlobalPropertyHandle, ColorProfileProps, CommandContext, CommandState, Condition, ConditionalGlobalPropertiesChangedEventData, CreateElementCommand, CreateLayoutCommand, CurrencyContext, CurrencyService, Customer, CustomerDetailsInput, DeleteElementCommand, DesignCreationMessage, DesignCreationProgressUpdate, DesignInputStep, DigitalContentStepData, DigitalContentStepHandle, EditedSteps, ExportedStepData, ExportedStepDataProperty, ExportedStepDataPropertyType, FileUploadGlobalPropertyHandle, FlowExecutionNodeResult, FlowExecutionResult, FlowService, FontAlignmentCommand, FontColorCommand, FontSizeCommand, FontSourceCommand, FrameElement, FrameService, FrameStep, FrameStepData, FrameStepHandle, FrameThresholdSettings, GetNewWorkflowOptions, GetWorkflowOptions, GlobalPropertiesMandatoryChangedEventData, GlobalPropertyConfiguration, GlobalPropertyHandle, GroupCommand, ILayout, IllustrationElement, IllustrationStepData, IllustrationStepHandle, ImageElement, InformationMessageType, InformationResult, InformationStepData, InformationStepHandle, Integration, IntegrationOptionResource, IntegrationProduct, IntegrationType, LayoutComponentConfiguration, LayoutData, LayoutElement, LayoutElementFactory, LayoutElementType, LayoutNotFoundError, LayoutRenderingPurpose, LayoutState, LayoutsState, MandatorySteps, MaterialEffectMode, MaterialStepData, MaterialStepHandle, MisconfigurationError, MockWorkflowManager, ModelStepData, ModelStepHandle, ModuleStepData, ModuleStepHandle, MoveCommand, NodeType, ObjectInput, ObjectInputType, OptionGlobalPropertyHandle, OptionNotFoundError, OptionResource, Order, OrderItem, PapyrusComponent, ParseError, PictureStepData, PictureStepHandle, Placeable, PmsSearchResult, Point, Product, ProductCameraRig, ProductCollection, ProductCollectionProductSortKey, ProductWorkflow$1 as ProductWorkflow, promiseCache as PromiseCache, PromiseQueue, QuestionStepData, QuestionStepHandle, QueueablePromise, Recipient, Region, RegionElement, RenderableScene, ResizeCommand, ResourceNotFoundError, RotateCommand, SavedDesign, ScaleAxis, SelectionStorage, SendBackwardsCommand, ShapeStepData, ShapeStepHandle, ShareAction, ShareActionType, SilentIllustrationStepData, SpiffCommerceClient, Stakeholder, StakeholderType, StateMutationFunc, Step, StepAspect, StepAspectType, StepElements, StepGroup, StepHandle, StepStorage, StepType, TextAlgorithm, TextChangeCommand, TextChangeResult, TextGlobalPropertyHandle, TextInput, TextStepData, TextStepHandle, TextStepStorage, TextboxElement, Theme, ToastCallback, Transaction, Transform, TransformCollection$1 as TransformCollection, UnhandledBehaviorError, UnitOfMeasurement, UpdateImageSourceCommand, Variant, VariantResource, Vector3, Workflow, WorkflowExperience, WorkflowExperienceEventType, WorkflowExperienceHoverEventData, WorkflowExperienceImpl, WorkflowManager, WorkflowMetadata, WorkflowPanel, WorkflowScene, WorkflowSelections, WorkflowStorage, assetService, browserColorToHex, cmPerPixel, createDesign, currentDirection, dataUrlFromExternalUrl, designService, determineCorrectFontSizeAndLines, digitalContentStepService, domParser, duplicateBundle, duplicateTransaction, fetchAsString, findAngle, findElement, findPmsColors, frameDataCache, frameStepService, generate, generateCommands, generateSVGWithUnknownColors, generateStateFromDesignInputSteps, getAddressValidationJobs, getAttributesFromArrayBuffer, getAxisAlignedBoundingBox, getBoundedOffsets, getBundleThemeConfiguration, getCustomer, getCustomerBundles, getElementVertices, getFrameData, getGlobalPropertyStateForBundle, getIntegration, getNEPoint, getNWPoint, getOrderedTransactions, getOverrideThemeConfiguration, getPointOfRotation, getProductCollections, getSEPoint, getSvgElement, getTemplateBundles, getTemplateTransactions, getTransaction, getTransactionThemeConfiguration, getTransactionsForBundle, getTrueCoordinates, getUnorderedTransactions, getValidationJobsForWorkflowExperiences, getWorkflow, getWorkflows, graphQlManager, illustrationStepService, isCloseToValue, loadFont, matchHexToPms, materialStepService, metafieldManager, mmPerPixel, modelStepService, modifySVGColors, moduleStepService, nameBundle, nameTransaction, optionService, outlineFontsInSvg, patternImageDataCache, persistenceService, pictureStepService, pmsToRgb, questionStepService, registerFetchImplementation, registerWindowImplementation, rehydrateSerializedLayout, rgbToPms, rotateAroundPoint, sanitizeSvgTree, setBearerAuthenticationToken, setCanvasModule, shapeStepService, shortenUrl, spiffCoreConfiguration, stepAspectValuesToDesignInputSteps, svgColorValueToDefinition, svgStringDimensions, svgToDataUrl, textStepService, toast, validateWorkflowExperienceRecipient, validateWorkflowExperienceRecipients, xmlSerializer };
|
package/dist/index.js
CHANGED
|
@@ -1602,6 +1602,7 @@
|
|
|
1602
1602
|
title
|
|
1603
1603
|
description
|
|
1604
1604
|
entityId
|
|
1605
|
+
mandatory
|
|
1605
1606
|
conditions {
|
|
1606
1607
|
targetAspectName
|
|
1607
1608
|
action
|
|
@@ -1613,6 +1614,9 @@
|
|
|
1613
1614
|
pmsPickerEnabled
|
|
1614
1615
|
colorOptionId
|
|
1615
1616
|
}
|
|
1617
|
+
text {
|
|
1618
|
+
templatingEnabled
|
|
1619
|
+
}
|
|
1616
1620
|
}
|
|
1617
1621
|
}
|
|
1618
1622
|
}
|
|
@@ -2275,7 +2279,7 @@
|
|
|
2275
2279
|
/>
|
|
2276
2280
|
</svg>
|
|
2277
2281
|
`,g={"spiff-fill-shape":{browserValue:s.color||"#000000"}},m=Q();return new q({colors:g,id:m,svg:u,type:k.Illustration,y:d.top,x:d.left,rotation:d.rotation,width:d.width,height:d.height,layer:d.layer,layerIndex:d.layerIndex,immutable:d.immutable},A)},l=a.data.regions;try{return l.map(o)}catch(d){return console.error(d),[]}},Gl=async(r,t,e)=>{const a=[],i=(()=>{var c,d;return t.type===I.ProductOverlay?e||((c=t.data.asset)==null?void 0:c.fileLink)||"":((d=t.data.asset)==null?void 0:d.fileLink)||""})(),o=(()=>i.endsWith(".jpeg")||i.endsWith(".jpg")||i.endsWith(".png")?k.Image:(i.endsWith(".svg"),k.Illustration))(),l=t.data.regions;if(o==="image")try{l.forEach(c=>{const d=r.find(u=>u.panelId===c.panelId);if(!d)throw new Y(c);const A={id:Q(),src:i,type:o,y:c.top,x:c.left,width:c.width,height:c.height,layer:c.layer,layerIndex:c.layerIndex,productOverlay:t.type===I.ProductOverlay?!0:void 0,scaleX:1,scaleY:1,rotation:c.rotation,excludeFromExport:t.data.excludeFromPrint,preserveAspectRatio:"none"};a.push(new q(A,d))})}catch(c){console.error(c)}else{const c=await et(i,!0),d=A=>{const u=/<svg.*?<\/svg>/s,h=A.match(u)||[],g=(h==null?void 0:h.length)>0?h[0]:"",f=ct().parseFromString(g,"image/svg+xml").firstElementChild;if(!f)throw new St("Failed to read SVG.");return $e(f),wt().serializeToString(f)};l.forEach(A=>{const u=r.find(g=>g.panelId===A.panelId);if(!u)throw new Y(A);const h={id:Q(),src:i,asset_key:i,svg:d(c),colors:{},type:o,y:A.top,x:A.left,width:A.width,height:A.height,layer:A.layer,layerIndex:A.layerIndex,scaleX:1,scaleY:1,rotation:A.rotation,productOverlay:t.type===I.ProductOverlay?!0:void 0,excludeFromExport:t.data.excludeFromPrint};a.push(new q(h,u))})}return a},ql=async(r,t,e,a)=>{const n=[],i=e.data,s=30,o=p=>p.vertical?"center":p.textAlign||"center",l=()=>{var w;const p=a.option;if(!p)return;const f=((w=p.variants)==null?void 0:w.find(S=>S.id===i.fontVariantId))||Ae(p);if(!f||!f.asset)return;t[a.stepName]={selectedVariants:[f]};const C=f.asset.fileLink;if(C)return C},d=await(async()=>{const p=l();if(!p)return;const f=await It(p);return{assetUrl:p,name:f.names.fullName.en}})(),A=(a.data.replaceableText?a.data.replaceableText.replace("{{}}",i.text):i.text)||"",u=De(A,{vertical:a.data.vertical,uppercase:a.data.uppercase}),h=async p=>{const f=p.colorOption;if(!f)return;const C=H.getDefaultVariant(f);return C==null?void 0:C.color},g=i.color||await h(a.data),m=a.data.regions;for(const p of m){const f=r.find(w=>w.panelId===p.panelId);if(!f)continue;const C={stepName:e.name,id:Q(),align:o(a.data),curved:a.data.curved,fill:i.color||g||"#000000",fontData:d,fontSize:a.data.size||s,height:p.height,layer:p.layer,layerIndex:p.layerIndex,paths:a.data.paths,rotation:p.rotation,text:u,type:k.Textbox,vertical:a.data.vertical,verticalAlign:a.data.verticalAlign||"middle",width:p.width,x:p.left,y:p.top};if(d){const[w,S]=Kt(a.data.size||s,d,p,[De(u,{vertical:a.data.vertical,uppercase:a.data.uppercase})],{size:a.data.size,minSize:a.data.minSize,maxSize:a.data.maxSize});n.push(new q({...C,fontSize:w,text:C.curved?C.text:(S||[]).join(`
|
|
2278
|
-
`)},f))}else n.push(new q(C,f))}return n},Wl=(r,t)=>r.conditions?r.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const n=a.selectedVariants;return e.requiredVariantSelections.some(i=>n.find(s=>s.id===i)!==void 0)}return!1}):!0,Tr=async(r,t,e,a)=>{const n=[],i={};for(const s of r){const o=t.steps.find(l=>l.stepName===s.name);if(o)switch(o.type){case I.DigitalContent:n.push(...await Ol(e,s,o));break;case I.Frame:case I.Photo:n.push(...await $l(e,i,s,o));break;case I.Illustration:n.push(...await Ul(e,i,s,o));break;case I.Module:n.push(...await Ll(e,s,o));break;case I.Picture:n.push(...await Vl(e,i,s,o));break;case I.Shape:n.push(...await zl(e,i,s,o));break;case I.Text:n.push(...await ql(e,i,s,o));break}}for(const s of t.steps)s.type!==I.SilentIllustration&&s.type!==I.ProductOverlay||Wl(s,i)&&n.push(...await Gl(e,s,a));return n};class jl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Jl(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Hl=()=>new Promise((r,t)=>{try{const a=pt().getContext("webgl2");r(!!a)}catch{r(!1)}}),Yl=Hl();class Jl{constructor(t,e,a,n,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Da(2),this.id=t,this.name=e,this.service=a,this.panelSize=n,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=Et(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new Kl(this.getID(),a,await Yl,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class Kl extends Pa{constructor(t,e,a,n,i,s){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=n,this.layouts=i,this.getWorkflowManager=s}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,n=e/t.height,i=Math.min(a,n);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){var h,g;const t=this.layouts.find(m=>m.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,n=t.layoutState.layout.height,i=a===1||n===1?{width:1,height:1}:this.getDynamicTextureResolution(),s=i.width,o=i.height;let l,c;if(this.nonPOTSupport){const m=s/o;a/n<m?(l=s,c=n*(s/a)):(l=a*(o/n),c=o);const f=this.resizeFit({width:l,height:c});l=f.width,c=f.height}else l=i.width,c=i.height;const d=ze(t.layoutState.layout,e,{renderingConfiguration:{purpose:Tt.ThreeD,templatingContext:(g=(h=this.getWorkflowManager)==null?void 0:h.call(this))==null?void 0:g.getTemplatingContext()}}),A=Tn(d),u=await Sa.Pith.from(this.ctx,A,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:pt,createImage:oe,DOMParser:ba(),fetch});u.resize(l,c),await u.render(),this.onRender()}}const _l=(r,t)=>{const e=[];return r.forEach(a=>{const n=t.steps.find(i=>i.stepName===a.stepName);(n==null?void 0:n.type)===I.Text&&a.stepAspectType==="Text"&&e.push({name:n.stepName,data:{text:a.value}})}),e},Xl=async(r,t,e,a)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};n=new $(e.map(l=>new Na(l))).apply(n);const s=await Tr(r,t,e,a);return new $(s).apply(n)};class Zl{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){var e;if(!((e=this.bundle.getProductCollection())!=null&&e.getResource().globalPropertyConfiguration))return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(a=>this.getHandle(a)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const n=e.aspects.find(i=>i.name===a.targetAspectName);return n?a.requiredVariantSelections.some(i=>i===n.value):!1})}async createHandle(t){switch(t.type){case V.FileUpload:return new Nr(this.bundle,t).initialize();case V.ColorOption:return new Ca(this.bundle,t,t.entityId?await H.getOption(t.entityId):void 0);case V.Option:{const e=t.entityId?await H.getOption(t.entityId):void 0;return(e==null?void 0:e.type)==="Color"?new Ca(this.bundle,t,e):new za(this.bundle,t,e)}case V.Text:return new Qr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Ge{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(n=>n.getStepsConditionallyActive().filter(i=>{var s;return i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:(s=i.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name})}))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Nr extends Ge{constructor(t,e){super(t,e)}async initialize(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorOptionId&&(this.colorOption=await H.getOption((n=(a=this.property.data)==null?void 0:a.fileUpload)==null?void 0:n.colorOptionId)),await this.loadImageData(),this}async loadImageData(){var e;const t=await this.getImage();if(t!=null&&t.fileLink)if(t!=null&&t.fileLink.endsWith(".svg")){const a=await et(t==null?void 0:t.fileLink),n=await Ma(t==null?void 0:t.fileLink),i=n.width,s=n.height,o=await ot(a),l=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);(e=l==null?void 0:l.colors)==null||e.forEach(d=>{o.colors[d.key]={browserValue:d.browserValue,pmsValue:d.pmsValue}});const c={src:t==null?void 0:t.fileLink,width:i,height:s,aspect:i/s,svg:o.svg,colors:o.colors};dt.set(t==null?void 0:t.fileLink,c),this.imageData=c}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Me.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await U.removeBackgroundFromAsset(e),s={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,s):a.setAspectStorage(this.property.name,s)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return U.getLocalOrFromServer(t)}async getImageWithColors(){var t,e;return await this.loadImageData(),(t=this.imageData)!=null&&t.svg?Oe(Ue(this.imageData.svg,this.imageData.colors??{},!1)):(e=this.imageData)==null?void 0:e.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.originalAssetKey)return U.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.backgroundRemovedAssetKey)return U.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){var t;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.useOriginalAsset)??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if((n==null?void 0:n.useOriginalAsset)===t)return;const i={...n,useOriginalAsset:t},s=t?n==null?void 0:n.originalAssetKey:n==null?void 0:n.backgroundRemovedAssetKey,o=[a.setAspect(this.property.name,s||"",i)];if(t)o.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};o.push(l())}o.push(this.loadImageData()),await Promise.all(o),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await U.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const i=new Map(n.colors.map(s=>[s.key,{browserValue:s.browserValue,pmsValue:s.pmsValue}])??[]);this.getSharedSteps(t).forEach(s=>{s.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorPickerEnabled?((n=(a=this.colorOption)==null?void 0:a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})))??[]:[]}getCurrentColors(){var t;return(t=this.imageData)==null?void 0:t.colors}isColorPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.colorPickerEnabled)??!1}isPmsPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.pmsPickerEnabled)??!1}async getOriginalColors(){var e;return(e=this.imageData)!=null&&e.svg?(await ot(this.imageData.svg)).colors:void 0}async changeColors(t){var i;if(!((i=this.imageData)!=null&&i.svg))return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(s=>{s.changeColors(a)});const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([s,o])=>({key:s,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const s=this.getSharedSteps(e).map(o=>{const l=o;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(s)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{var s;if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;((s=n.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name}))&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Qr extends Ge{constructor(t,e){super(t,e)}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(n)}}class za extends Ge{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){var e,a;const t=(a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.find(n=>{var i,s;return n.id===((s=(i=this.optionResource)==null?void 0:i.defaultVariant)==null?void 0:s.id)});t&&await this.selectVariant(new it(t))}getCurrentVariant(){var e,a;if(!this.optionResource)return;const t=this.getStateValue();if(t){const n=(a=this.optionResource.variants)==null?void 0:a.find(i=>i.id===t);return n?new it(n):void 0}else{const n=(e=this.optionResource.variants)==null?void 0:e.find(i=>{var s,o;return i.id===((o=(s=this.optionResource)==null?void 0:s.defaultVariant)==null?void 0:o.id)});return n?new it(n):void 0}}getAvailableVariants(){var e,a;return(((a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.filter(n=>n.enabled))||[]).map(n=>new it(n))}getAllVariants(){var e;return(((e=this.optionResource)==null?void 0:e.variants)||[]).map(a=>new it(a))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyVariantSelection(t)])}async applyGlobalState(t){var n,i;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(i=(n=this.optionResource)==null?void 0:n.variants)==null?void 0:i.find(s=>s.id===e);return a?this.applyVariantSelection(new it(a),t):Promise.resolve()}async applyVariantSelection(t,e){const n=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(n)}}class Ca extends za{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.applyColorVariant(t,void 0,e)])}async applyGlobalState(t){var i,s,o;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(s=(i=this.optionResource)==null?void 0:i.variants)==null?void 0:s.find(l=>l.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new it(a),t);const n=(o=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:o.customColor;n&&this.setCustomColor(n)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(s=>{switch(s.getType()){case I.Shape:return s.selectVariant(t);case I.Text:return s.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case I.Illustration:return s.setColor((a==null?void 0:a.toString())||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){var t,e;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.customColor)||((e=this.getCurrentVariant())==null?void 0:e.getColor())||"#ffffff"}}const tc=(r,t,e,a)=>r.flatMap(n=>n.getSteps()).filter(n=>n.getGlobalPropertyAspects(t).includes(e)&&n.getType()===a),ec=(r,t,e)=>{const n=tc(r,t,e,I.Illustration).map(i=>{var l;const s=(l=i.getCurrentVariant())==null?void 0:l.getAssetResource(),o=i.getColors();return!(s!=null&&s.assetConfiguration)||!o?0:Object.getOwnPropertyNames(o).length});return Math.max(...n)};class ac{constructor(t,e,a,n,i){this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const s=i==null?void 0:i.existingGlobalPropertyState;this.initPromise=s?Promise.resolve(s).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=s}):this.createGlobalPropertyState().then(o=>{console.log("Setting global property state to new state."),this.globalPropertyState=o}),this.onGlobalPropertyStateChange=n}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=Et(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){var a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e))==null?void 0:a.storage}async setAspect(t,e,a,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);const s=Et(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(l=>l.name===t);if(o.length>0)if(n){const l=o.find(c=>c.channel===n);if(l)l.value=e,l.type=i.type,l.channel=n,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(n===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n})}}else{const l=o[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(s,this.globalPropertyState)}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(o=>o.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=Et(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(o=>o.name===t);if(s.length>0)if(a){const o=s.find(l=>l.channel===a);o&&(o.storage=e!==null?e:void 0,o.type=n.type)}else{const o=s[0];o.storage=e!==null?e:void 0,o.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async updateGlobalPropertyState(){var e,a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await B.getShadowGraphqlClient().mutate({mutation:Wo,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(n=>{let i=n.type&&n.storage?{}:void 0;if(i)switch(n.type){case V.FileUpload:{i.fileUpload=n.storage;break}case V.Option:{i.option=n.storage;break}case V.ColorOption:{i=n.storage;break}}return{name:n.name,value:n.value,type:n.type,storage:i,channel:n.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((a=t.data)!=null&&a.globalPropertyStateUpdate)this.globalPropertyState=t.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){var e,a;const t=await B.getShadowGraphqlClient().mutate({mutation:qo,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((a=t.data)!=null&&a.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class nc{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){var s;if(!this.state||!((s=t==null?void 0:t.getWorkflowManager())!=null&&s.getModelContainer()))return;const e=this.state.transactions.find(o=>o.transactionId===t.getWorkflowManager().getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const n=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=n.position,i.rotation=n.rotation,i.scale=n.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(s=>s.transactionId===n);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:n,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){var l,c;if(!((l=t==null?void 0:t.getWorkflowManager())!=null&&l.getModelContainer())||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,n=this.state.transactions.find(d=>d.transactionId===a),i=(c=n==null?void 0:n.transforms)==null?void 0:c[e];if(!i)return;const s=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),o=t.getWorkflowManager().getModelContainer();o.position=s.position,o.rotation=s.rotation,o.scale=s.scale,n.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const rc=v.gql`
|
|
2282
|
+
`)},f))}else n.push(new q(C,f))}return n},Wl=(r,t)=>r.conditions?r.conditions.every(e=>{const a=t[e.targetStepName];if(a&&a.selectedVariants){const n=a.selectedVariants;return e.requiredVariantSelections.some(i=>n.find(s=>s.id===i)!==void 0)}return!1}):!0,Tr=async(r,t,e,a)=>{const n=[],i={};for(const s of r){const o=t.steps.find(l=>l.stepName===s.name);if(o)switch(o.type){case I.DigitalContent:n.push(...await Ol(e,s,o));break;case I.Frame:case I.Photo:n.push(...await $l(e,i,s,o));break;case I.Illustration:n.push(...await Ul(e,i,s,o));break;case I.Module:n.push(...await Ll(e,s,o));break;case I.Picture:n.push(...await Vl(e,i,s,o));break;case I.Shape:n.push(...await zl(e,i,s,o));break;case I.Text:n.push(...await ql(e,i,s,o));break}}for(const s of t.steps)s.type!==I.SilentIllustration&&s.type!==I.ProductOverlay||Wl(s,i)&&n.push(...await Gl(e,s,a));return n};class jl{constructor(t){this.handleCompleteRender=null;const e=new Map;t.forEach(a=>e.set(a.id,new Jl(a.id,a.name,this,{width:a.width,height:a.height},this.getWorkflowManager.bind(this)))),this.layouts=e}setCompleteRenderCallback(t){this.handleCompleteRender=t,t(Array.from(this.layouts.values()))}onCompleteRender(){this.handleCompleteRender&&this.handleCompleteRender(Array.from(this.layouts.values()))}getAll(){return this.layouts}setWorkflowManager(t){this.workflowManager=t}getWorkflowManager(){return this.workflowManager}}const Hl=()=>new Promise((r,t)=>{try{const a=pt().getContext("webgl2");r(!!a)}catch{r(!1)}}),Yl=Hl();class Jl{constructor(t,e,a,n,i){this.hasSetStaticContext=!1,this.interactiveDirty=!1,this.staticCtxDirty=!1,this.lastRequestedRenderArguments=void 0,this.lastCompletedStaticRender=void 0,this.renderQueue=new Da(2),this.id=t,this.name=e,this.service=a,this.panelSize=n,this.getWorkflowManager=i}getID(){return this.id}getName(){return this.name}getPanelSize(){return this.panelSize}getStaticContext(){return this.textureCtx}setStaticContext(t){this.textureCtx=t,this.lastRequestedRenderArguments&&this.render(this.lastRequestedRenderArguments)}getStaticContextDirty(){return this.staticCtxDirty}setStaticContextDirty(t){this.staticCtxDirty=t}getInteractiveCanvasDirty(){return this.interactiveDirty}setInteractiveCanvasDirty(t){this.interactiveDirty=t}markLastCompletedStaticRender(){this.lastCompletedStaticRender=Date.now(),this.service.onCompleteRender()}getLastCompletedStaticRender(){return this.lastCompletedStaticRender}async render(t){const e=Et(t);this.lastRequestedRenderArguments=e;const a=this.getStaticContext();if(!a){this.markLastCompletedStaticRender(),this.setStaticContextDirty(!1);return}this.renderQueue.enqueue(new Kl(this.getID(),a,await Yl,()=>{this.markLastCompletedStaticRender(),this.setStaticContextDirty(!0)},e,this.getWorkflowManager))}}class Kl extends Pa{constructor(t,e,a,n,i,s){super(),this.layoutId=t,this.ctx=e,this.nonPOTSupport=a,this.onRender=n,this.layouts=i,this.getWorkflowManager=s}getDynamicTextureResolution(){return this.getIsMobile()||!this.offscreenRenderingSupported()?{width:1024,height:1024}:{width:2048,height:2048}}getIsMobile(){return window.innerWidth<=480}offscreenRenderingSupported(){return navigator.userAgent.includes("SamsungBrowser")?!1:!!window.Worker&&!!window.OffscreenCanvas}resizeFit(t,e=4096){const a=e/t.width,n=e/t.height,i=Math.min(a,n);return i>1?t:{width:t.width*i,height:t.height*i}}async execute(){var h,g;const t=this.layouts.find(m=>m.layoutState.layout.id===this.layoutId);if(!t)return;const e=t.layoutState.elements||[],a=t.layoutState.layout.width,n=t.layoutState.layout.height,i=a===1||n===1?{width:1,height:1}:this.getDynamicTextureResolution(),s=i.width,o=i.height;let l,c;if(this.nonPOTSupport){const m=s/o;a/n<m?(l=s,c=n*(s/a)):(l=a*(o/n),c=o);const f=this.resizeFit({width:l,height:c});l=f.width,c=f.height}else l=i.width,c=i.height;const d=ze(t.layoutState.layout,e,{renderingConfiguration:{purpose:Tt.ThreeD,templatingContext:(g=(h=this.getWorkflowManager)==null?void 0:h.call(this))==null?void 0:g.getTemplatingContext()}}),A=Tn(d),u=await Sa.Pith.from(this.ctx,A,{anonymousCrossOrigin:!0,ignoreDimensions:!this.nonPOTSupport,ignoreAnimation:!0,ignoreClear:!0,ignoreMouse:!0,enableRedraw:!1,createCanvas:pt,createImage:oe,DOMParser:ba(),fetch});u.resize(l,c),await u.render(),this.onRender()}}const _l=(r,t)=>{const e=[];return r.forEach(a=>{const n=t.steps.find(i=>i.stepName===a.stepName);(n==null?void 0:n.type)===I.Text&&a.stepAspectType==="Text"&&e.push({name:n.stepName,data:{text:a.value}})}),e},Xl=async(r,t,e,a)=>{let n={serializableWorkflow:{steps:[]},layouts:{}};n=new $(e.map(l=>new Na(l))).apply(n);const s=await Tr(r,t,e,a);return new $(s).apply(n)};class Zl{constructor(t){this.handleCache={},this.bundle=t}async getHandle(t){if(this.handleCache[t.name])return this.handleCache[t.name];const e=await this.createHandle(t);return this.handleCache[t.name]=e,e}async getHandles(){var e;if(!((e=this.bundle.getProductCollection())!=null&&e.getResource().globalPropertyConfiguration))return[];await this.bundle.getGlobalPropertyStateManager().getInitializationPromise();const t=this.bundle.getProductCollection().getResource().globalPropertyConfiguration;return Promise.all(t.aspects.map(a=>this.getHandle(a)))}applyConditionsFromState(t,e){return e?t.filter(a=>this.aspectConditionsSatisfied(a.getRawProperty(),e)):t}aspectConditionsSatisfied(t,e){return!t.conditions||t.conditions.length===0?!0:t.conditions.some(a=>{const n=e.aspects.find(i=>i.name===a.targetAspectName);return n?a.requiredVariantSelections.some(i=>i===n.value):!1})}async createHandle(t){switch(t.type){case V.FileUpload:return new Nr(this.bundle,t).initialize();case V.ColorOption:return new Ca(this.bundle,t,t.entityId?await H.getOption(t.entityId):void 0);case V.Option:{const e=t.entityId?await H.getOption(t.entityId):void 0;return(e==null?void 0:e.type)==="Color"?new Ca(this.bundle,t,e):new za(this.bundle,t,e)}case V.Text:return new Qr(this.bundle,t);default:throw new Error("Unhandled Global Property Aspect Type")}}}class Ge{constructor(t,e){this.bundle=t,this.property=e}getName(){return this.property.name}getTitle(){return this.property.title}getDescription(){return this.property.description}getType(){return this.property.type}getRawProperty(){return this.property}isMandatory(){return!!this.property.mandatory}isMandatoryFulfilled(){return!this.property.mandatory||!!this.bundle.getGlobalPropertyStateManager().getAspectMandatoryFulfilled(this.property.name)}getSharedSteps(t){return(t??this.bundle.getWorkflowExperiences()).flatMap(n=>n.getStepsConditionallyActive().filter(i=>{var s;return i.getOverrideGlobalPropertyConfiguration(this.property.type)?!1:(s=i.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name})}))}getStateValue(){return this.bundle.getGlobalPropertyStateManager().getAspect(this.property.name)}}class Nr extends Ge{constructor(t,e){super(t,e)}async initialize(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorOptionId&&(this.colorOption=await H.getOption((n=(a=this.property.data)==null?void 0:a.fileUpload)==null?void 0:n.colorOptionId)),await this.loadImageData(),this}async loadImageData(){var e;const t=await this.getImage();if(t!=null&&t.fileLink)if(t!=null&&t.fileLink.endsWith(".svg")){const a=await et(t==null?void 0:t.fileLink),n=await Ma(t==null?void 0:t.fileLink),i=n.width,s=n.height,o=await ot(a),l=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);(e=l==null?void 0:l.colors)==null||e.forEach(d=>{o.colors[d.key]={browserValue:d.browserValue,pmsValue:d.pmsValue}});const c={src:t==null?void 0:t.fileLink,width:i,height:s,aspect:i/s,svg:o.svg,colors:o.colors};dt.set(t==null?void 0:t.fileLink,c),this.imageData=c}else this.imageData=void 0}async selectImage(t){const e=this.bundle.getGlobalPropertyStateManager();await Promise.all([e.setAspect(this.property.name,t.key,{...e.getAspectStorage(this.property.name)||{},originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0},void 0),e.setAspectMandatoryFulfilled(this.property.name,!0),this.applyImageSelection(t),this.loadImageData()])}async canUseBackgroundRemover(){return this.bundle.getClient().canUseAddon(Me.BackgroundRemover)}async removeBackgroundFromImage(t=!0){if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImage();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=this.bundle.getGlobalPropertyStateManager(),n=await U.removeBackgroundFromAsset(e),s={...a.getAspectStorage(this.property.name),backgroundRemovedAssetKey:n.key,useOriginalAsset:!t},l=[t?a.setAspect(this.property.name,n.key,s):a.setAspectStorage(this.property.name,s)];return t&&(l.push(this.applyImageSelection(n,void 0,!1,!1)),l.push(this.loadImageData())),await Promise.all(l),this.updateSharedStepStorage(s),n}hasImage(){return!!this.getStateValue()}async getImage(){const t=this.getStateValue();if(t)return U.getLocalOrFromServer(t)}async getImageWithColors(){var t,e;return await this.loadImageData(),(t=this.imageData)!=null&&t.svg?Oe(Ue(this.imageData.svg,this.imageData.colors??{},!1)):(e=this.imageData)==null?void 0:e.src}async getOriginalImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.originalAssetKey)return U.getLocalOrFromServer(t.originalAssetKey)}async getBackgroundRemovedImage(){const t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(t!=null&&t.backgroundRemovedAssetKey)return U.getLocalOrFromServer(t.backgroundRemovedAssetKey)}getUseOriginalImage(){var t;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.useOriginalAsset)??!1}async setUseOriginalImage(t){const e=await this.getOriginalImage();if(!e)throw new Error("You must select an image before calling setUseOriginalImage");const a=this.bundle.getGlobalPropertyStateManager(),n=a.getAspectStorage(this.property.name);if((n==null?void 0:n.useOriginalAsset)===t)return;const i={...n,useOriginalAsset:t},s=t?n==null?void 0:n.originalAssetKey:n==null?void 0:n.backgroundRemovedAssetKey,o=[a.setAspect(this.property.name,s||"",i)];if(t)o.push(this.applyImageSelection(e,void 0,!1,!1));else{const l=async()=>{const c=await this.getBackgroundRemovedImage();if(!c)throw new Error("You must call removeBackgroundFromImage before attempting to use that version of the image.");this.applyImageSelection(c,void 0,!1,!1)};o.push(l())}o.push(this.loadImageData()),await Promise.all(o),this.updateSharedStepStorage(i)}async applyGlobalState(t){const e=this.getStateValue();if(!e)return;const a=await U.getLocalOrFromServer(e);if(!a)return;await this.applyImageSelection(a,t,!1,!0);const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);if(n){if(this.updateSharedStepStorage({...n}),n.colors){const i=new Map(n.colors.map(s=>[s.key,{browserValue:s.browserValue,pmsValue:s.pmsValue}])??[]);this.getSharedSteps(t).forEach(s=>{s.changeColors(i)})}}else this.updateSharedStepStorage({originalAssetKey:e}),await this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{originalAssetKey:e})}getAvailableColors(){var t,e,a,n;return(e=(t=this.property.data)==null?void 0:t.fileUpload)!=null&&e.colorPickerEnabled?((n=(a=this.colorOption)==null?void 0:a.variants)==null?void 0:n.map(i=>({fill:i.color,stroke:i.color,variant:i,pmsValue:i.name})))??[]:[]}getCurrentColors(){var t;return(t=this.imageData)==null?void 0:t.colors}isColorPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.colorPickerEnabled)??!1}isPmsPickerEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.fileUpload)==null?void 0:e.pmsPickerEnabled)??!1}async getOriginalColors(){var e;return(e=this.imageData)!=null&&e.svg?(await ot(this.imageData.svg)).colors:void 0}async changeColors(t){var i;if(!((i=this.imageData)!=null&&i.svg))return;const e=this.getSharedSteps(),a=new Map(Object.entries(t));e.forEach(s=>{s.changeColors(a)});const n=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name);await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{...n,colors:Object.entries(t).map(([s,o])=>({key:s,browserValue:o.browserValue,pmsValue:o.pmsValue}))}),await this.loadImageData()])}async applyImageSelection(t,e,a=!0,n=!0){const s=this.getSharedSteps(e).map(o=>{const l=o;if(l.getFrameService())return l.selectImage(t,a,n)});await Promise.all(s)}updateSharedStepStorage(t){this.bundle.getWorkflowExperiences().forEach(a=>a.getSteps().forEach(n=>{var s;if(n.getOverrideGlobalPropertyConfiguration(this.property.type))return;((s=n.getRaw().globalPropertyAspectConfigurations)==null?void 0:s.some(o=>{var l,c;return o.globalPropertyConfigurationId===((c=(l=this.bundle.getProductCollection())==null?void 0:l.getResource().globalPropertyConfiguration)==null?void 0:c.id)&&o.aspectName===this.property.name}))&&a.getWorkflowManager().updateStorage(n.getId(),{framePatternData:{originalAssetKey:t.originalAssetKey,backgroundRemovedAssetKey:t.backgroundRemovedAssetKey,useOriginalAsset:t.useOriginalAsset}})}))}}class Qr extends Ge{constructor(t,e){super(t,e)}isTemplatingEnabled(){var t,e;return((e=(t=this.property.data)==null?void 0:t.text)==null?void 0:e.templatingEnabled)||!1}getText(){const t=this.getStateValue();return t||""}async setText(t){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t,void 0,void 0),this.bundle.getGlobalPropertyStateManager().setAspectMandatoryFulfilled(this.property.name,t.trim()!==""),this.applyTextSelection(t)])}async applyGlobalState(t){const e=this.getStateValue();if(!e)return Promise.resolve();await this.applyTextSelection(e,t)}async applyTextSelection(t,e){const n=this.getSharedSteps(e).map(i=>{i.setText(t)});await Promise.all(n)}}class za extends Ge{constructor(t,e,a){super(t,e),this.optionResource=a}async initDefaultVariant(){var e,a;const t=(a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.find(n=>{var i,s;return n.id===((s=(i=this.optionResource)==null?void 0:i.defaultVariant)==null?void 0:s.id)});t&&await this.selectVariant(new it(t))}getCurrentVariant(){var e,a;if(!this.optionResource)return;const t=this.getStateValue();if(t){const n=(a=this.optionResource.variants)==null?void 0:a.find(i=>i.id===t);return n?new it(n):void 0}else{const n=(e=this.optionResource.variants)==null?void 0:e.find(i=>{var s,o;return i.id===((o=(s=this.optionResource)==null?void 0:s.defaultVariant)==null?void 0:o.id)});return n?new it(n):void 0}}getAvailableVariants(){var e,a;return(((a=(e=this.optionResource)==null?void 0:e.variants)==null?void 0:a.filter(n=>n.enabled))||[]).map(n=>new it(n))}getAllVariants(){var e;return(((e=this.optionResource)==null?void 0:e.variants)||[]).map(a=>new it(a))}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.bundle.getGlobalPropertyStateManager().setAspectMandatoryFulfilled(this.property.name,!0),this.applyVariantSelection(t)])}async applyGlobalState(t){var n,i;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(i=(n=this.optionResource)==null?void 0:n.variants)==null?void 0:i.find(s=>s.id===e);return a?this.applyVariantSelection(new it(a),t):Promise.resolve()}async applyVariantSelection(t,e){const n=this.getSharedSteps(e).map(i=>i.selectVariant(t));await Promise.all(n)}}class Ca extends za{constructor(t,e,a){super(t,e,a)}async selectVariant(t,e){await Promise.all([this.bundle.getGlobalPropertyStateManager().setAspect(this.property.name,t.getId(),void 0,e),this.bundle.getGlobalPropertyStateManager().setAspectMandatoryFulfilled(this.property.name,!0),this.applyColorVariant(t,void 0,e)])}async applyGlobalState(t){var i,s,o;const e=this.getStateValue();if(!e)return Promise.resolve();const a=(s=(i=this.optionResource)==null?void 0:i.variants)==null?void 0:s.find(l=>l.id===e);if(!a)return Promise.resolve();await this.applyColorVariant(new it(a),t);const n=(o=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:o.customColor;n&&this.setCustomColor(n)}async applyColorVariant(t,e,a){const i=this.getSharedSteps(e).map(s=>{switch(s.getType()){case I.Shape:return s.selectVariant(t);case I.Text:return s.setFillColor({fill:t.getColor(),stroke:t.getColor(),variant:t.getResource()});case I.Illustration:return s.setColor((a==null?void 0:a.toString())||"",t.getColor()||"")}});await Promise.all(i)}setCustomColor(t){this.getSharedSteps().forEach(a=>a.setCustomColor(t)),this.bundle.getGlobalPropertyStateManager().setAspectStorage(this.property.name,{customColor:t})}getCustomColor(){var t,e;return((t=this.bundle.getGlobalPropertyStateManager().getAspectStorage(this.property.name))==null?void 0:t.customColor)||((e=this.getCurrentVariant())==null?void 0:e.getColor())||"#ffffff"}}const tc=(r,t,e,a)=>r.flatMap(n=>n.getSteps()).filter(n=>n.getGlobalPropertyAspects(t).includes(e)&&n.getType()===a),ec=(r,t,e)=>{const n=tc(r,t,e,I.Illustration).map(i=>{var l;const s=(l=i.getCurrentVariant())==null?void 0:l.getAssetResource(),o=i.getColors();return!(s!=null&&s.assetConfiguration)||!o?0:Object.getOwnPropertyNames(o).length});return Math.max(...n)};class ac{constructor(t,e,a,n,i){this.mandatoryFulfilledAspects=new Map,this.bundleId=t,this.bundleOwnerId=e,this.configuration=a,this.bundleOptions=i;const s=i==null?void 0:i.existingGlobalPropertyState;this.initPromise=s?Promise.resolve(s).then(()=>{console.log("Setting global property state to existing state."),this.globalPropertyState=s,this.recalculateMandatoryStates()}):this.createGlobalPropertyState().then(o=>{console.log("Setting global property state to new state."),this.globalPropertyState=o,this.recalculateMandatoryStates()}),this.onGlobalPropertyStateChange=n}recalculateMandatoryStates(){var t;this.mandatoryFulfilledAspects.clear(),(t=this.globalPropertyState)==null||t.aspects.forEach(e=>{e.value!==""&&(this.mandatoryFulfilledAspects[e.name]=!0)})}setBundleOptions(t){this.bundleOptions=t}getBundleOptions(){return this.bundleOptions}setConfiguration(t){this.configuration=t}getInitializationPromise(){return this.initPromise}getGlobalPropertyState(){return this.globalPropertyState}async setGlobalPropertyState(t){this.globalPropertyState||await this.initPromise;const e=Et(this.globalPropertyState);this.globalPropertyState={...t,id:e.id},this.recalculateMandatoryStates(),await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(e,this.globalPropertyState)}getAspectMandatoryFulfilled(t){return this.mandatoryFulfilledAspects[t]}async setAspectMandatoryFulfilled(t,e){this.mandatoryFulfilledAspects[t]=e,await this.onGlobalPropertyStateChange(this.globalPropertyState,this.globalPropertyState)}getAspect(t,e){if(!this.globalPropertyState)throw new Error("Global property state not initialized");const a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e);if(a)return a.value}getAspectStorage(t,e){var a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");return(a=this.globalPropertyState.aspects.find(n=>n.name===t&&n.channel===e))==null?void 0:a.storage}async setAspect(t,e,a,n){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const i=this.configuration.aspects.find(l=>l.name===t);if(!i)throw new Error(`Failed to find configuration aspect with name: ${t}`);const s=Et(this.globalPropertyState),o=this.globalPropertyState.aspects.filter(l=>l.name===t);if(o.length>0)if(n){const l=o.find(c=>c.channel===n);if(l)l.value=e,l.type=i.type,l.channel=n,a!==void 0&&(l.storage=a!==null?a:void 0);else{if(n===1){const c=this.globalPropertyState.aspects.findIndex(d=>!d.channel&&d.name===t);c&&c>0&&this.globalPropertyState.aspects.splice(c,1)}this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n})}}else{const l=o[0];l.value=e,l.type=i.type,a!==void 0&&(l.storage=a!==null?a:void 0)}else this.globalPropertyState.aspects.push({name:t,value:e,type:i.type,storage:a!==null?a:void 0,channel:n});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(s,this.globalPropertyState)}async setAspectStorage(t,e,a){if(!this.globalPropertyState)throw new Error("Global property state not initialized");if(!this.configuration)throw new Error("Global property configuration not linked to the state manager.");const n=this.configuration.aspects.find(o=>o.name===t);if(!n)throw new Error(`Failed to find configuration aspect with name: ${t}`);const i=Et(this.globalPropertyState),s=this.globalPropertyState.aspects.filter(o=>o.name===t);if(s.length>0)if(a){const o=s.find(l=>l.channel===a);o&&(o.storage=e!==null?e:void 0,o.type=n.type)}else{const o=s[0];o.storage=e!==null?e:void 0,o.type=n.type}else this.globalPropertyState.aspects.push({name:t,value:"",type:n.type,storage:e!==null?e:void 0,channel:a});await this.updateGlobalPropertyState(),await this.onGlobalPropertyStateChange(i,this.globalPropertyState)}async updateGlobalPropertyState(){var e,a;if(!this.globalPropertyState)throw new Error("Global property state not initialized");const t=await B.getShadowGraphqlClient().mutate({mutation:Wo,variables:{id:this.globalPropertyState.id,aspects:this.globalPropertyState.aspects.map(n=>{let i=n.type&&n.storage?{}:void 0;if(i)switch(n.type){case V.FileUpload:{i.fileUpload=n.storage;break}case V.Option:{i.option=n.storage;break}case V.ColorOption:{i=n.storage;break}}return{name:n.name,value:n.value,type:n.type,storage:i,channel:n.channel}})},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((a=t.data)!=null&&a.globalPropertyStateUpdate)this.globalPropertyState=t.data.globalPropertyStateUpdate;else throw new Error("Unable to update global property state")}async createGlobalPropertyState(){var e,a;const t=await B.getShadowGraphqlClient().mutate({mutation:qo,variables:{bundleId:this.bundleId},context:{headers:{bundleOwnerId:this.bundleOwnerId,...(e=this.bundleOptions)==null?void 0:e.additionalHeaders}}});if((a=t.data)!=null&&a.globalPropertyStateCreate&&t.data.globalPropertyStateCreate.id)return t.data.globalPropertyStateCreate;throw new Error(`Unable to create global property state for bundle: ${this.bundleId}`)}}class nc{constructor(t){this.setState(t)}setState(t){t&&(this.state=JSON.parse(t))}applyStateToWorkflowExperience(t){var s;if(!this.state||!((s=t==null?void 0:t.getWorkflowManager())!=null&&s.getModelContainer()))return;const e=this.state.transactions.find(o=>o.transactionId===t.getWorkflowManager().getTransaction().id);if(!e)return;const a=this.getTransformToApply(e);if(!a)return;const n=this.flipTransform(a,t.getWorkflowManager().getPreviewService()),i=t.getWorkflowManager().getModelContainer();i.position=n.position,i.rotation=n.rotation,i.scale=n.scale}getTransformToApply(t){return t.activeTransform&&t.transforms?t.transforms[t.activeTransform]:t.transform}updateWorkflowExperienceTransform(t,e,a){const n=t.getWorkflowManager().getTransaction().id;this.state?this.state.transactions||(this.state.transactions=[]):this.state={transactions:[]};const i=this.state.transactions.find(s=>s.transactionId===n);i?(i.transforms||(i.transforms={}),i.transforms[e]=a):this.state.transactions.push({transactionId:n,activeTransform:e,transforms:{[e]:a}})}activateWorkflowExperienceTransform(t,e){var l,c;if(!((l=t==null?void 0:t.getWorkflowManager())!=null&&l.getModelContainer())||!this.state)return;const a=t.getWorkflowManager().getTransaction().id,n=this.state.transactions.find(d=>d.transactionId===a),i=(c=n==null?void 0:n.transforms)==null?void 0:c[e];if(!i)return;const s=this.flipTransform(i,t.getWorkflowManager().getPreviewService()),o=t.getWorkflowManager().getModelContainer();o.position=s.position,o.rotation=s.rotation,o.scale=s.scale,n.activeTransform=e}removeStateForTransaction(t){if(!this.state||!this.state.transactions)return;const e=this.state.transactions.findIndex(a=>a.transactionId===t);e!==-1&&this.state.transactions.splice(e,1)}getSerializedState(){if(this.state)return this.deleteFieldNameFromObjectRecursive(this.state,"__typename"),JSON.stringify(this.state)}deleteFieldNameFromObjectRecursive(t,e){if(!(typeof t!="object"||t===null))for(const a in t)a===e?delete t[a]:this.deleteFieldNameFromObjectRecursive(t[a],e)}flipTransform(t,e){return e&&e.flipTransform?e.flipTransform(t.position,{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},t.scale):{position:t.position,rotation:{x:t.rotation.x*Math.PI/180,y:t.rotation.y*Math.PI/180,z:t.rotation.z*Math.PI/180},scale:t.scale}}}const rc=v.gql`
|
|
2279
2283
|
query GetManyMetafields($entityIds: [String!]!) {
|
|
2280
2284
|
metafieldsMany(entityIds: $entityIds) {
|
|
2281
2285
|
id
|
|
@@ -2328,7 +2332,7 @@
|
|
|
2328
2332
|
quoteId
|
|
2329
2333
|
}
|
|
2330
2334
|
}
|
|
2331
|
-
`;class ea{constructor(t,e,a,n,i,s){var c,d,A;this.workflowExperiences=[],this.eventEmitter=new lc,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(((c=e.metadata)==null?void 0:c.map(u=>[u.key,u.value]))||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new nc(e.bundleStateData);const o=(d=this.productCollection)==null?void 0:d.globalPropertyConfiguration;this.globalConfigurationPropertyId=o==null?void 0:o.id,this.globalPropertyStateManager=new ac(this.id,this.ownerId,o,this.checkConditionalHandlesChanged.bind(this),s),this.globalPropertyHandleService=new Zl(this),this.setPreviewService(a);const l=new Promise((u,h)=>{if(s!=null&&s.readonly){u([]);return}console.log("Setting default global variants.");const g=this.globalPropertyStateManager.getGlobalPropertyState();g?this.globalPropertyHandleService.getHandles().then(m=>{const p=m.map(f=>{if(f.getType()===V.ColorOption||f.getType()===V.Option){const C=f;if(!g.aspects.find(S=>S.name===C.getName()))return C.initDefaultVariant()}});Promise.all(p).then(u).catch(h)}):(console.log("Attempted to set global default variant before state was initialized."),u([]))});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(((A=e.transactions)==null?void 0:A.map(u=>u.id))||[],{...n,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(u=>{console.error(`Bundle initialization failed: ${u}`)})}getTemplate(){return this.template}async generateQuoteId(){var a,n;const e=(n=(a=(await B.getShadowGraphqlClient().mutate({mutation:Ac,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data)==null?void 0:a.bundleGenerateQuoteId)==null?void 0:n.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,n,i,s){await B.getShadowGraphqlClient().mutate({mutation:cc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:i||void 0,postCode:s||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await B.getShadowGraphqlClient().mutate({mutation:dc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){var t;return!!((t=this.productCollection)!=null&&t.globalPropertyConfiguration)}getGlobalPropertyConfiguration(){var t;return(t=this.productCollection)==null?void 0:t.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){var a;const e=await this.globalPropertyHandleService.getHandles();for(const n of t.aspects){const i=n==null?void 0:n.name;this.getGlobalPropertyStateManager().setAspect(i,n.value)}for(const n of t.aspects){const i=n==null?void 0:n.name,s=e.find(o=>o.getName()===i);if(s)switch(n.type){case V.FileUpload:{const o=s,l=await Ie([n.value]);l.length>0&&await o.selectImage(l[0]);const c=(a=n.storage)==null?void 0:a.colors;if(c){const d=Object.fromEntries(c.map(A=>[A.key,{browserValue:A.browserValue,pmsValue:A.pmsValue}])??[]);await o.changeColors(d)}break}case V.ColorOption:{const o=s;if(n.type===V.ColorOption){const c=o.getAllVariants().find(d=>d.getId()===n.value);c&&await o.selectVariant(c)}else o.setCustomColor(n.value);break}case V.Option:{const o=s,c=o.getAllVariants().find(d=>d.getId()===n.value);c&&await o.selectVariant(c);break}case V.Text:{await s.setText(n.value);break}}}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===V.Option).map(a=>{var n;return((n=a.getCurrentVariant())==null?void 0:n.getPrice())||0}).reduce((a,n)=>a+n,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new Ga(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){var e,a,n,i;for(const s of t.getStepsByType(I.Illustration)){const o=s.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const l of o){const c=(e=this.getGlobalPropertyConfiguration())==null?void 0:e.aspects.find(d=>d.name===l);if(c&&c.type===V.ColorOption){const d=(a=s.getCurrentVariant())==null?void 0:a.getAssetResource(),A=((n=d==null?void 0:d.assetConfiguration)==null?void 0:n.channelNumbers)||[],u=((i=d==null?void 0:d.assetConfiguration)==null?void 0:i.defaultColorVariants)||[],h=ec(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",l),g=[...new Set(A.map(p=>p.number))];if(g.length>h)for(const p of g){const f=this.getGlobalPropertyStateManager(),C=u.find(w=>w.channelNumber===p);C&&await f.setAspect(l,C.variant.id||"",void 0,C.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const o of t)await this.initializeAdditionalRequiredColorChannels(o);const e=t.map(o=>o.getWorkflowManager().getTransaction().id),a=e.map(o=>this.workflowExperiences.find(l=>l.getWorkflowManager().getTransaction().id===o));if(a.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(o=>!!o).map(o=>o==null?void 0:o.getWorkflowManager().getTransaction().id).join(", "));const n=N.getMap("transactionOwnerIds")||new Map,i=e.map(o=>n.get(o));await B.getShadowGraphqlClient().mutate({mutation:rl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...t);const s=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const l of o)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),s()]),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const s=(N.getMap("transactionOwnerIds")||new Map).get(a);await B.getShadowGraphqlClient().mutate({mutation:nl,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:s}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const n=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);if(n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await B.getShadowGraphqlClient().mutate({mutation:il,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,s])=>({key:i,value:s})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(n=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id));if(e.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((n,i)=>e[i]===-1).map(n=>n.id).join(", "));const a=t.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id),1)[0]);a.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&a.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),t.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await B.getShadowGraphqlClient().mutate({mutation:sl,variables:{id:this.id,transactionIds:t.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,i])=>({key:n,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(n=>n.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){var i;const a=await B.getShadowGraphqlClient().mutate({mutation:ol,variables:{id:this.id,details:t,type:e||Zt.Owner},context:{bundleOwnerId:this.ownerId}});if(!((i=a.data)!=null&&i.bundleAddStakeholder))throw new Error("Bundle not found!");const n=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async removeStakeholder(t){var a;if(!((a=(await B.getShadowGraphqlClient().mutate({mutation:ll,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data)!=null&&a.bundleRemoveStakeholder))throw new Error("Bundle not found!")}async updateStakeholders(t){var n;const e=await B.getShadowGraphqlClient().mutate({mutation:cl,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!((n=e.data)!=null&&n.bundleUpdateStakeholders))throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await B.getShadowGraphqlClient().query({query:dn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await B.getShadowGraphqlClient().query({query:dn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){if(this.completed)return await B.getShadowGraphqlClient().mutate({mutation:gl,variables:{bundleId:this.id}}),{bundleId:this.id,items:[],bundleOwnerId:this.ownerId};const a=await xl(this.workflowExperiences.map(n=>({workflowManager:n.getWorkflowManager(),workflow:n.getWorkflowManager().getWorkflow(),layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:n.getWorkflowManager().getProduct(),transaction:n.getWorkflowManager().getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:n.getWorkflowManager().getWorkflow().name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(n,i)=>{const s=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===i);return s?e(s,n):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getWorkflowManager().getTransaction().id,amountToOrder:e.getWorkflowManager().getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await B.getShadowGraphqlClient().mutate({mutation:ul,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){var a,n;const e=await B.getShadowGraphqlClient().mutate({mutation:Al(((a=this.globalPropertyStateManager.getBundleOptions())==null?void 0:a.eagerFetchProducts)??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if((n=e.data)!=null&&n.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const i=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(i),this.globalConfigurationPropertyId=i==null?void 0:i.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const n=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===n.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(n=>({type:"transaction",transactionId:n})),e);if(a.forEach(n=>n.setBundle(this)),a.forEach(n=>n.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const n of a)await this.injectExperienceIntoPreviewService(n)}async updateBundle(){var e;if(!((e=(await B.getShadowGraphqlClient().mutate({mutation:al,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,n])=>({key:a,value:n})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data)!=null&&e.bundleUpdate))throw new Error("Bundle not found!")}async updateTransactionOrder(){await B.getShadowGraphqlClient().mutate({mutation:dl,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async checkConditionalHandlesChanged(t,e){const a=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);if((()=>{if(n.length!==i.length)return!0;for(let o=0;o<n.length;o++)if(n[o].getName()!==i[o].getName())return!0;return!1})()){this.fireEvent("conditional-global-properties-changed",{globalProperties:i});const o=i.filter(l=>!n.includes(l));await Promise.all(o.map(l=>l.applyGlobalState()))}}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await B.getShadowGraphqlClient().mutate({mutation:ml,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await B.getShadowGraphqlClient().mutate({mutation:pl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const uc=v.gql`
|
|
2335
|
+
`;class ea{constructor(t,e,a,n,i,s){var c,d,A;this.workflowExperiences=[],this.eventEmitter=new lc,this.client=t,this.id=e.id,this.name=e.name||"",this.dispatchDate=e.dispatchDate,this.template=e.template||!1,this.quoteId=e.quoteId,this.shareActions=e.bundleShareActions,this.workflowViewerLink=e.workflowViewerLink,this.workflowViewerAmendLink=e.workflowViewerAmendLink,this.ownerId=i,this.metadata=new Map(((c=e.metadata)==null?void 0:c.map(u=>[u.key,u.value]))||[]),this.completed=e.completed??!1,this.productCollection=e.productCollection,this.bundleStateManager=new nc(e.bundleStateData);const o=(d=this.productCollection)==null?void 0:d.globalPropertyConfiguration;this.globalConfigurationPropertyId=o==null?void 0:o.id,this.globalPropertyStateManager=new ac(this.id,this.ownerId,o,this.onGlobalPropertiesChanged.bind(this),s),this.globalPropertyHandleService=new Zl(this),this.setPreviewService(a);const l=new Promise((u,h)=>{if(s!=null&&s.readonly){u([]);return}console.log("Setting default global variants.");const g=this.globalPropertyStateManager.getGlobalPropertyState();g?this.globalPropertyHandleService.getHandles().then(m=>{const p=m.map(f=>{if(f.getType()===V.ColorOption||f.getType()===V.Option){const C=f;if(!g.aspects.find(S=>S.name===C.getName()))return C.initDefaultVariant()}});Promise.all(p).then(u).catch(h)}):(console.log("Attempted to set global default variant before state was initialized."),u([]))});this.initializationPromise=Promise.all([this.loadExistingWorkflowExperiences(((A=e.transactions)==null?void 0:A.map(u=>u.id))||[],{...n,bundleOwnerId:i}),this.globalPropertyStateManager.getInitializationPromise()]).then(()=>l),this.initializationPromise.catch(u=>{console.error(`Bundle initialization failed: ${u}`)}),this.initializationPromise.then(()=>{this.getGlobalProperties().then(u=>this.checkMandatoryHandlesChanged([],u))})}getTemplate(){return this.template}async generateQuoteId(){var a,n;const e=(n=(a=(await B.getShadowGraphqlClient().mutate({mutation:Ac,variables:{id:this.id},context:{bundleOwnerId:this.ownerId}})).data)==null?void 0:a.bundleGenerateQuoteId)==null?void 0:n.quoteId;return this.quoteId=e,e||""}async attachAddress(t,e,a,n,i,s){await B.getShadowGraphqlClient().mutate({mutation:cc,variables:{bundleId:this.id,streetAddress:t||void 0,apartment:e||void 0,city:a||void 0,country:n||void 0,state:i||void 0,postCode:s||void 0},context:{bundleOwnerId:this.ownerId}})}async attachOrganization(t){await B.getShadowGraphqlClient().mutate({mutation:dc,variables:{bundleId:this.id,organizationName:t},context:{bundleOwnerId:this.ownerId}})}setBundleOptions(t){this.globalPropertyStateManager.setBundleOptions(t)}getInitializationPromise(){return this.initializationPromise}addEventListener(t,e){this.eventEmitter.on(t,e)}removeEventListener(t,e){this.eventEmitter.off(t,e)}getClient(){return this.client}getId(){return this.id}getName(){return this.name}getQuoteId(){return this.quoteId}setName(t){return this.name=t,this.updateBundle()}getDispatchDate(){return this.dispatchDate}setDispatchDate(t){return this.dispatchDate=t,this.updateBundle()}getPurchaseOrder(){return this.purchaseOrder}setPurchaseOrder(t){return this.purchaseOrder=t,this.updateBundle()}getMetadata(){return new Map(this.metadata)}setMetadata(t){return this.metadata=new Map(t),this.updateBundle()}setNameAndMetadata(t,e){return this.name=t,this.metadata=new Map(e),this.updateBundle()}hasGlobalProperties(){var t;return!!((t=this.productCollection)!=null&&t.globalPropertyConfiguration)}getGlobalPropertyConfiguration(){var t;return(t=this.productCollection)==null?void 0:t.globalPropertyConfiguration}async getGlobalProperties(){return this.globalPropertyHandleService.applyConditionsFromState(await this.globalPropertyHandleService.getHandles(),this.getGlobalPropertyStateManager().getGlobalPropertyState())}async applyGlobalPropertyState(t){var a;const e=await this.globalPropertyHandleService.getHandles();for(const n of t.aspects){const i=n==null?void 0:n.name;this.getGlobalPropertyStateManager().setAspect(i,n.value)}for(const n of t.aspects){const i=n==null?void 0:n.name,s=e.find(o=>o.getName()===i);if(s)switch(n.type){case V.FileUpload:{const o=s,l=await Ie([n.value]);l.length>0&&await o.selectImage(l[0]);const c=(a=n.storage)==null?void 0:a.colors;if(c){const d=Object.fromEntries(c.map(A=>[A.key,{browserValue:A.browserValue,pmsValue:A.pmsValue}])??[]);await o.changeColors(d)}break}case V.ColorOption:{const o=s;if(n.type===V.ColorOption){const c=o.getAllVariants().find(d=>d.getId()===n.value);c&&await o.selectVariant(c)}else o.setCustomColor(n.value);break}case V.Option:{const o=s,c=o.getAllVariants().find(d=>d.getId()===n.value);c&&await o.selectVariant(c);break}case V.Text:{await s.setText(n.value);break}}}}getGlobalPropertyStateManager(){return this.globalPropertyStateManager}async getGlobalPropertyTotalSubunits(){return(await this.globalPropertyHandleService.getHandles()).filter(a=>a.getType()===V.Option).map(a=>{var n;return((n=a.getCurrentVariant())==null?void 0:n.getPrice())||0}).reduce((a,n)=>a+n,0)}getTotalSubunits(){return this.workflowExperiences.map(t=>t.getTotalPriceSubunits()).reduce((t,e)=>t+e,0)}getProductCollection(){return this.productCollection?new Ga(this.productCollection):void 0}async initializeAdditionalRequiredColorChannels(t){var e,a,n,i;for(const s of t.getStepsByType(I.Illustration)){const o=s.getGlobalPropertyAspects(this.globalConfigurationPropertyId||"");for(const l of o){const c=(e=this.getGlobalPropertyConfiguration())==null?void 0:e.aspects.find(d=>d.name===l);if(c&&c.type===V.ColorOption){const d=(a=s.getCurrentVariant())==null?void 0:a.getAssetResource(),A=((n=d==null?void 0:d.assetConfiguration)==null?void 0:n.channelNumbers)||[],u=((i=d==null?void 0:d.assetConfiguration)==null?void 0:i.defaultColorVariants)||[],h=ec(this.getWorkflowExperiences(),this.globalConfigurationPropertyId||"",l),g=[...new Set(A.map(p=>p.number))];if(g.length>h)for(const p of g){const f=this.getGlobalPropertyStateManager(),C=u.find(w=>w.channelNumber===p);C&&await f.setAspect(l,C.variant.id||"",void 0,C.channelNumber)}}}}}async addWorkflowExperience(t){await this.initializeAdditionalRequiredColorChannels(t),t.setBundle(this),await this.appendWorkflowExperience(t),await this.injectExperienceIntoPreviewService(t),await t.getWorkflowManager().getInitializationPromise();const e=await this.getGlobalProperties();for(const a of e)await a.applyGlobalState([t]);this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async addWorkflowExperiences(t){for(const o of t)await this.initializeAdditionalRequiredColorChannels(o);const e=t.map(o=>o.getWorkflowManager().getTransaction().id),a=e.map(o=>this.workflowExperiences.find(l=>l.getWorkflowManager().getTransaction().id===o));if(a.some(o=>!!o))throw new Error("Unable to add transaction to bundle - Already Exists: "+a.filter(o=>!!o).map(o=>o==null?void 0:o.getWorkflowManager().getTransaction().id).join(", "));const n=N.getMap("transactionOwnerIds")||new Map,i=e.map(o=>n.get(o));await B.getShadowGraphqlClient().mutate({mutation:rl,variables:{id:this.id,transactionIds:e,transactionOwnerIds:i},context:{bundleOwnerId:this.ownerId}}).catch(o=>{console.error(o)}),this.workflowExperiences.push(...t);const s=async()=>{for(const l of t)l.setBundle(this),await this.injectExperienceIntoPreviewService(l);await Promise.all(t.map(l=>l.getWorkflowManager().getInitializationPromise()));const o=await this.getGlobalProperties();for(const l of o)await l.applyGlobalState(t)};await Promise.all([this.updateTransactionOrder(),s()]),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()),this.fireEvent("workflow-experience-added",{workflowExperiences:this.workflowExperiences})}async appendWorkflowExperience(t,e=!0){const a=t.getWorkflowManager().getTransaction().id;if(this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===a))throw new Error("Unable to add transaction to bundle - Already Exists!");const s=(N.getMap("transactionOwnerIds")||new Map).get(a);await B.getShadowGraphqlClient().mutate({mutation:nl,variables:{id:this.id,transactionId:a},context:{bundleOwnerId:this.ownerId,transactionOwnerId:s}}),e&&(this.workflowExperiences.push(t),this.workflowExperiences.forEach(o=>o.checkForPriceBreakChanges()))}async removeWorkflowExperience(t){const e=this.workflowExperiences.indexOf(t);await this.removeTransaction(e,this.workflowExperiences[e].getWorkflowManager().getTransaction()),this.fireEvent("workflow-experience-added",{workflowExperiences:[t]})}async removeWorkflowExperiences(t){await this.removeTransactions(t.map(e=>e.getWorkflowManager().getTransaction()))}async removeWorkflowExperienceByTransaction(t){const e=this.workflowExperiences.findIndex(a=>a.getWorkflowManager().getTransaction().id===t.id);await this.removeTransaction(e,t)}async removeWorkflowExperiencesByTransactions(t){await this.removeTransactions(t)}async removeTransaction(t,e,a=!0){if(t>-1){const n=this.workflowExperiences.find(i=>i.getWorkflowManager().getTransaction().id===e.id);if(n.setBundle(void 0),this.previewService&&n.getWorkflowManager().ejectFromPreviewService(),this.bundleStateManager.removeStateForTransaction(e.id),await B.getShadowGraphqlClient().mutate({mutation:il,variables:{id:this.id,transactionId:e.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([i,s])=>({key:i,value:s})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),a){const i=this.workflowExperiences.splice(t,1);this.workflowExperiences.forEach(s=>s.checkForPriceBreakChanges()),n.checkForPriceBreakChanges(),await this.updateTransactionOrder(),this.fireEvent("workflow-experience-removed",{workflowExperiences:i})}}else throw new Error("Unable to remove workflow experience from bundle - Not Found! - "+e.id)}async removeTransactions(t){const e=t.map(n=>this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id));if(e.some(n=>n===-1))throw new Error("Unable to remove workflow experience from bundle - The following aren't included in the bundle: "+t.filter((n,i)=>e[i]===-1).map(n=>n.id).join(", "));const a=t.map(n=>this.workflowExperiences.splice(this.workflowExperiences.findIndex(i=>i.getWorkflowManager().getTransaction().id===n.id),1)[0]);a.forEach(n=>n.setBundle(void 0)),[...this.workflowExperiences,...a].forEach(n=>n.checkForPriceBreakChanges()),this.previewService&&a.forEach(n=>n.getWorkflowManager().ejectFromPreviewService()),t.forEach(n=>this.bundleStateManager.removeStateForTransaction(n.id)),await B.getShadowGraphqlClient().mutate({mutation:sl,variables:{id:this.id,transactionIds:t.map(n=>n.id),name:this.name,metadata:Array.from(this.metadata.entries()).map(([n,i])=>({key:n,value:i})),bundleStateData:this.bundleStateManager.getSerializedState()},context:{bundleOwnerId:this.ownerId}}),this.fireEvent("workflow-experience-removed",{workflowExperiences:a}),await this.updateTransactionOrder()}async insertWorkflowExperience(t,e){await this.appendWorkflowExperience(t,!1),this.workflowExperiences.splice(e,0,t),await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(t);const a=await this.getGlobalProperties();await Promise.all(a.map(n=>n.applyGlobalState([t])))})()])}async replaceWorkflowExperience(t,e){if(t<0||t>=this.workflowExperiences.length)throw new Error("Unable to replace workflow experience in bundle - Index out of range!");const a=this.workflowExperiences[t];if(a.getWorkflowManager().getTransaction().id===e.getWorkflowManager().getTransaction().id)throw new Error("Unable to replace workflow experience in bundle - Same transaction!");await Promise.all([this.removeTransaction(t,a.getWorkflowManager().getTransaction(),!1),this.appendWorkflowExperience(e,!1)]),this.workflowExperiences[t]=e,await Promise.all([this.updateTransactionOrder(),(async()=>{await this.injectExperienceIntoPreviewService(e);const n=await this.getGlobalProperties();await Promise.all(n.map(i=>i.applyGlobalState([e])))})()])}async swapWorkflowExperiences(t,e){if(t<0||t>=this.workflowExperiences.length||e<0||e>=this.workflowExperiences.length)throw new Error("Unable to swap workflow experiences in bundle - Index out of range!");if(t===e)return;const a=this.workflowExperiences[t];this.workflowExperiences[t]=this.workflowExperiences[e],this.workflowExperiences[e]=a,await this.updateTransactionOrder()}getWorkflowExperiences(){return[...this.workflowExperiences]}async sortWorkflowExperiences(t){this.workflowExperiences=this.workflowExperiences.sort(t),await this.updateTransactionOrder()}getWorkflowExperienceCount(){return this.workflowExperiences.length}async addStakeholder(t,e){var i;const a=await B.getShadowGraphqlClient().mutate({mutation:ol,variables:{id:this.id,details:t,type:e||Zt.Owner},context:{bundleOwnerId:this.ownerId}});if(!((i=a.data)!=null&&i.bundleAddStakeholder))throw new Error("Bundle not found!");const n=a.data.bundleAddStakeholder.bundleStakeholders||[];this.storeStakeholderCustomers(n)}async removeStakeholder(t){var a;if(!((a=(await B.getShadowGraphqlClient().mutate({mutation:ll,variables:{id:this.id,emailAddress:t},context:{bundleOwnerId:this.ownerId}})).data)!=null&&a.bundleRemoveStakeholder))throw new Error("Bundle not found!")}async updateStakeholders(t){var n;const e=await B.getShadowGraphqlClient().mutate({mutation:cl,variables:{id:this.id,input:t},context:{bundleOwnerId:this.ownerId}});if(!((n=e.data)!=null&&n.bundleUpdateStakeholders))throw new Error("Bundle not found!");const a=e.data.bundleUpdateStakeholders.bundleStakeholders||[];this.storeStakeholderCustomers(a)}async getAllStakeholders(){const t=await B.getShadowGraphqlClient().query({query:dn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");const e=t.data.bundles[0].bundleStakeholders||[];return this.storeStakeholderCustomers(e),e}async getCurrentStakeholder(){const t=await B.getShadowGraphqlClient().query({query:dn,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id},context:{bundleOwnerId:this.ownerId}});if(!t.data.bundles||t.data.bundles.length===0)throw new Error("Bundle not found!");return t.data.bundles[0].currentBundleStakeholder}storeStakeholderCustomers(t){t.forEach(e=>{e.customer&&this.client.storeCustomer(e.customer)})}async finish(t,e){if(this.completed)return await B.getShadowGraphqlClient().mutate({mutation:gl,variables:{bundleId:this.id}}),{bundleId:this.id,items:[],bundleOwnerId:this.ownerId};const a=await xl(this.workflowExperiences.map(n=>({workflowManager:n.getWorkflowManager(),workflow:n.getWorkflowManager().getWorkflow(),layouts:n.getWorkflowManager().getLayouts(),getReducerState:()=>n.getCommandContext().getState(),product:n.getWorkflowManager().getProduct(),transaction:n.getWorkflowManager().getTransaction(),workflowSelections:n.getWorkflowManager().getWorkflowSelections(),designName:n.getWorkflowManager().getWorkflow().name,workflowMetadata:n.getWorkflowManager().getWorkflowMetadata()})),t??(()=>{}),e?(n,i)=>{const s=this.workflowExperiences.find(o=>o.getWorkflowManager().getTransaction().id===i);return s?e(s,n):(console.warn("SpiffCommerce - Bundle create design - Unable to find experience for transaction: "+i),Promise.resolve(void 0))}:void 0);return{bundleId:this.id,items:a,bundleOwnerId:this.ownerId}}async placeOrder(){const t=this.workflowExperiences.map(e=>({transactionId:e.getWorkflowManager().getTransaction().id,amountToOrder:e.getWorkflowManager().getTransaction().quantity||1}));return await this.getClient().placeOrder(t)}getPreviewService(){return this.previewService}async setPreviewService(t){if(this.workflowExperiences&&this.workflowExperiences.length>0&&(this.workflowExperiences.forEach(e=>e.getWorkflowManager().ejectFromPreviewService()),t))for(const e of this.workflowExperiences)await this.injectExperienceIntoPreviewService(e);t&&t.registerModelLoadEventListener&&t.registerModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService&&this.previewService!==t&&this.previewService.unregisterModelLoadEventListener&&this.previewService.unregisterModelLoadEventListener(this.onModelLoadEvent.bind(this)),this.previewService=t}updateWorkflowExperienceTransform(t,e,a){return this.bundleStateManager.updateWorkflowExperienceTransform(t,e,a),this.updateBundle()}activateWorkflowExperienceTransform(t,e){return this.bundleStateManager.activateWorkflowExperienceTransform(t,e),this.updateBundle()}async assignGlobalPropertyConfiguration(t){await B.getShadowGraphqlClient().mutate({mutation:ul,variables:{bundleId:this.id,globalPropertyConfigurationId:t},context:{bundleOwnerId:this.ownerId}}),this.globalConfigurationPropertyId=t}async assignProductCollection(t){var a,n;const e=await B.getShadowGraphqlClient().mutate({mutation:Al(((a=this.globalPropertyStateManager.getBundleOptions())==null?void 0:a.eagerFetchProducts)??!1),variables:{id:this.id,productCollectionId:t??""},context:{bundleOwnerId:this.ownerId}});if((n=e.data)!=null&&n.bundleAssignProductCollection.productCollection){this.productCollection=e.data.bundleAssignProductCollection.productCollection;const i=e.data.bundleAssignProductCollection.productCollection.globalPropertyConfiguration;this.globalPropertyStateManager.setConfiguration(i),this.globalConfigurationPropertyId=i==null?void 0:i.id}}onModelLoadEvent(t){t.eventType==="unload"||!t.modelContainer||(t.modelContainer.registerMaterialSelectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!0)),t.modelContainer.registerMaterialDeselectedCallback(()=>this.onModelSelectedEvent(t.modelContainer,!1)))}onModelSelectedEvent(t,e){if(t&&t.metadata&&t.metadata instanceof Map&&t.metadata.has("workflowManager")){const n=t.metadata.get("workflowManager").getTransaction(),i=this.workflowExperiences.find(s=>s.getWorkflowManager().getTransaction().id===n.id);i&&this.fireEvent(e?"workflow-experience-hover-enter":"workflow-experience-hover-exit",{workflowExperience:i})}}async injectExperienceIntoPreviewService(t){if(this.previewService){const e=t.getWorkflowManager().injectIntoPreviewService(this.previewService);try{this.bundleStateManager.applyStateToWorkflowExperience(t)}catch(a){console.error(`Unable to apply state to workflow experience: ${a}`)}await e}}async loadExistingWorkflowExperiences(t,e){if(t.length===0)return;const a=await this.client.getWorkflowExperiences(t.map(n=>({type:"transaction",transactionId:n})),e);if(a.forEach(n=>n.setBundle(this)),a.forEach(n=>n.checkForPriceBreakChanges()),this.workflowExperiences=a,this.previewService)for(const n of a)await this.injectExperienceIntoPreviewService(n)}async updateBundle(){var e;if(!((e=(await B.getShadowGraphqlClient().mutate({mutation:al,variables:{id:this.id,name:this.name,metadata:Array.from(this.metadata.entries()).map(([a,n])=>({key:a,value:n})),bundleStateData:this.bundleStateManager.getSerializedState(),dispatchDate:this.dispatchDate,purchaseOrder:this.purchaseOrder},context:{bundleOwnerId:this.ownerId}})).data)!=null&&e.bundleUpdate))throw new Error("Bundle not found!")}async updateTransactionOrder(){await B.getShadowGraphqlClient().mutate({mutation:dl,variables:{id:this.id,transactionIds:this.workflowExperiences.map(t=>t.getWorkflowManager().getTransaction().id)},context:{bundleOwnerId:this.ownerId}})}async onGlobalPropertiesChanged(t,e){const a=await this.globalPropertyHandleService.getHandles(),n=this.globalPropertyHandleService.applyConditionsFromState(a,t),i=this.globalPropertyHandleService.applyConditionsFromState(a,e);this.checkConditionalHandlesChanged(n,i),this.checkMandatoryHandlesChanged(n,i);const s=i.filter(o=>!n.includes(o));await Promise.all(s.map(o=>o.applyGlobalState()))}checkConditionalHandlesChanged(t,e){(()=>{if(t.length!==e.length)return!0;for(let n=0;n<t.length;n++)if(t[n].getName()!==e[n].getName())return!0;return!1})()&&this.fireEvent("conditional-global-properties-changed",{globalProperties:e})}checkMandatoryHandlesChanged(t,e){const a=[],n=[],i=[];for(const s of e)if(s.isMandatory()){const o=t.find(c=>c.getName()==s.getName()),l=s.isMandatoryFulfilled();l?n.push(s):i.push(s),(!o||o.isMandatoryFulfilled()!==l)&&a.push(s)}a.length>0&&this.fireEvent("global-properties-mandatory-changed",{changed:a,completed:n,remaining:i})}fireEvent(t,e){this.eventEmitter.emit(t,e)}getShareActions(){return this.shareActions}getWorkflowViewerLink(){return this.workflowViewerLink}getWorkflowViewerAmendLink(){return this.workflowViewerAmendLink}async approve(t,e){await B.getShadowGraphqlClient().mutate({mutation:ml,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}async reject(t,e){await B.getShadowGraphqlClient().mutate({mutation:pl,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:this.id,note:t,stakeholderId:e}})}getQuoteCompleteMessage(){return{bundleId:this.id,bundleOwnerId:this.ownerId,quoteId:this.quoteId||""}}}const uc=v.gql`
|
|
2332
2336
|
mutation processFlowCreate($processFlowId: String!, $inputs: [String]!) {
|
|
2333
2337
|
processExecutionCreate(processFlowId: $processFlowId, inputs: $inputs) {
|
|
2334
2338
|
id
|
|
@@ -2451,7 +2455,7 @@
|
|
|
2451
2455
|
}
|
|
2452
2456
|
}
|
|
2453
2457
|
}
|
|
2454
|
-
`;class Cc{constructor(t,e=B.getShadowGraphqlClient.bind(B)){this.options=t,this.client=e}query(t){var a,n;const e=(a=this.options)!=null&&a.onQuery?(n=this.options)==null?void 0:n.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){var a,n;const e=(a=this.options)!=null&&a.onMutate?(n=this.options)==null?void 0:n.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class wc{init(t,e,a){this.cognitoClient=new pe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){var a;const e=await((a=this.cognitoClient)==null?void 0:a.send(new pe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}})));(e==null?void 0:e.ChallengeName)==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){var i;const n=await((i=this.cognitoClient)==null?void 0:i.send(new pe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}})));return(n==null?void 0:n.ChallengeName)==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}async refreshTokens(){var a;const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await((a=this.cognitoClient)==null?void 0:a.send(new pe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}})))}}const Wt=new wc;class Gr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Ai(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ka.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t,a=Ka.code(e);if((a==null?void 0:a.code)==="CLP")return"USD0,0"}}const un=new Gr;class qr{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,un.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,un.getPrecisionForCurrency(e))}}const yc=async(r,t)=>{var n;const e=await B.getShadowGraphqlClient().query({query:Es(((n=t==null?void 0:t.assets)==null?void 0:n.metadata)||!1),errorPolicy:"all",variables:{ids:r}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.steps.forEach(s=>{var o,l,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((l=s.option.defaultVariant)!=null&&l.asset&&U.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&U.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(d=>{d.asset&&U.cacheAsset(d.asset),d.thumbnail&&U.cacheAsset(d.thumbnail),d.material&&U.cacheMaterial(d.material)}),Ot.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},Sc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},ja=async(r,t)=>{const e=r.map(o=>Ot.get({id:o,options:t})),a=r.filter((o,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=yc(a,t),i=a.map(o=>Ot.set({id:o,options:t},Sc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},vc=async(r,t)=>(await ja([r],t))[0],Ec=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:Q(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),bc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):Ec(t.panels)};class Bc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return B.getShadowGraphqlClient().mutate({...e,mutation:As})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Di(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 29.1.2"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Rn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!xi())throw new Error("Application key required to use Flow Service.");return new Lr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await B.getShadowGraphqlClient().query({query:ks,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:s,rateTo:o}=i.data.currencyConversion;return new qr(s,o,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Wr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(a){return console.error(a),!1}}async authenticateBundleFromLocalStorage(t){var n,i;const e=N.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const a=N.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const s=a.get(t);if((N.getMap("partnerCustomerIds")||new Map).get(s)&&await this.reloadLoggedInCustomer()){const d=(i=(n=this.customer)==null?void 0:n.bundleStakeholders)==null?void 0:i.find(A=>{var u;return((u=A.bundle)==null?void 0:u.id)===t});if(d)return Promise.resolve({success:!0,stakeholderType:d.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var d,A,u,h,g,m;const e=B.getShadowGraphqlClient(),a=await e.query({query:bs,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const n=a.data.transactions[0];if(!((A=(d=n.product)==null?void 0:d.partner)==null?void 0:A.id))throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=N.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const o=N.getMap("transactionCustomerIds");if(o!=null&&o.has(t)&&o.get(t)&&await this.reloadLoggedInCustomer()){const C=((h=(u=this.customer)==null?void 0:u.bundleStakeholders)==null?void 0:h.find(w=>{var S,y;return(y=(S=w.bundle)==null?void 0:S.transactions)==null?void 0:y.some(E=>E.id===t)}))||((m=(g=this.customer)==null?void 0:g.stakeholders)==null?void 0:m.find(w=>{var S;return((S=w.transaction)==null?void 0:S.id)===t}));if(C)return Promise.resolve({success:!0,stakeholderType:C.type})}const c=(await e.query({query:Bs,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=N.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),N.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await B.getShadowGraphqlClient().query({query:Se,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var a,n;const e=(n=(a=this.customer)==null?void 0:a.stakeholders)==null?void 0:n.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=B.getShadowGraphqlClient(),n=(await e.query({query:Se,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:mc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!l)throw new Error("Unable to create customer.");return this.storeCustomer(l),this.customer=l,{customer:l,isAuthenticated:!1}}this.storeCustomer(n);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),i=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l!=null&&l.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const o=(await B.getShadowGraphqlClient().query({query:Se,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return o.id?(this.customer=o,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await B.getShadowGraphqlClient().mutate({mutation:pc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n!=null&&n.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const s=(await B.getShadowGraphqlClient().query({query:Se,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!s.id)throw new Error("Failed to get customer.");return this.customer=s,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,i=!(a!=null&&a.AccessToken)||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||i){const s=await Wt.refreshTokens();if(s!=null&&s.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await B.getShadowGraphqlClient().query({query:fc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){var c,d,A,u,h;const i=(A=(await B.getShadowGraphqlClient().mutate({mutation:tl(((d=(c=a==null?void 0:a.graphql)==null?void 0:c.productCollection)==null?void 0:d.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((g,m)=>({key:g[0],value:g[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:A.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=N.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),N.setMap("bundlePartnerIds",s);const o=N.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),N.setMap("bundleOwnerIds",o);const l=new ea(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(h=(u=a==null?void 0:a.graphql)==null?void 0:u.productCollection)==null?void 0:h.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){var g,m,p,f,C,w,S,y,E,b,P;const i=N.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),o={};try{const x=await this.loggedInBearerToken();o.Authorization=`Bearer ${x}`}catch{const M=((g=Object.entries(localStorage).find(([Z,R])=>Z.startsWith("CognitoIdentityServiceProvider")&&Z.endsWith("idToken")))==null?void 0:g[0])||"",T=localStorage.getItem(M);T&&!_t(T)&&(o.Authorization=`Bearer ${T}`)}const l={bundleOwnerId:s,...o,...(m=n==null?void 0:n.graphql)==null?void 0:m.additionalHeaders},c=await B.getShadowGraphqlClient().query({query:Jo(((f=(p=n==null?void 0:n.graphql)==null?void 0:p.productCollection)==null?void 0:f.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!((C=c.data)!=null&&C.bundles)||((w=c.data)==null?void 0:w.bundles.length)===0||!((S=c.data)!=null&&S.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const d=(y=c.data)==null?void 0:y.bundles[0],A=N.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),N.setMap("bundlePartnerIds",A);const u=new ea(this,d,e,a,s,{additionalHeaders:(E=n==null?void 0:n.graphql)==null?void 0:E.additionalHeaders,eagerFetchProducts:(P=(b=n==null?void 0:n.graphql)==null?void 0:b.productCollection)==null?void 0:P.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:n==null?void 0:n.readonly});await u.getInitializationPromise();const h=c.data.globalPropertyState;return h&&u.applyGlobalPropertyState(h),u}async duplicateBundle(t,e,a,n){var u,h,g,m,p,f;const i=(u=N.getMap("bundleOwnerIds"))==null?void 0:u.get(t),s={};try{const C=await this.loggedInBearerToken();s.Authorization=`Bearer ${C}`}catch{const S=((h=Object.entries(localStorage).find(([E,b])=>E.startsWith("CognitoIdentityServiceProvider")&&E.endsWith("idToken")))==null?void 0:h[0])||"",y=localStorage.getItem(S);y&&!_t(y)&&(s.Authorization=`Bearer ${y}`)}const o={bundleOwnerId:i,...s,...(g=n==null?void 0:n.graphql)==null?void 0:g.additionalHeaders},c=(f=(await B.getShadowGraphqlClient().mutate({mutation:el(((p=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:p.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data)==null?void 0:f.bundleDuplicate;if(!(c!=null&&c.id))throw new Error("Unable to duplicate bundle");const d=N.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),N.setMap("bundlePartnerIds",d);const A=N.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),N.setMap("bundleOwnerIds",A),async()=>{var w,S;const C=new ea(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:(S=(w=n==null?void 0:n.graphql)==null?void 0:w.productCollection)==null?void 0:S.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await C.getInitializationPromise(),C}}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await B.getShadowGraphqlClient().query({query:hl(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){var i;if(!this.customer)throw new Error("Customer not authenticated.");const t=await B.getShadowGraphqlClient().query({query:Ko,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=N.getMap("bundlePartnerIds")||new Map;return a.forEach(s=>{var o,l;(o=s.bundle)!=null&&o.id&&((l=s.bundle.partner)!=null&&l.id)&&n.set(s.bundle.id,s.bundle.partner.id)}),N.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new ht("No options provided!");const a=B.getShadowGraphqlClient(),n=async y=>{var x,F,M;if(y.length===0)return[];const E=y.map(T=>T.option.transactionId),b=await a.query({query:ds,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),P=b.data.transactions;if(P.length!==y.length){const T=((F=(x=b.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Not all transactions were found: ${T}`)}return!this.activeIntegration&&((M=P[0].integrationProduct)!=null&&M.integration)&&(this.activeIntegration=Promise.resolve(P[0].integrationProduct.integration)),P.map((T,Z)=>{var R;return{transaction:T,workflowId:T.workflowId,readOnly:((R=y.find(at=>at.option.transactionId===T.id))==null?void 0:R.option.readOnly)??!1,index:y[Z].index}})},i=async y=>{var P,x,F;if(y.length===0)return[];const E=await a.mutate({mutation:cs,variables:{inputs:y.map(M=>({integrationProductId:M.option.type==="integration"?M.option.integrationProductId:void 0,externalIntegrationId:M.option.type==="external"?M.option.externalIntegrationId:void 0,externalProductId:M.option.type==="external"?M.option.externalProductId:void 0,workflowId:M.option.workflowId,designName:M.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),b=(P=E.data)==null?void 0:P.transactionCreateMany;if(!b||b.length===0){const M=((F=(x=E.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Failed to create transactions: ${M}`)}return b.map((M,T)=>({transaction:M,workflowId:M.workflowId,readOnly:!1,index:y[T].index}))},s=t.map((y,E)=>({option:y,index:E})),o=s.filter(y=>y.option.type==="transaction"),l=s.filter(y=>y.option.type==="integration"||y.option.type==="external"),c=Ja(o,10),d=Ja(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(y=>y.workflowId))],h=await ja(u,e),g=new Map(h.map(y=>[y.id,y])),m=N.getMap("transactionOwnerIds")||new Map,p=A.map(async y=>{var at;const{transaction:E,workflowId:b,readOnly:P,index:x}=y,F=g.get(b),M=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const T=m.get(E.id)||void 0,Z=new Cc({onMutate:()=>({context:{transactionOwnerId:T,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:T,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})}),R={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:(at=M==null?void 0:M.workflowConfiguration)==null?void 0:at.singleVariantsRenderable,stateMutationFunc:P?async()=>{throw new z("State mutation is forbidden in read only mode!")}:async tt=>this.updateTransactionState({...tt,context:{transactionOwnerId:T,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),graphQlClient:()=>Z,readOnly:P,workflow:F,isReloadedTransaction:M.type==="transaction"};if(!P&&M.workflowState){const tt=JSON.parse(M.workflowState);R.layouts=Object.values(tt.layouts||{}).map(Ut=>Ut.layout),await or(tt),R.reloadedState=tt}else R.layouts=bc(R.transaction,R.workflow);return R.renderableContextService=new jl(R.layouts),R.delayWorkflowStateSync=!0,{experienceOptions:R,index:x,options:M}}),f=await Promise.all(p);N.setMap("transactionOwnerIds",m);const w=f.sort((y,E)=>y.index-E.index).map(async y=>{const{experienceOptions:E,options:b}=y,P=new Mr(this,E);return await P.getWorkflowManager().getInitializationPromise(),b.type!=="transaction"&&this.customer&&await P.attachCustomerDetails({email:this.customer.emailAddress}),P}),S=await Promise.all(w);return S.forEach(y=>y.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),S}storeCustomer(t){const e=N.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),N.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){var s,o;const i=(s=(await B.getShadowGraphqlClient().query({query:ms(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProducts;if(!i||i.length===0||!((o=i[0])!=null&&o.id))throw new Error("Integration product not found.");return new wa(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await B.getShadowGraphqlClient().query({query:ps(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:o.integrationProductFromExternalIds;if(!(s!=null&&s.id))throw new Error("Integration product not found.");return new wa(s)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(N.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await B.getShadowGraphqlClient().query({query:gs,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await B.getShadowGraphqlClient().mutate({mutation:Fs,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const Wr=async(r,t)=>(await B.getShadowGraphqlClient().query({query:Ps,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,Ic=async r=>{const e=await B.getShadowGraphqlClient().query({query:hs,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Pc=async(r,t)=>{var a;return(a=(await B.getShadowGraphqlClient().query({query:Is,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},Dc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:xs,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},xc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Ds,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function jr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const o=r,l=Math.max(t.width/e.width,t.height/e.height);o.zoom=Math.max(l,r.zoom);const c=e.width*o.zoom,d=e.height*o.zoom;return o.x=ve(r.x,t.width-c,0),o.y=ve(r.y,t.height-d,0),o}const s=r;return s.x=ve(s.x,-n,t.width),s.y=ve(s.y,-i,t.height),s}function ve(r,t,e){return Math.min(Math.max(r,t),e)}class Hr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=En(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let s=0;s<n.currentFrameSources.length;s++){const o=n.currentFrameSources[s],l=await ue(o),c=this.frameData?this.frameData[s]:void 0;vn(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[s]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Ft.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=Ue(this.imageData.svg,this.imageData.colors||{},!1);return Oe(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((s,o)=>{const l=(e[o]-this.offsets[o].x)/this.offsets[o].zoom,c=(a[o]-this.offsets[o].y)/this.offsets[o].zoom,d=e[o]-l*t[o],A=a[o]-c*t[o];return{x:d,y:A,zoom:this.imageData.width*t[o]/this.imageData.width}});this.updateOffsets(i,n),this.onZoomChangeListeners.forEach(s=>s(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new z("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(t[o].x===s.x&&t[o].y===s.y&&t[o].zoom===s.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=jr(t[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,i){if(!a||a.length===0||a.some(o=>!o))throw new z("Frame data not set. This is a bug");if(!this.workflowManager)throw new z("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,l)=>{s(new $([new po(o,e,t[l]),new fo(o,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=ka(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Fc{updateRecipient(t,e,a,n,i,s,o,l,c,d){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Yr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(Yr||{});class Jr extends rt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Hr(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ut.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){var n;if(await ut.selectImage(this.step,t,this.manager,a),e){const i=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Me.BackgroundRemover)}async canRemoveBackground(){var t,e,a,n;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((n=(a=this.frameService)==null?void 0:a.getImageData())!=null&&n.svg)}async removeBackgroundFromImageSelection(t=!0){var i;if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await U.removeBackgroundFromAsset(e);t&&await ut.selectImage(this.step,a,this.manager,!1);const n=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ut.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ut.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ut.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){var e,a;const t=(a=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:a.originalAssetKey;if(t)return U.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){var e,a;const t=(a=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:a.backgroundRemovedAssetKey;if(t)return U.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var n;const e=((n=this.getFrameStepStorage())==null?void 0:n.framePatternData)||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const kc=v.gql`
|
|
2458
|
+
`;class Cc{constructor(t,e=B.getShadowGraphqlClient.bind(B)){this.options=t,this.client=e}query(t){var a,n;const e=(a=this.options)!=null&&a.onQuery?(n=this.options)==null?void 0:n.onQuery(t):{};return this.client().query({...e,...t,context:{...e.context??{},...t.context??{}}})}mutate(t){var a,n;const e=(a=this.options)!=null&&a.onMutate?(n=this.options)==null?void 0:n.onMutate(t):{};return this.client().mutate({...e,...t,context:{...e.context??{},...t.context??{}}})}}class wc{init(t,e,a){this.cognitoClient=new pe.CognitoIdentityProviderClient({region:e}),this.spiffRegion=t,this.userPoolClientId=a}async generateCode(t){var a;const e=await((a=this.cognitoClient)==null?void 0:a.send(new pe.InitiateAuthCommand({AuthFlow:"CUSTOM_AUTH",ClientId:this.userPoolClientId,AuthParameters:{USERNAME:t}})));(e==null?void 0:e.ChallengeName)==="CUSTOM_CHALLENGE"&&(this.challengeSession=e.Session)}async verifyCode(t,e,a){var i;const n=await((i=this.cognitoClient)==null?void 0:i.send(new pe.RespondToAuthChallengeCommand({ClientId:this.userPoolClientId,ChallengeName:"CUSTOM_CHALLENGE",Session:this.challengeSession,ChallengeResponses:{USERNAME:t,ANSWER:e},ClientMetadata:{partnerId:a,environment:(this.spiffRegion||"").toLowerCase()}})));return(n==null?void 0:n.ChallengeName)==="CUSTOM_CHALLENGE"&&(this.challengeSession=n.Session),n}async refreshTokens(){var a;const t=localStorage.getItem("cognito-tokens");if(!t)throw new Error("Failed to find existing tokens.");const e=JSON.parse(t);return await((a=this.cognitoClient)==null?void 0:a.send(new pe.InitiateAuthCommand({AuthFlow:"REFRESH_TOKEN_AUTH",ClientId:this.userPoolClientId,AuthParameters:{REFRESH_TOKEN:e.RefreshToken||""}})))}}const Wt=new wc;class Gr{formatCurrencyForDisplay(t,e){const a={amount:e||0,currency:t,precision:this.getPrecisionForCurrency(t)};return Ai(a).toFormat(this.getSpecialFormat(t))}getPrecisionForCurrency(t){const e=t,a=Ka.code(e);return a?a.digits:2}getSpecialFormat(t){const e=t,a=Ka.code(e);if((a==null?void 0:a.code)==="CLP")return"USD0,0"}}const un=new Gr;class qr{constructor(t,e,a,n){this.presentmentCurrency=void 0,this.presentmentCurrency=n,this.partnerCurrency=a,this.rateFrom=t,this.rateTo=e}code(){return this.presentmentCurrency?this.presentmentCurrency:this.partnerCurrency}conversionRequired(){return this.presentmentCurrency!==void 0&&this.code()!==this.partnerCurrency}getConvertedSubunits(t){return this.conversionRequired()?Math.ceil(this.subunits(this.units(t,this.partnerCurrency)/this.rateFrom*this.rateTo,this.code())):t}units(t,e){return t/Math.pow(10,un.getPrecisionForCurrency(e))}subunits(t,e){return t*Math.pow(10,un.getPrecisionForCurrency(e))}}const yc=async(r,t)=>{var n;const e=await B.getShadowGraphqlClient().query({query:Es(((n=t==null?void 0:t.assets)==null?void 0:n.metadata)||!1),errorPolicy:"all",variables:{ids:r}});if(e.error)throw e.error;if(e.errors)throw e.errors.forEach(i=>console.error(i)),new Error("Unable to read workflows. Consult GraphQL errors.");const a=e.data.workflows;if(a===void 0||a.length!==r.length)throw new Error(`Unable to read workflows: ${e.errors??"Length mismatch in response"}`);return a.forEach(i=>{i.steps.forEach(s=>{var o,l,c;delete s.data.__typename,(o=s.option)!=null&&o.id&&((l=s.option.defaultVariant)!=null&&l.asset&&U.cacheAsset(s.option.defaultVariant.asset),s.option.colorProfile&&U.cacheAsset(s.option.colorProfile),(c=s.option.variants)==null||c.forEach(d=>{d.asset&&U.cacheAsset(d.asset),d.thumbnail&&U.cacheAsset(d.thumbnail),d.material&&U.cacheMaterial(d.material)}),Ot.set({id:s.option.id},Promise.resolve(s.option)))}),i.finalizeStepConfig||(i.finalizeStepConfig={}),i.finalizeStepConfig.termsMarkdown=i.finalizeStepConfig.termsMarkdown||i.partner.termsMarkdown}),a},Sc=async(r,t)=>{const a=(await t).find(n=>n.id===r);if(!a)throw new Error(`Workflow not found: ${r}`);return a},ja=async(r,t)=>{const e=r.map(o=>Ot.get({id:o,options:t})),a=r.filter((o,l)=>e[l]===void 0);if(a.length===0)return Promise.all(e);const n=yc(a,t),i=a.map(o=>Ot.set({id:o,options:t},Sc(o,n))),s=e.filter(o=>o!==void 0);return await Promise.all(s.concat(i))},vc=async(r,t)=>(await ja([r],t))[0],Ec=r=>r.sort((t,e)=>t.index-e.index).map(t=>({id:Q(),panelId:t.name,name:t.name,title:t.title,index:t.index,createdAt:new Date,updatedAt:new Date,transparentBackground:t.transparentBackground,height:t.height,width:t.width,previewRegion:t.previewRegion,useEditableArea:t.useEditableArea,editableArea:t.editableArea})),bc=(r,t)=>{const e=r.workflowState,a=e?JSON.parse(e):void 0;return a?Object.values(a.layouts).map(n=>n.layout):Ec(t.panels)};class Bc{constructor(t){this.activeIntegration=void 0,this.updateTransactionState=async e=>{try{return B.getShadowGraphqlClient().mutate({...e,mutation:As})}catch(a){throw console.error(a),new ht("Critical - Unable to synchronize workflow state with server.")}},this.options=t,this.options.applicationKey&&Di(this.options.applicationKey),console.debug("------------------------"),console.debug("Spiff Commerce Core SDK"),console.debug("Version: 29.2.0-beta.decf8a29-8a3c-5a28-b86d-f2ac07bea19f"),console.debug(`Application Key Provided: ${!!this.options.applicationKey}`),console.debug("------------------------")}configure(t){At.setHubUrl(t.hubUrl),At.setServerUrl(t.serverUrl),At.setServicesApiUrl(t.servicesApiUrl),this.marketplaceThemeInstallId=t.marketplaceThemeInstallId,this.marketplaceThemeInstallConfigurationId=t.marketplaceThemeInstallConfigurationId,this.userPoolClientId=t.userPoolClientId,this.userPoolRegion=t.userPoolRegion,this.spiffRegion=t.spiffRegion,t.bearerAuthenticationToken&&Rn(t.bearerAuthenticationToken),this.options.applicationKey&&this.getIntegration(),this.spiffRegion&&this.userPoolRegion&&this.userPoolClientId&&Wt.init(this.spiffRegion,this.userPoolRegion,this.userPoolClientId)}getAssetManager(){return U}getFlowService(){if(!xi())throw new Error("Application key required to use Flow Service.");return new Lr}async getCurrencyContext(t){const a=(await this.getIntegration()).partner.currencyCode,i=await B.getShadowGraphqlClient().query({query:ks,errorPolicy:"all",fetchPolicy:"cache-first",variables:{from:a,to:t}}),{rateFrom:s,rateTo:o}=i.data.currencyConversion;return new qr(s,o,a,t)}async getIntegration(){if(this.activeIntegration)return this.activeIntegration;if(!this.options.applicationKey)throw new Error("Cannot get current Integration without specifying an Application Key.");return this.activeIntegration=Wr(this.options.applicationKey),this.activeIntegration}async canUseAddon(t){var e;try{return((e=(await this.getIntegration()).partner.activeAddons)==null?void 0:e.includes(t))??!1}catch(a){return console.error(a),!1}}async authenticateBundleFromLocalStorage(t){var n,i;const e=N.getMap("bundleOwnerIds");if(e!=null&&e.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const a=N.getMap("bundlePartnerIds")||new Map;if(a.has(t)){const s=a.get(t);if((N.getMap("partnerCustomerIds")||new Map).get(s)&&await this.reloadLoggedInCustomer()){const d=(i=(n=this.customer)==null?void 0:n.bundleStakeholders)==null?void 0:i.find(A=>{var u;return((u=A.bundle)==null?void 0:u.id)===t});if(d)return Promise.resolve({success:!0,stakeholderType:d.type})}}return Promise.resolve({success:!1})}async authenticateTransactionFromLocalStorage(t){var d,A,u,h,g,m;const e=B.getShadowGraphqlClient(),a=await e.query({query:bs,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t}});if(!a.data.transactions||a.data.transactions.length===0)throw new Error(`Transaction not found: ${t}`);const n=a.data.transactions[0];if(!((A=(d=n.product)==null?void 0:d.partner)==null?void 0:A.id))throw new Error(`Unable to read transaction: ${t}`);if(n.isOrdered)return Promise.resolve({success:!1,transactionReadOnly:!0});const s=N.getMap("transactionOwnerIds");if(s!=null&&s.has(t))return Promise.resolve({success:!0,stakeholderType:Zt.Owner});const o=N.getMap("transactionCustomerIds");if(o!=null&&o.has(t)&&o.get(t)&&await this.reloadLoggedInCustomer()){const C=((h=(u=this.customer)==null?void 0:u.bundleStakeholders)==null?void 0:h.find(w=>{var S,y;return(y=(S=w.bundle)==null?void 0:S.transactions)==null?void 0:y.some(E=>E.id===t)}))||((m=(g=this.customer)==null?void 0:g.stakeholders)==null?void 0:m.find(w=>{var S;return((S=w.transaction)==null?void 0:S.id)===t}));if(C)return Promise.resolve({success:!0,stakeholderType:C.type})}const c=(await e.query({query:Bs,errorPolicy:"all",variables:{id:n.workflowId}})).data.workflow;if(!c)throw new Error(`Unable to read workflow: ${n.workflowId}`);return Promise.resolve({success:!1,theme:c.overrideTheme,customLogoLink:n.customLogoLink})}clearCustomer(){this.customer=void 0}clearCustomerForTransaction(t){const e=N.getMap("transactionCustomerIds");e!=null&&e.has(t)&&(e.delete(t),N.setMap("transactionCustomerIds",e))}async customerHasBundleTemplates(t){const n=(await B.getShadowGraphqlClient().query({query:Se,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;return n.id?n.hasBundleTemplates??!1:!1}getStakeholderTypeForTransaction(t){var a,n;const e=(n=(a=this.customer)==null?void 0:a.stakeholders)==null?void 0:n.find(i=>{var s;return((s=i.transaction)==null?void 0:s.id)===t});if(e)return e.type}async getOrCreateCustomer(t){var s;this.customer=void 0;const e=B.getShadowGraphqlClient(),n=(await e.query({query:Se,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!n.id){const l=(s=(await e.mutate({mutation:mc,errorPolicy:"all",fetchPolicy:"no-cache",variables:{details:{emailAddress:t}}})).data)==null?void 0:s.customerCreate;if(!l)throw new Error("Unable to create customer.");return this.storeCustomer(l),this.customer=l,{customer:l,isAuthenticated:!1}}this.storeCustomer(n);const i=await this.reloadLoggedInCustomer();return{customer:this.customer||n,isAuthenticated:i}}getCustomer(){return this.customer}async reloadLoggedInCustomer(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens"),a=localStorage.getItem("cognito-email");if(!t||!e||!a)return!1;const n=JSON.parse(e),i=new Date().getTime()/1e3;if(!n.ExpiresIn||n.ExpiresIn<i-parseInt(t)){const l=await Wt.refreshTokens();if(l!=null&&l.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),n.AccessToken=l.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(n));else return this.logOut(),console.error("Failed to refresh tokens."),!1}const o=(await B.getShadowGraphqlClient().query({query:Se,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:a}})).data.customer;return o.id?(this.customer=o,!0):(console.error("Failed to get customer."),!1)}async generateVerificationCode(t){await B.getShadowGraphqlClient().mutate({mutation:pc,variables:{emailAddress:t}}),await Wt.generateCode(t)}async verifyCode(t,e){const a=(await this.getIntegration()).partner.id||"",n=await Wt.verifyCode(t,e,a);if(n!=null&&n.AuthenticationResult){localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),localStorage.setItem("cognito-tokens",JSON.stringify(n.AuthenticationResult)),localStorage.setItem("cognito-email",t);const s=(await B.getShadowGraphqlClient().query({query:Se,errorPolicy:"all",fetchPolicy:"no-cache",variables:{emailAddress:t}})).data.customer;if(!s.id)throw new Error("Failed to get customer.");return this.customer=s,!0}else throw new Error}async logOut(){localStorage.removeItem("last-refreshed-cognito-tokens"),localStorage.removeItem("cognito-tokens"),localStorage.removeItem("cognito-email"),this.clearCustomer()}async loggedInBearerToken(){const t=localStorage.getItem("last-refreshed-cognito-tokens"),e=localStorage.getItem("cognito-tokens");if(!t||!e)throw new Error("No token data in storage.");const a=JSON.parse(e),n=new Date().getTime()/1e3,i=!(a!=null&&a.AccessToken)||_t(a.AccessToken);if(!a.ExpiresIn||a.ExpiresIn<n-parseInt(t)||i){const s=await Wt.refreshTokens();if(s!=null&&s.AuthenticationResult)localStorage.setItem("last-refreshed-cognito-tokens",`${new Date().getTime()/1e3}`),a.AccessToken=s.AuthenticationResult.AccessToken,localStorage.setItem("cognito-tokens",JSON.stringify(a));else throw this.logOut(),new Error("Failed to refresh tokens.")}if(!a.AccessToken)throw new Error("No bearer token in storage.");return a.AccessToken}async getCustomerMetafields(){var e;if(!((e=this.customer)!=null&&e.id))throw new Error("Customer must be logged in before calling this function.");return(await B.getShadowGraphqlClient().query({query:fc,variables:{id:this.customer.id}})).data.metafields}async getNewBundle(t,e,a){var c,d,A,u,h;const i=(A=(await B.getShadowGraphqlClient().mutate({mutation:tl(((d=(c=a==null?void 0:a.graphql)==null?void 0:c.productCollection)==null?void 0:d.eagerFetchProducts)||!1),variables:{collectionId:t,initialMetadata:e?Object.entries(e).map((g,m)=>({key:g[0],value:g[1]})):void 0,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},fetchPolicy:"no-cache"})).data)==null?void 0:A.bundleCreate;if(!(i!=null&&i.id))throw new Error("Unable to create bundle");const s=N.getMap("bundlePartnerIds")||new Map;s.set(i.id,i.partner.id),N.setMap("bundlePartnerIds",s);const o=N.getMap("bundleOwnerIds")||new Map;o.set(i.id,i.bundleOwnerId),N.setMap("bundleOwnerIds",o);const l=new ea(this,i,void 0,void 0,i.bundleOwnerId,{eagerFetchProducts:(h=(u=a==null?void 0:a.graphql)==null?void 0:u.productCollection)==null?void 0:h.eagerFetchProducts});return await l.getInitializationPromise(),l}async getExistingBundle(t,e,a,n){var g,m,p,f,C,w,S,y,E,b,P;const i=N.getMap("bundleOwnerIds"),s=i==null?void 0:i.get(t),o={};try{const x=await this.loggedInBearerToken();o.Authorization=`Bearer ${x}`}catch{const M=((g=Object.entries(localStorage).find(([Z,R])=>Z.startsWith("CognitoIdentityServiceProvider")&&Z.endsWith("idToken")))==null?void 0:g[0])||"",T=localStorage.getItem(M);T&&!_t(T)&&(o.Authorization=`Bearer ${T}`)}const l={bundleOwnerId:s,...o,...(m=n==null?void 0:n.graphql)==null?void 0:m.additionalHeaders},c=await B.getShadowGraphqlClient().query({query:Jo(((f=(p=n==null?void 0:n.graphql)==null?void 0:p.productCollection)==null?void 0:f.eagerFetchProducts)||!1),variables:{id:t},fetchPolicy:"no-cache",context:{headers:l}});if(!((C=c.data)!=null&&C.bundles)||((w=c.data)==null?void 0:w.bundles.length)===0||!((S=c.data)!=null&&S.bundles[0]))throw new Error(`Unable to find bundle: ${t}`);const d=(y=c.data)==null?void 0:y.bundles[0],A=N.getMap("bundlePartnerIds")||new Map;A.set(d.id,d.partner.id),N.setMap("bundlePartnerIds",A);const u=new ea(this,d,e,a,s,{additionalHeaders:(E=n==null?void 0:n.graphql)==null?void 0:E.additionalHeaders,eagerFetchProducts:(P=(b=n==null?void 0:n.graphql)==null?void 0:b.productCollection)==null?void 0:P.eagerFetchProducts,existingGlobalPropertyState:c.data.globalPropertyState,readonly:n==null?void 0:n.readonly});await u.getInitializationPromise();const h=c.data.globalPropertyState;return h&&u.applyGlobalPropertyState(h),u}async duplicateBundle(t,e,a,n){var u,h,g,m,p,f;const i=(u=N.getMap("bundleOwnerIds"))==null?void 0:u.get(t),s={};try{const C=await this.loggedInBearerToken();s.Authorization=`Bearer ${C}`}catch{const S=((h=Object.entries(localStorage).find(([E,b])=>E.startsWith("CognitoIdentityServiceProvider")&&E.endsWith("idToken")))==null?void 0:h[0])||"",y=localStorage.getItem(S);y&&!_t(y)&&(s.Authorization=`Bearer ${y}`)}const o={bundleOwnerId:i,...s,...(g=n==null?void 0:n.graphql)==null?void 0:g.additionalHeaders},c=(f=(await B.getShadowGraphqlClient().mutate({mutation:el(((p=(m=n==null?void 0:n.graphql)==null?void 0:m.productCollection)==null?void 0:p.eagerFetchProducts)||!1),variables:{id:t,template:e,marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId,duplicateTransactions:a},context:{headers:o},fetchPolicy:"no-cache"})).data)==null?void 0:f.bundleDuplicate;if(!(c!=null&&c.id))throw new Error("Unable to duplicate bundle");const d=N.getMap("bundlePartnerIds")||new Map;d.set(c.id,c.partner.id),N.setMap("bundlePartnerIds",d);const A=N.getMap("bundleOwnerIds")||new Map;return A.set(c.id,c.bundleOwnerId),N.setMap("bundleOwnerIds",A),async()=>{var w,S;const C=new ea(this,c,void 0,void 0,c.bundleOwnerId,{eagerFetchProducts:(S=(w=n==null?void 0:n.graphql)==null?void 0:w.productCollection)==null?void 0:S.eagerFetchProducts,existingGlobalPropertyState:c.globalPropertyState});return await C.getInitializationPromise(),C}}async getBundlesForCustomer(t){var i;if(!((i=this.customer)!=null&&i.id))throw new Error("Customer not authenticated.");const{includeMetadata:e,...a}=t;return(await B.getShadowGraphqlClient().query({query:hl(e??!1),variables:{...a,id:this.customer.id},fetchPolicy:"no-cache"})).data.customerBundlesFeed}async getBundleStakeholders(){var i;if(!this.customer)throw new Error("Customer not authenticated.");const t=await B.getShadowGraphqlClient().query({query:Ko,variables:{id:this.customer.id},fetchPolicy:"no-cache"});if(!((i=t.data)!=null&&i.customers)||t.data.customers.length===0)throw new Error("Unable to find customer.");const a=t.data.customers[0].bundleStakeholders||[],n=N.getMap("bundlePartnerIds")||new Map;return a.forEach(s=>{var o,l;(o=s.bundle)!=null&&o.id&&((l=s.bundle.partner)!=null&&l.id)&&n.set(s.bundle.id,s.bundle.partner.id)}),N.setMap("bundlePartnerIds",n),a}async getWorkflowExperience(t,e){if(!t)throw new Error("getWorkflowExperience has been called without an options object! This is not supported.");const a=await this.getWorkflowExperiences([t],t.graphql),n=a[0];return e&&await n.getWorkflowManager().injectIntoPreviewService(e(n.getWorkflowManager().getWorkflow())),a[0]}async getWorkflowExperiences(t,e){if(t.length===0)throw new ht("No options provided!");const a=B.getShadowGraphqlClient(),n=async y=>{var x,F,M;if(y.length===0)return[];const E=y.map(T=>T.option.transactionId),b=await a.query({query:ds,variables:{ids:E},errorPolicy:"all",fetchPolicy:"no-cache"}),P=b.data.transactions;if(P.length!==y.length){const T=((F=(x=b.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Not all transactions were found: ${T}`)}return!this.activeIntegration&&((M=P[0].integrationProduct)!=null&&M.integration)&&(this.activeIntegration=Promise.resolve(P[0].integrationProduct.integration)),P.map((T,Z)=>{var R;return{transaction:T,workflowId:T.workflowId,readOnly:((R=y.find(at=>at.option.transactionId===T.id))==null?void 0:R.option.readOnly)??!1,index:y[Z].index}})},i=async y=>{var P,x,F;if(y.length===0)return[];const E=await a.mutate({mutation:cs,variables:{inputs:y.map(M=>({integrationProductId:M.option.type==="integration"?M.option.integrationProductId:void 0,externalIntegrationId:M.option.type==="external"?M.option.externalIntegrationId:void 0,externalProductId:M.option.type==="external"?M.option.externalProductId:void 0,workflowId:M.option.workflowId,designName:M.option.designName,claim:!0})),marketplaceThemeInstallId:this.marketplaceThemeInstallId,marketplaceThemeInstallConfigurationId:this.marketplaceThemeInstallConfigurationId},errorPolicy:"all",fetchPolicy:"no-cache"}),b=(P=E.data)==null?void 0:P.transactionCreateMany;if(!b||b.length===0){const M=((F=(x=E.errors)==null?void 0:x[0])==null?void 0:F.message)||"Unknown error";throw new ht(`Failed to create transactions: ${M}`)}return b.map((M,T)=>({transaction:M,workflowId:M.workflowId,readOnly:!1,index:y[T].index}))},s=t.map((y,E)=>({option:y,index:E})),o=s.filter(y=>y.option.type==="transaction"),l=s.filter(y=>y.option.type==="integration"||y.option.type==="external"),c=Ja(o,10),d=Ja(l,10),A=(await Promise.all([...c.map(n),...d.map(i)])).flat(),u=[...new Set(A.map(y=>y.workflowId))],h=await ja(u,e),g=new Map(h.map(y=>[y.id,y])),m=N.getMap("transactionOwnerIds")||new Map,p=A.map(async y=>{var at;const{transaction:E,workflowId:b,readOnly:P,index:x}=y,F=g.get(b),M=t[x];!m.get(E.id)&&E.transactionOwnerId&&m.set(E.id,E.transactionOwnerId);const T=m.get(E.id)||void 0,Z=new Cc({onMutate:()=>({context:{transactionOwnerId:T,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),onQuery:()=>({context:{transactionOwnerId:T,bundleOwnerId:e==null?void 0:e.bundleOwnerId}})}),R={product:E.product,transaction:E,layouts:[],singleVariantsRenderable:(at=M==null?void 0:M.workflowConfiguration)==null?void 0:at.singleVariantsRenderable,stateMutationFunc:P?async()=>{throw new z("State mutation is forbidden in read only mode!")}:async tt=>this.updateTransactionState({...tt,context:{transactionOwnerId:T,bundleOwnerId:e==null?void 0:e.bundleOwnerId}}),graphQlClient:()=>Z,readOnly:P,workflow:F,isReloadedTransaction:M.type==="transaction"};if(!P&&M.workflowState){const tt=JSON.parse(M.workflowState);R.layouts=Object.values(tt.layouts||{}).map(Ut=>Ut.layout),await or(tt),R.reloadedState=tt}else R.layouts=bc(R.transaction,R.workflow);return R.renderableContextService=new jl(R.layouts),R.delayWorkflowStateSync=!0,{experienceOptions:R,index:x,options:M}}),f=await Promise.all(p);N.setMap("transactionOwnerIds",m);const w=f.sort((y,E)=>y.index-E.index).map(async y=>{const{experienceOptions:E,options:b}=y,P=new Mr(this,E);return await P.getWorkflowManager().getInitializationPromise(),b.type!=="transaction"&&this.customer&&await P.attachCustomerDetails({email:this.customer.emailAddress}),P}),S=await Promise.all(w);return S.forEach(y=>y.getWorkflowManager().setWorkflowStateSyncEnabled(!0)),S}storeCustomer(t){const e=N.getMap("partnerCustomerIds")||new Map;e.set(t.partner.id,t.id),N.setMap("partnerCustomerIds",e)}async getIntegrationProductById(t,e){var s,o;const i=(s=(await B.getShadowGraphqlClient().query({query:ms(e),variables:{ids:[t]},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:s.integrationProducts;if(!i||i.length===0||!((o=i[0])!=null&&o.id))throw new Error("Integration product not found.");return new wa(i[0])}async getIntegrationProductFromExternalIds(t,e,a){var o;const s=(o=(await B.getShadowGraphqlClient().query({query:ps(a),variables:{externalProductId:e,externalIntegrationId:t},fetchPolicy:"no-cache",errorPolicy:"all"})).data)==null?void 0:o.integrationProductFromExternalIds;if(!(s!=null&&s.id))throw new Error("Integration product not found.");return new wa(s)}async getIntegrationProduct(t){return t.type==="integration"?this.getIntegrationProductById(t.integrationProductId):this.getIntegrationProductFromExternalIds(t.externalIntegrationId,t.externalProductId)}async getShareActionsForTransaction(t){const a=(N.getMap("transactionOwnerIds")||new Map).get(t)||void 0,n=await B.getShadowGraphqlClient().query({query:gs,errorPolicy:"all",fetchPolicy:"no-cache",variables:{id:t},context:{transactionOwnerId:a}});if(!n.data.transactions||n.data.transactions.length!==1)throw new Error(`Failed to fetch share actions for transaction: ${t}`);return n.data.transactions[0].transactionShareActions}async placeOrder(t){const e=await B.getShadowGraphqlClient().mutate({mutation:Fs,variables:{orderItems:t}});if(e.errors)throw new Error(e.errors[0].message);if(!e.data)throw new Error("Failed to create order: No order data in response.");return{id:e.data.orderCreate.id,internalId:e.data.orderCreate.internalId}}}const Wr=async(r,t)=>(await B.getShadowGraphqlClient().query({query:Ps,errorPolicy:"all",fetchPolicy:"no-cache",context:{headers:{"x-application-key":r}},variables:{themeConfigurationId:t}})).data.currentIntegration,Ic=async r=>{const e=await B.getShadowGraphqlClient().query({query:hs,errorPolicy:"all",fetchPolicy:"network-only",variables:{id:r}});if(e.data.transactions.length!==0)return e.data.transactions[0]},Pc=async(r,t)=>{var a;return(a=(await B.getShadowGraphqlClient().query({query:Is,errorPolicy:"all",variables:{themeConfigurationId:r,themeInstallId:t}})).data)==null?void 0:a.marketplaceThemeInstallConfiguration},Dc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:xs,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.bundles)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration},xc=async r=>{var e,a,n;return(n=(a=(e=(await B.getShadowGraphqlClient().query({query:Ds,errorPolicy:"all",variables:{id:r}})).data)==null?void 0:e.transactions)==null?void 0:a[0])==null?void 0:n.marketplaceThemeInstallConfiguration};function jr(r,t,e,a){const n=e.width*r.zoom,i=e.height*r.zoom;if(a){const o=r,l=Math.max(t.width/e.width,t.height/e.height);o.zoom=Math.max(l,r.zoom);const c=e.width*o.zoom,d=e.height*o.zoom;return o.x=ve(r.x,t.width-c,0),o.y=ve(r.y,t.height-d,0),o}const s=r;return s.x=ve(s.x,-n,t.width),s.y=ve(s.y,-i,t.height),s}function ve(r,t,e){return Math.min(Math.max(r,t),e)}class Hr{constructor(t,e){this.minZoomScale=[.03],this.maxZoomScale=[20],this._debouncedUpdateFrameOffsets=En(this.updateFrameOffsets,200),this.targetElements=[],this.onFrameDataChangeListeners=[],this.onZoomChangeListeners=[],this.forceImageCover=t,this.initialZoom=e,this.thresholdSettings={useThreshold:!1,invertThreshold:!1,threshold:128,thresholdSaturation:.5}}connectWorkflowManager(t,e){e&&t.addStepSpecificStorageCallback(async a=>{if(a){const n=a;if(n.currentFrameSources){let i=!1;for(let s=0;s<n.currentFrameSources.length;s++){const o=n.currentFrameSources[s],l=await ue(o),c=this.frameData?this.frameData[s]:void 0;vn(l,c)||(this.frameData||(this.frameData=new Array(n.currentFrameSources.length)),this.frameData[s]=l,i=!0)}i&&(this.onFrameDataChangeListeners.forEach(s=>s(this.frameData)),this.frameData&&this.imageData&&(this.recalculateOffsets(this.imageData),this.updateOffsets(this.offsets),this.recalculateZoomLimits(this.imageData,this.frameData)))}}},e),this.workflowManager=t,this.stepName=e}setTargetElements(t){this.targetElements=t}getFrameData(){return this.frameData}setFrameData(t){if(!t){this.frameData=void 0;return}t.forEach((e,a)=>{const n=Ft.get(e);n&&(this.frameData||(this.frameData=new Array(t.length)),this.frameData[a]=n)})}getImageData(){return this.imageData}getImageSrc(){if(this.imageData){if(this.imageData.svg){const t=Ue(this.imageData.svg,this.imageData.colors||{},!1);return Oe(t)}return this.imageData.src}}getOffsets(){return this.offsets}setOffsets(t){this.offsets=t}setZoom(t,e,a,n){if(this.imageData&&this.offsets&&this.frameData){(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length));const i=this.frameData.map((s,o)=>{const l=(e[o]-this.offsets[o].x)/this.offsets[o].zoom,c=(a[o]-this.offsets[o].y)/this.offsets[o].zoom,d=e[o]-l*t[o],A=a[o]-c*t[o];return{x:d,y:A,zoom:this.imageData.width*t[o]/this.imageData.width}});this.updateOffsets(i,n),this.onZoomChangeListeners.forEach(s=>s(t))}}setPatternData(t,e=!0){this.imageData=t,t&&this.frameData&&((e||!this.offsets)&&this.recalculateOffsets(t),this.updateOffsets(this.offsets,void 0,!0)),this.imageData&&this.frameData&&this.recalculateZoomLimits(this.imageData,this.frameData)}updateOffsets(t,e,a){const n=this.imageData;if(!n||!this.frameData)return;if(this.frameData.length!==t.length)throw new z("Frame data and offsets are not the same length. This is a bug. Please report it.");if(!this.offsets.some((s,o)=>!(t[o].x===s.x&&t[o].y===s.y&&t[o].zoom===s.zoom))&&!a){e&&e();return}(!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((s,o)=>{this.offsets[o]=jr(t[o],s,this.imageData,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,n,this.frameData,this.thresholdSettings,e)}getThresholdSettings(){return this.thresholdSettings}setThresholdSettings(t){this.thresholdSettings=t,this.imageData&&this.frameData&&this._debouncedUpdateFrameOffsets(this.offsets,this.imageData,this.frameData,t)}onFrameDataChanged(t){t(this.frameData),this.onFrameDataChangeListeners.push(t)}onZoom(t){this.onZoomChangeListeners.push(t)}updateFrameOffsets(t,e,a,n,i){if(!a||a.length===0||a.some(o=>!o))throw new z("Frame data not set. This is a bug");if(!this.workflowManager)throw new z("No workflow manager set, cannot update offsets.");const s=this.workflowManager.getCommandDispatcher();this.targetElements.forEach((o,l)=>{s(new $([new po(o,e,t[l]),new fo(o,n.useThreshold,n.invertThreshold,n.threshold,n.thresholdSaturation)]))}),this.stepName&&this.workflowManager.updateStorage(this.stepName,{frameOffsetsList:t}),i&&i()}recalculateZoomLimits(t,e){(this.minZoomScale.length!==e.length||this.maxZoomScale.length!==e.length)&&(this.minZoomScale=new Array(e.length),this.maxZoomScale=new Array(e.length)),e.forEach((a,n)=>{const i=Math.max(a.width/t.width,a.height/t.height);this.forceImageCover?(this.minZoomScale[n]=i,this.maxZoomScale[n]=i*2.5):(this.minZoomScale[n]=i/10,this.maxZoomScale[n]=i*2.5)})}recalculateOffsets(t){this.frameData&&((!this.offsets||this.offsets.length!==this.frameData.length)&&(this.offsets=new Array(this.frameData.length)),this.frameData.forEach((e,a)=>{this.offsets[a]=ka(t,e,this.initialZoom&&!this.forceImageCover?{scale:this.initialZoom}:void 0,this.forceImageCover)}),this._debouncedUpdateFrameOffsets(this.offsets,t,this.frameData,this.thresholdSettings))}}class Fc{updateRecipient(t,e,a,n,i,s,o,l,c,d){throw new Error("Method not implemented.")}approveTransaction(t){throw new Error("Method not implemented.")}rejectTransaction(t){throw new Error("Method not implemented.")}getClient(){return this.client??{}}getWorkflowExperience(){return{}}setClient(t){this.client=t}getInitializationPromise(){return Promise.resolve()}isInitialized(){return!0}getInformationResults(){return[]}async reset(){}updateStateWithServer(t){}async outstandingRequestsPromise(){}async updateStateWithServerImmediate(t){}addPoller(t){}addConfirmCallback(t){}addEditedCallback(t){}addElementsCallback(t){}addInformationResultCallback(t){}addInitCallback(t){}addMakingAdjustmentsCallback(t){}addMandatoryCallback(t){}addMetadataCallback(t){}addSelectionCallback(t){}addStepSpecificStorageCallback(t,e){}addStorageCallback(t){}getCommandDispatcher(){return t=>{}}getLayouts(){return[]}getLayoutPreviewService(){return{getAll:()=>new Map}}getPreviewService(){}getModelContainer(){}getProfanities(){return[]}getRegionElements(t){return[]}getSerializedStep(t,e){}getStepSpecificServices(t){}getTransaction(){return{id:""}}getTransactionCustomer(){}setTransactionCustomer(){}setTransactionCustomerDetails(){}getWorkflow(){return{id:"",name:"",panels:[],steps:[],showModelOnFinishStep:!1,allowProofDownload:!1,introduction:"",stepGroups:[]}}markStepsAsInitialised(t){}markUpdateCompleted(t){}markUpdatePending(){return"123"}getWorkflowSelections(){return{}}getStepSelections(){return{}}setCurrentAdjustingStepId(t){}setEditedStatus(t,e){}setInformationResults(t){}setMandatoryFulfilled(t,e){}async setSelectionsAndElements(t,e,a){}toggleDesignConfirmed(){}updateMetadata(t,e){}async updateStorage(t,e){}injectIntoPreviewService(t){return Promise.resolve()}ejectFromPreviewService(){}setWorkflowStateSyncEnabled(t){}async updateTransactionShareActions(){}addValidationCallback(t){}setStepError(t,e,a){}getStepErrors(t){}getValidationErrors(){return{steps:new Map}}async updateTransactionStakeholders(){}getStepTags(t){return[]}}var Yr=(r=>(r.SelectFrame="SelectFrame",r.SelectImage="SelectImage",r.Position="Position",r))(Yr||{});class Jr extends rt{constructor(t,e,a){super(t,e,a);const n=e.data;this.frameService=new Hr(n.forceImageCover,n.initialZoomLevel),this.frameService.connectWorkflowManager(t,e.stepName)}selectVariant(t){const e=this.manager.getRegionElements(this.step.stepName);return ut.selectVariant(this.step,t.getResource(),e,this.manager,a=>this.setUpdateState(a))}onFrameDataChanged(t){this.frameService&&this.frameService.onFrameDataChanged(e=>{e&&t(e)})}async selectImage(t,e=!0,a=!0){var n;if(await ut.selectImage(this.step,t,this.manager,a),e){const i=((n=this.manager.getStepStorage(this.step.stepName))==null?void 0:n.framePatternData)||{};this.manager.updateStorage(this.step.stepName,{framePatternData:{...i,originalAssetKey:t.key,backgroundRemovedAssetKey:void 0,useOriginalAsset:void 0}})}}async canUseBackgroundRemover(){return this.manager.getClient().canUseAddon(Me.BackgroundRemover)}async canRemoveBackground(){var t,e,a,n;return await this.canUseBackgroundRemover()&&this.hasOriginalImageSelection()&&!!((e=(t=this.frameService)==null?void 0:t.getImageData())!=null&&e.src)&&!((n=(a=this.frameService)==null?void 0:a.getImageData())!=null&&n.svg)}async removeBackgroundFromImageSelection(t=!0){var i;if(!await this.canUseBackgroundRemover())throw new Error("The current Integration does not have access to the Background Remover. Please call canUseBackgroundRemover to ensure you disable this feature when appropriate.");const e=await this.getOriginalImageSelection();if(!e)throw new Error("You must supply an image selection before attempting to remove the background.");const a=await U.removeBackgroundFromAsset(e);t&&await ut.selectImage(this.step,a,this.manager,!1);const n=((i=this.manager.getStepStorage(this.step.stepName))==null?void 0:i.framePatternData)||{};return this.manager.updateStorage(this.step.stepName,{framePatternData:{...n,backgroundRemovedAssetKey:a.key,useOriginalAsset:!t}}),a}changeColors(t){ut.changeColors(this.step,this.manager,t)}getImageData(){if(this.frameService)return this.frameService.getImageData()}async getColorOption(){return this.step.data.colorOption}getAvailableColors(){return this.step.data.colorPickerEnabled?ut.availableColors(this.step,this.manager):Promise.resolve([])}isColorPickerEnabled(){return this.step.data.colorPickerEnabled??!1}async getOriginalImageColors(){const t=this.getImageData();return t!=null&&t.svg?(await ot(t.svg)).colors:void 0}getMaxAllowedColors(){return this.step.data.maxColors}getUniqueColorCount(){return ut.getUniqueColorCount(this.step,this.manager)}getCurrentFrameStep(t,e,a,n){return n&&n.length>1&&t===void 0?"SelectFrame":e||a||this.getImageData()?"Position":"SelectImage"}getFrameService(){return this.frameService}hasOverlayImageKey(){return this.step.data.overlayImageKey}hasOverlayImageUrl(){return this.step.data.overlayImageUrl}getWhitelistedExtensions(){return[...this.step.data.whitelistedExtensions,...this.step.data.whitelistedExtensions.includes(".jpg")?[".jpeg"]:[]]}async getOriginalImageSelection(){var e,a;const t=(a=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:a.originalAssetKey;if(t)return U.getLocalOrFromServer(t)}async getBackgroundRemovedImageSelection(){var e,a;const t=(a=(e=this.manager.getStepStorage(this.step.stepName))==null?void 0:e.framePatternData)==null?void 0:a.backgroundRemovedAssetKey;if(t)return U.getLocalOrFromServer(t)}hasOriginalImageSelection(){var t,e;return!!((e=(t=this.manager.getStepStorage(this.step.stepName))==null?void 0:t.framePatternData)!=null&&e.originalAssetKey)}hasBackgroundRemovedImageSelection(){var t,e;return!!((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)!=null&&e.backgroundRemovedAssetKey)}getUseOriginalImageSelection(){var t,e;return((e=(t=this.getFrameStepStorage())==null?void 0:t.framePatternData)==null?void 0:e.useOriginalAsset)??!1}async setUseOriginalImageSelection(t){var n;const e=((n=this.getFrameStepStorage())==null?void 0:n.framePatternData)||{};if(e.useOriginalAsset===t)return;const a=await this.getOriginalImageSelection();if(!a)throw new Error("You must provide an image selection before calling setUseOriginalImageSelection");if(t)await this.selectImage(a,!1,!1);else{const i=await this.getBackgroundRemovedImageSelection();if(!i)throw new Error("You must call removeBackgroundFromImageSelection before attempting to apply the image.");await this.selectImage(i,!1,!1)}this.manager.updateStorage(this.step.stepName,{framePatternData:{...e,useOriginalAsset:t}})}getFrameStepStorage(){return this.manager.getStepStorage(this.step.stepName)}}const kc=v.gql`
|
|
2455
2459
|
query GetLoggedInCustomer($email: String!) {
|
|
2456
2460
|
customer(emailAddress: $email) {
|
|
2457
2461
|
id
|