b23-lib 2.0.21 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,2 +1,3 @@
1
- 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var lt=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var lt__default=/*#__PURE__*/_interopDefault(lt);var w=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},U=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},O=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},B=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},z=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},x=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},F=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},V=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},$=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},G=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},k=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},K=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},q=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},j=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},Q=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},v=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},D=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},I=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},y=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},E=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var Z=new Uint8Array(256),H=Z.length;function W(){return H>Z.length-16&&(lt__default.default.randomFillSync(Z),H=0),Z.slice(H,H+=16)}var rt=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function dt(r){return typeof r=="string"&&rt.test(r)}var nt=dt;var m=[];for(let r=0;r<256;++r)m.push((r+256).toString(16).slice(1));function Y(r,t=0){return m[r[t+0]]+m[r[t+1]]+m[r[t+2]]+m[r[t+3]]+"-"+m[r[t+4]]+m[r[t+5]]+"-"+m[r[t+6]]+m[r[t+7]]+"-"+m[r[t+8]]+m[r[t+9]]+"-"+m[r[t+10]]+m[r[t+11]]+m[r[t+12]]+m[r[t+13]]+m[r[t+14]]+m[r[t+15]]}function gt(r){if(!nt(r))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(r.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(r.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(r.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(r.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(r.slice(24,36),16))/1099511627776&255,e[11]=t/4294967296&255,e[12]=t>>>24&255,e[13]=t>>>16&255,e[14]=t>>>8&255,e[15]=t&255,e}var ot=gt;function pt(r){r=unescape(encodeURIComponent(r));let t=[];for(let e=0;e<r.length;++e)t.push(r.charCodeAt(e));return t}var mt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ht="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function J(r,t,e){function i(n,o,s,d){var c;if(typeof n=="string"&&(n=pt(n)),typeof o=="string"&&(o=ot(o)),((c=o)===null||c===void 0?void 0:c.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+n.length);if(a.set(o),a.set(n,o.length),a=e(a),a[6]=a[6]&15|t,a[8]=a[8]&63|128,s){d=d||0;for(let h=0;h<16;++h)s[d+h]=a[h];return s}return Y(a)}try{i.name=r;}catch{}return i.DNS=mt,i.URL=ht,i}var _={randomUUID:lt__default.default.randomUUID};function ft(r,t,e){if(_.randomUUID&&!t&&!r)return _.randomUUID();r=r||{};let i=r.random||(r.rng||W)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let n=0;n<16;++n)t[e+n]=i[n];return t}return Y(i)}var tt=ft;function Ct(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),lt__default.default.createHash("sha1").update(r).digest()}var st=Ct;var xt=J("v5",80,st),et=xt;var It={isUUID:r=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r),isEmail:r=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r),isURL:r=>/^(http|https):\/\/[^ "]+$/.test(r),generateUUID:(r,t)=>t&&r?et(r,t):tt(),generateSearchId:(r,t)=>`${r}#${A.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:r=>{let[t,e]=r.split("#");return {key:t,selectionAttributes:A.parseSelectionAttributesKey(e)}},deepClone(r){return structuredClone(r)}},l=It;var f=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){this.customFields={...t.customFields},this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,n){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:n};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}};var C={"en-IN":"en","kn-IN":"kn"};var at={INR:"\u20B9"},ct={INR:"en-IN"};var T=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw new E("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw new E("Cannot remove the 'original' image source.");delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var u=class r{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new v("Amount cannot be negative.");if(!t.currency)throw new D("Currency code is required.");this.amount=t.amount,this.currency=t.currency;}get kind(){return this.#t}static isPriceModel(t){return typeof t=="object"&&t!==null&&t.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new I("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new I("Cannot add prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return new r({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new I("Cannot subtract prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return new r({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new I("Cannot multiply prices in different currencies.");return new r({amount:this.amount*t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new r({amount:this.amount*t,currency:this.currency});throw new y("Must be a non-negative number.")}divide(t){if(r.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new I("Cannot divide prices in different currencies.");return new r({amount:this.amount/t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>0)return new r({amount:this.amount/t,currency:this.currency});throw new y("Must be a positive number.")}min(...t){if(t.length===0)throw new y("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(r.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new I("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i})}max(...t){if(t.length===0)throw new y("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(r.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new I("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i})}zero(){return new r({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new r({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return r.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return r.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=ct[e];if(!e||!n)throw new D("Invalid currency code for formatting.");let o=t,s=i.displayAsInteger?0:r.getDecimalPlaces(e),d={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:s,maximumFractionDigits:s};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,d).format(o)}catch(c){return console.error(`Error formatting price for currency "${e}" and locale "${n}":`,c),`${at[e]??e} ${r.addThousandSeparators(o.toFixed(s))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],n=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(t,e){if(t<0)throw new v("Amount cannot be negative for rounding.");if(e===void 0)throw new D("Invalid currency code for rounding.");let i=r.getDecimalPlaces(e),n=Math.pow(10,i);return Math.round(t*n)/n}};var M=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new u(t.baseUnitPrice);if(!t.taxCategory)throw new G;let i=(t.tiers??[]).map(c=>({minQuantity:c.minQuantity,unitPrice:new u(c.unitPrice)})).sort((c,a)=>c.minQuantity-a.minQuantity);if(i.some(c=>c.minQuantity<=0))throw new k;let o=i.some(c=>c.unitPrice.getCurrency()!==e.getCurrency()),s=i.some((c,a)=>a>0&&c.unitPrice.compareTo(i[a-1].unitPrice)>0),d=i[0]?.unitPrice.compareTo(e)>0;if(o||s||d)throw new K("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new q;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new j(t)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let t=this.tiers[this.tiers.length-1].unitPrice.getAmount(),e=this.baseUnitPrice.getAmount();return (e-t)/e*100}};var A=class r extends f{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(t){if(typeof t!="object")throw new x("Selection attributes must be an object");return Object.keys(t).filter(i=>t[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>t[i].name?`${i}:c+${t[i].name}`:`${i}:${t[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(t){try{let e={},i=t.split("|");for(let n of i){let[o,s]=n.split(":");s.startsWith("c+")?e[o]={name:s.slice(2)}:e[o]=s;}return e}catch(e){throw new x(e?.message)}}constructor(t,e=new Date){super(t,e),this.id=t.id,this.key=t.key,this.name={...t.name},this.description={...t.description},this.slug={...t.slug},this.brand=t.brand,this.pricing=Object.keys(t.pricing).reduce((n,o)=>(t.pricing[o]&&(n[o]=new M(t.pricing[o])),n),{}),this.targetGender=t.targetGender,this.attributes=l.deepClone(t.attributes),this.specifications=l.deepClone(t.specifications),this.categories=l.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new x("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new O(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new T(n.images.primary),gallery:(n.images.gallery||[]).map(s=>new T(s))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?l.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[C[t]]??this.name.en:l.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[C[t]]??this.description.en:l.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[C[t]]??this.slug.en:l.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:this.pricing}getAttributes(){return l.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:t.selectionAttributes,images:{primary:t.images.primary,gallery:t.images.gallery}}))}getImagesBySelectionAttributes(t){let e=r.generateSelectionAttributesKey(t),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===e);return i?i.images:null}getImages(t,e){switch(e){case"PRIMARY":return this.getImagesBySelectionAttributes(t)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(t)?.gallery??[];default:return this.getImagesBySelectionAttributes(t)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return l.deepClone(this.categories)}getSpecifications(t){return t?l.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):l.deepClone(this.specifications)}getSearchTags(t){return t?l.deepClone(this.searchTags[t]??this.searchTags[C[t]]??this.searchTags.en):l.deepClone(this.searchTags)}getDetails(){let t=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((e,i)=>(this.pricing[i]&&(e[i]=this.pricing[i]?.getDetails()),e),{}),attributes:this.getAttributes(),variants:this.variants.map(e=>({sku:e.sku,selectionAttributes:l.deepClone(e.selectionAttributes),images:{primary:e.images.primary.getDetails(),gallery:e.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...t}}checkSelectionAttributes(t){if(!t||typeof t!="object")throw new x("Selection attributes are required");Object.keys(this.attributes).forEach(e=>{if(e.toLowerCase()==="size")return;let i=this.attributes[e],n=t[e];if(n===void 0)throw new x(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new x(`Selection attribute '${e}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new x(`Selection attribute '${e}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new x(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=r.generateSelectionAttributesKey(t);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var P=class extends f{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.company=t.company||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var X=class r extends f{taxRuleId;taxSystem;taxCategory;country;slabs;effectiveFrom;effectiveTo;constructor(t,e=new Date){super(t,e),this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.slabs=t.slabs.map(i=>({rate:i.rate,minUnitPrice:new u(i.minUnitPrice),maxUnitPrice:i.maxUnitPrice?new u(i.maxUnitPrice):void 0})),this.effectiveFrom=new Date(t.effectiveFrom),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getSlabs(){return this.slabs}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0,...super.getDetails()}}appliesTo(t,e,i=new Date){return this.taxCategory===t&&this.country===e&&this.effectiveFrom<=i&&(this.effectiveTo?this.effectiveTo>=i:!0)}getApplicableTaxRate(t){return r.getApplicableTaxRate(t,this.slabs)}getTaxRateDisplayString(t,e){let i=this.getApplicableTaxRate(t);return r.getTaxRateDisplayString(i,{taxSystem:this.taxSystem,merchantState:e?.merchantState,customerState:e?.customerState})}static getApplicableTaxRate(t,e){let i=e.filter(n=>(n.minUnitPrice===void 0||t.compareTo(n.minUnitPrice)>=0)&&(n.maxUnitPrice===void 0||t.compareTo(n.maxUnitPrice)<0));if(i.length!==1)throw new Q;return i[0].rate}static getTaxRateDisplayString(t,e){let i=t*100,n=i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"");if(e.taxSystem==="GST"&&e.merchantState&&e.customerState)if(e.merchantState.toLowerCase().trim()===e.customerState.toLowerCase().trim()){let o=i/2%1===0?(i/2).toString():(i/2).toFixed(2).replace(/\.?0+$/,"");return `${o}% CGST + ${o}% SGST`}else return `${n}% IGST`;return e.taxSystem?`${n}% ${e.taxSystem}`:`${n}%`}};var L=class{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=l.deepClone(t.selectionAttributes),this.name=l.deepClone(t.name),this.specifications=l.deepClone(t.specifications),this.primaryImage=new T(t.primaryImage),this.subItems=l.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new U(i.size);e.add(i.size);}),this.pricing={unitPrice:new u(t.pricing.unitPrice),tierPricing:new M(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,tax:{taxRuleId:t.pricing.tax.taxRuleId,taxSystem:t.pricing.tax.taxSystem,country:t.pricing.tax.country,rate:t.pricing.tax.rate,taxSlabs:t.pricing.tax.taxSlabs.map(i=>({rate:i.rate,minUnitPrice:new u(i.minUnitPrice),maxUnitPrice:i.maxUnitPrice?new u(i.maxUnitPrice):void 0}))}},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,subtotal:new u(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,n])=>[i,new u(n)])),taxableAmount:new u(t.total.taxableAmount),taxTotal:new u(t.total.taxTotal),grandTotal:new u(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return l.deepClone(this.selectionAttributes)}getName(t){return t?l.deepClone(this.name[t]??this.name[C[t]]??this.name.en):l.deepClone(this.name)}getSpecifications(t){return t?l.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):l.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return l.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:{taxRuleId:this.pricing.tax.taxRuleId,taxSystem:this.pricing.tax.taxSystem,country:this.pricing.tax.country,rate:this.pricing.tax.rate,taxSlabs:this.pricing.tax.taxSlabs}}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,subtotal:this.total.subtotal,taxableAmount:this.total.taxableAmount,taxTotal:this.total.taxTotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,e])=>[t,e])),grandTotal:this.total.grandTotal}}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:this.getPricing().unitPrice.getDetails(),tierPricing:this.getPricing().tierPricing.getDetails(),taxCategory:this.getPricing().taxCategory,tax:{taxRuleId:this.getPricing().tax.taxRuleId,taxSystem:this.getPricing().tax.taxSystem,country:this.getPricing().tax.country,rate:this.getPricing().tax.rate,taxSlabs:this.getPricing().tax.taxSlabs.map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}},state:this.getState(),total:{quantity:this.getTotal().quantity,subtotal:this.getTotal().subtotal.getDetails(),taxableAmount:this.getTotal().taxableAmount.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),discounts:Object.fromEntries(Object.entries(this.getTotal().discounts).map(([t,e])=>[t,e.getDetails()])),grandTotal:this.getTotal().grandTotal.getDetails()}}}addSubItems(t,e){t.forEach(i=>{let n=this.subItems.find(o=>o.size===i.size);n?n.quantity=e?n.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new B;if(!t.getIsActive())throw new z;this.subItems.forEach(d=>{if(!t.validateSize(d.size))throw new F});let n=t.getPriceDetails(e);if(!n||n.getBaseUnitPrice().getCurrency()!==i)throw new V;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((d,c)=>d+c.quantity,0),{unitPrice:s}=n.getApplicableTier(o);this.pricing={unitPrice:s,tierPricing:n,taxCategory:n.getTaxCategory(),tax:this.pricing.tax},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}updateTax(t){if(!t.appliesTo(this.pricing.taxCategory,this.pricing.tax.country))throw new $;let e=this.total.quantity>0?this.total.taxableAmount.divide(this.total.quantity):this.total.taxableAmount.zero();this.pricing.tax={taxRuleId:t.getTaxRuleId(),taxSystem:t.getTaxSystem(),country:t.getCountry(),rate:t.getApplicableTaxRate(e),taxSlabs:t.getSlabs()},this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((b,p)=>b+p.quantity,0),{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),n=i.multiply(e),o=Object.values(this.total.discounts).reduce((b,p)=>b.add(p),t),s=n.subtract(o),d=e>0?s.divide(e):t,c=X.getApplicableTaxRate(d,this.pricing.tax.taxSlabs),a=s.multiply(c).round(),h=n.subtract(o).add(a);this.total={quantity:e,subtotal:n,taxableAmount:s,taxTotal:a,discounts:this.total.discounts,grandTotal:h};}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new T({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:this.pricing.tax},this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};}};var N=class extends f{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){if(super(t,e),this.couponCode=t.couponCode,this.name=l.deepClone(t.name),this.description=l.deepClone(t.description),this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=Object.keys(t.minCartValue).reduce((i,n)=>{let o=t.minCartValue[n];return o&&(i[n]=new u(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,n)=>{let o=t.maxCartDiscount[n];return o&&(i[n]=new u(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new y("Percentage value cannot be greater than 100");this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[C[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[C[t]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue[t]:this.minCartValue}getMaxCartDiscount(t){return t?this.maxCartDiscount[t]:this.maxCartDiscount}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((t,e)=>{let i=this.getMinCartValue(e);return i&&(t[e]=i.getDetails()),t},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((t,e)=>{let i=this.getMaxCartDiscount(e);return i&&(t[e]=i.getDetails()),t},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}calculateApplicableCouponDiscount(t,e,i,n,o=!0){let s=new u({amount:0,currency:n}),d;if(o&&!this.isActive())return s;let c=this.getMinCartValue(i),a=this.getMaxCartDiscount(i);if(!c||c.compareTo(t)>0||!a)return s;let h=this.getCategory(),b=this.getDiscountMethod(),p=h==="SHIPPING"?e:t;if(p.getAmount()<=0)return s;switch(b){case"flat":let ut=a;d=p.min(ut);break;case"percentage":d=p.multiply(this.getPercentageValue()/100).round();break;default:return s}return d.min(a)}};var R=class extends f{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new L(i)),this.billingAddress=t.billingAddress?new P(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new P(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new N(i)),this.shippingDetails=t.shippingDetails?l.deepClone(t.shippingDetails):null,this.total={subtotal:new u(t.total.subtotal),shipping:new u(t.total.shipping),effectiveShipping:new u(t.total.effectiveShipping),taxTotal:new u(t.total.taxTotal),couponTotal:Object.fromEntries(Object.entries(t.total.couponTotal).map(([i,n])=>[i,new u(n)])),couponDiscountTotal:new u(t.total.couponDiscountTotal),grandTotal:new u(t.total.grandTotal)};}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new L(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new P(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new P(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return this.total}getDetails(){return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:{subtotal:this.getTotal().subtotal.getDetails(),shipping:this.getTotal().shipping.getDetails(),effectiveShipping:this.getTotal().effectiveShipping.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),couponTotal:Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([t,e])=>[t,e.getDetails()])),couponDiscountTotal:this.getTotal().couponDiscountTotal.getDetails(),grandTotal:this.getTotal().grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new u({amount:0,currency:this.currency}),e=this.lineItems.filter(p=>p.getState()!=="CANCELLED"),i=e.reduce((p,S)=>p.add(S.getTotal().subtotal),t),n=new u({amount:this.shippingDetails?.cost||0,currency:this.currency}).round(),o=t,s={},d={};this.coupons.forEach(p=>{let S=p.calculateApplicableCouponDiscount(i,n,this.country,this.currency);o=o.add(S),s[p.getCode()]=S,p.getCategory()!=="SHIPPING"&&(d[p.getCode()]=S);}),this.applyDiscountsInLineItem(d);let c=e.reduce((p,S)=>p.add(S.getTotal().taxTotal),t),a=this.coupons.find(p=>p.getCategory()==="SHIPPING"),h=a?n.subtract(s[a.getCode()]||t):n,b=i.add(n).add(c).subtract(o);this.total={subtotal:i,shipping:n,effectiveShipping:h,couponTotal:s,couponDiscountTotal:o,taxTotal:c,grandTotal:b};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(n=>n.getCategory()==="SHIPPING"),i=t.filter(n=>n.getCategory()!=="SHIPPING");this.coupons=[],this.total.couponDiscountTotal=this.total.subtotal.zero(),this.total.couponTotal={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.couponTotal),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(n=>!n[1].isZero()),i=new Map;this.lineItems.forEach(n=>i.set(n.getId(),[])),e.forEach(([n,o])=>{let s=this.coupons.find(a=>a.getCode()===n);if(!s||o.isZero())return;let d=this.lineItems.filter(a=>a.getState()!=="CANCELLED"&&!a.getTotal().subtotal.isZero()).sort((a,h)=>a.getTotal().subtotal.compareTo(h.getTotal().subtotal)),c=new u({amount:0,currency:this.currency});d.forEach((a,h)=>{let b;h===d.length-1?b=o.subtract(c):b=o.multiply(a.getTotal().subtotal).divide(this.total.subtotal).round(),c=c.add(b),i.get(a.getId())?.push({coupon:s,amount:b});});}),this.lineItems.forEach(n=>{n.getState()==="CANCELLED"||this.total.subtotal.isZero()?n.updateDiscounts([]):n.updateDiscounts(i.get(n.getId())||[]);});}updateTax(t){this.lineItems.forEach(e=>{e.updateTax(t[e.getPricing().taxCategory]);}),this.calculateTotals();}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shipping,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.couponTotal[e[0].getCode()]=i,this.total.couponDiscountTotal=i);}}applyShippingCoupons(t){if(this.total.shipping.getAmount()>0&&t.length>0){let e=this.total.subtotal.subtract(this.total.couponDiscountTotal),i=t.reduce((o,s)=>{if(!o)return s;let d=s.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping),c=o.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);return d===c?s.getType()==="coupon"?s:o:d>c?s:o}),n=i.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);n.getAmount()>0&&(this.coupons.push(i),this.total.couponTotal[i.getCode()]=n,this.total.couponDiscountTotal=this.total.couponDiscountTotal.add(n),this.total.effectiveShipping=this.total.shipping.subtract(n));}}};var Tt=(n=>(n.ACTIVE="ACTIVE",n.FROZEN="FROZEN",n.MERGED="MERGED",n.ORDERED="ORDERED",n))(Tt||{}),St={expiresAtInSeconds:120*24*60*60},it=class extends R{state;expireAt;config;constructor(t,e=new Date,i=St){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+i.expiresAtInSeconds,this.config=i;}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}clearCartItems(){this.lineItems=[],this.coupons=[],this.shippingDetails=null,this.total.couponTotal={},this.calculateTotals();}validateLineItems(t){this.lineItems=this.lineItems.map(e=>{try{e.updateProductData(t[e.getProductKey()],this.country,this.currency);}catch(i){console.error(`Error recalculating line item ${e.getId()}:`,i),e.clearLineItem();}return e}).filter(e=>e.getId()),this.calculateTotals();}addLineItem(t){let e=t.getProductKey(),i=t.getSelectionAttributes(),n=A.generateSelectionAttributesKey(i),o=this.lineItems.findIndex(s=>s.getProductKey()===e&&A.generateSelectionAttributesKey(s.getSelectionAttributes())===n);return o>=0?this.lineItems[o].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.calculateTotals(),o>=0?o:this.lineItems.length-1}updateLineItem(t,e,i){let n=this.lineItems,o=n.findIndex(s=>s.getId()===t);if(o<0)throw new w(t);return n[o].addSubItems([{size:e,quantity:i}],!1),this.calculateTotals(),o}removeLineItem(t){let i=this.lineItems.findIndex(n=>n.getId()===t);if(i<0)throw new w(t);return this.lineItems.splice(i,1),this.calculateTotals(),i}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};exports.CartState=Tt;exports.DEFAULT_CART_CONFIG=St;exports.default=it;//# sourceMappingURL=Cart.js.map
1
+ 'use strict';Object.defineProperty(exports,'__esModule',{value:true});var gt=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var gt__default=/*#__PURE__*/_interopDefault(gt);var L=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},U=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},O=class extends Error{constructor(t){super(`Duplicate selection attribute found: ${t}`),this.name="DuplicateSelectionAttributeError";}},B=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},F=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},x=class extends Error{constructor(t="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${t}`),this.name="SelectionAttributeParseError";}},z=class extends Error{constructor(t="Size does not match."){super(`SizeMismatch: ${t}`),this.name="SizeMismatchError";}},$=class extends Error{constructor(t="Pricing details not available for the product"){super(`NotFound: ${t}`),this.name="PricingNotFoundError";}},V=class extends Error{constructor(t="Tax rule category mismatch."){super(`InvalidTaxRule: ${t}`),this.name="InvalidTaxRuleError";}},G=class extends Error{constructor(t="Tax category is not valid."){super(`InvalidTaxCategory: ${t}`),this.name="InvalidTaxCategoryError";}},k=class extends Error{constructor(t="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${t}`),this.name="InvalidMinQuantityError";}},K=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},q=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},j=class extends Error{constructor(t){super(`NoApplicableTier: Quantity ${t} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}},Q=class extends Error{constructor(t="No applicable tax slab or multiple slabs found for the given unit price."){super(`TaxSlabNotFound: ${t}`),this.name="TaxSlabNotFoundError";}},v=class extends Error{constructor(t="Amount cannot be negative."){super(`InvalidAmount: ${t}`),this.name="InvalidPriceAmountError";}},D=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},T=class extends Error{constructor(t="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${t}`),this.name="CurrencyMismatchError";}},f=class extends Error{constructor(t){super(`InvalidArgument: ${t}`),this.name="InvalidArgumentError";}},E=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var Z=new Uint8Array(256),H=Z.length;function W(){return H>Z.length-16&&(gt__default.default.randomFillSync(Z),H=0),Z.slice(H,H+=16)}var nt=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;function pt(n){return typeof n=="string"&&nt.test(n)}var ot=pt;var h=[];for(let n=0;n<256;++n)h.push((n+256).toString(16).slice(1));function Y(n,t=0){return h[n[t+0]]+h[n[t+1]]+h[n[t+2]]+h[n[t+3]]+"-"+h[n[t+4]]+h[n[t+5]]+"-"+h[n[t+6]]+h[n[t+7]]+"-"+h[n[t+8]]+h[n[t+9]]+"-"+h[n[t+10]]+h[n[t+11]]+h[n[t+12]]+h[n[t+13]]+h[n[t+14]]+h[n[t+15]]}function mt(n){if(!ot(n))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(n.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(n.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(n.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(n.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(n.slice(24,36),16))/1099511627776&255,e[11]=t/4294967296&255,e[12]=t>>>24&255,e[13]=t>>>16&255,e[14]=t>>>8&255,e[15]=t&255,e}var st=mt;function ht(n){n=unescape(encodeURIComponent(n));let t=[];for(let e=0;e<n.length;++e)t.push(n.charCodeAt(e));return t}var yt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",ft="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function J(n,t,e){function i(r,o,s,c){var u;if(typeof r=="string"&&(r=ht(r)),typeof o=="string"&&(o=st(o)),((u=o)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let a=new Uint8Array(16+r.length);if(a.set(o),a.set(r,o.length),a=e(a),a[6]=a[6]&15|t,a[8]=a[8]&63|128,s){c=c||0;for(let m=0;m<16;++m)s[c+m]=a[m];return s}return Y(a)}try{i.name=n;}catch{}return i.DNS=yt,i.URL=ft,i}var _={randomUUID:gt__default.default.randomUUID};function Ct(n,t,e){if(_.randomUUID&&!t&&!n)return _.randomUUID();n=n||{};let i=n.random||(n.rng||W)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let r=0;r<16;++r)t[e+r]=i[r];return t}return Y(i)}var tt=Ct;function Tt(n){return Array.isArray(n)?n=Buffer.from(n):typeof n=="string"&&(n=Buffer.from(n,"utf8")),gt__default.default.createHash("sha1").update(n).digest()}var at=Tt;var St=J("v5",80,at),et=St;var It={isUUID:n=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(n),isEmail:n=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(n),isURL:n=>/^(http|https):\/\/[^ "]+$/.test(n),generateUUID:(n,t)=>t&&n?et(n,t):tt(),generateSearchId:(n,t)=>`${n}#${S.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:n=>{let[t,e]=n.split("#");return {key:t,selectionAttributes:S.parseSelectionAttributesKey(e)}},deepClone(n){return structuredClone(n)}},d=It;var b=class{customFields;version;createdAt;modifiedAt;modifiedBy;constructor(t,e=new Date){this.customFields={...t.customFields},this.version=t.version??1,this.createdAt=t.createdAt&&!isNaN(Date.parse(t.createdAt))?new Date(t.createdAt).toISOString():e.toISOString(),this.modifiedAt=t.modifiedAt&&!isNaN(Date.parse(t.modifiedAt))?new Date(t.modifiedAt).toISOString():e.toISOString(),this.modifiedBy={...t.modifiedBy};}getDetails(){return {customFields:this.getAllCustomFields(),version:this.getVersion(),createdAt:this.getCreatedAt(),modifiedAt:this.getModifiedAt(),modifiedBy:this.getModifiedBy()}}getVersion(){return this.version}getCreatedAt(){return this.createdAt}getCreatedAtTime(){return new Date(this.createdAt).getTime()}getModifiedAt(){return this.modifiedAt}getModifiedAtTime(){return new Date(this.modifiedAt).getTime()}getModifiedBy(){return {...this.modifiedBy}}setModifiedBy(t,e,i,r){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:r};}getCustomField(t){return this.customFields[t]??null}setCustomField(t,e){this.customFields[t]=e;}getAllCustomFields(){return {...this.customFields}}};var C={"en-IN":"en","kn-IN":"kn"};var ct={INR:"\u20B9"},ut={INR:"en-IN"};var I=class{sources;alt;order;label;constructor(t){if(this.sources={...t.sources},this.alt=t.alt,this.order=t.order,this.label=t.label,!this.sources.original)throw new E("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(t){return this.sources[t]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(t){this.alt=t;}setOrder(t){this.order=t;}setLabel(t){this.label=t;}setSource(t,e){if(e===void 0){if(t==="original")throw new E("Cannot remove the 'original' image source.");delete this.sources[t];}else this.sources[t]=e;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var l=class n{#t;amount;currency;constructor(t){if(this.#t="PriceModel",t.amount<0)throw new v("Amount cannot be negative.");if(!t.currency)throw new D("Currency code is required.");this.amount=t.amount,this.currency=t.currency;}get kind(){return this.#t}static isPriceModel(t){return typeof t=="object"&&t!==null&&t.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot add prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new n({amount:this.amount+t.getAmount(),currency:this.currency})}subtract(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot subtract prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return new n({amount:this.amount-t.getAmount(),currency:this.currency})}multiply(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot multiply prices in different currencies.");return new n({amount:this.amount*t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>=0)return new n({amount:this.amount*t,currency:this.currency});throw new f("Must be a non-negative number.")}divide(t){if(n.isPriceModel(t)){if(this.currency!==t.getCurrency())throw new T("Cannot divide prices in different currencies.");return new n({amount:this.amount/t.getAmount(),currency:this.currency})}else if(typeof t=="number"&&t>0)return new n({amount:this.amount/t,currency:this.currency});throw new f("Must be a positive number.")}min(...t){if(t.length===0)throw new f("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return e.compareTo(i)<0?e:i})}max(...t){if(t.length===0)throw new f("Must provide at least one PriceModel.");return t.reduce((e,i)=>{if(n.isPriceModel(i)){if(e.getCurrency()!==i.getCurrency())throw new T("Cannot compare prices in different currencies.")}else throw new f("Must be a PriceModel instance.");return e.compareTo(i)>0?e:i})}zero(){return new n({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new n({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return n.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return n.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let r=ut[e];if(!e||!r)throw new D("Invalid currency code for formatting.");let o=t,s=i.displayAsInteger?0:n.getDecimalPlaces(e),c={style:i.style??"currency",currency:e,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:s,maximumFractionDigits:s};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(r,c).format(o)}catch(u){return console.error(`Error formatting price for currency "${e}" and locale "${r}":`,u),`${ct[e]??e} ${n.addThousandSeparators(o.toFixed(s))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],r=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+r}static getRoundedAmount(t,e){if(t<0)throw new v("Amount cannot be negative for rounding.");if(e===void 0)throw new D("Invalid currency code for rounding.");let i=n.getDecimalPlaces(e),r=Math.pow(10,i);return Math.round(t*r)/r}};var M=class{baseUnitPrice;taxCategory;tiers;constructor(t){let e=new l(t.baseUnitPrice);if(!t.taxCategory)throw new G;let i=(t.tiers??[]).map(u=>({minQuantity:u.minQuantity,unitPrice:new l(u.unitPrice)})).sort((u,a)=>u.minQuantity-a.minQuantity);if(i.some(u=>u.minQuantity<=0))throw new k;let o=i.some(u=>u.unitPrice.getCurrency()!==e.getCurrency()),s=i.some((u,a)=>a>0&&u.unitPrice.compareTo(i[a-1].unitPrice)>0),c=i[0]?.unitPrice.compareTo(e)>0;if(o||s||c)throw new K("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=e,this.taxCategory=t.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(t=>({minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}}getApplicableTier(t){if(t<=0)throw new q;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new j(t)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let t=this.tiers[this.tiers.length-1].unitPrice.getAmount(),e=this.baseUnitPrice.getAmount();return (e-t)/e*100}};var S=class n extends b{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(t){if(typeof t!="object")throw new x("Selection attributes must be an object");return Object.keys(t).filter(i=>t[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>t[i].name?`${i}:c+${t[i].name}`:`${i}:${t[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(t){try{let e={},i=t.split("|");for(let r of i){let[o,s]=r.split(":");s.startsWith("c+")?e[o]={name:s.slice(2)}:e[o]=s;}return e}catch(e){throw new x(e?.message)}}constructor(t,e=new Date){super(t,e),this.id=t.id,this.key=t.key,this.name={...t.name},this.description={...t.description},this.slug={...t.slug},this.brand=t.brand,this.pricing=Object.keys(t.pricing).reduce((r,o)=>(t.pricing[o]&&(r[o]=new M(t.pricing[o])),r),{}),this.targetGender=t.targetGender,this.attributes=d.deepClone(t.attributes),this.specifications=d.deepClone(t.specifications),this.categories=d.deepClone(t.categories);let i=new Set;this.variants=(t.variants||[]).map(r=>{if(!r.selectionAttributes||typeof r.selectionAttributes!="object")throw new x("Selection attributes are required");this.checkSelectionAttributes(r.selectionAttributes);let o=n.generateSelectionAttributesKey(r.selectionAttributes);if(i.has(o))throw new O(o);return i.add(o),{sku:r.sku,selectionAttributes:r.selectionAttributes,images:{primary:new I(r.images.primary),gallery:(r.images.gallery||[]).map(s=>new I(s))}}}),this.isActive=t.isActive,this.searchTags=t.searchTags?d.deepClone(t.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(t){return t?this.name[t]??this.name[C[t]]??this.name.en:d.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[C[t]]??this.description.en:d.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[C[t]]??this.slug.en:d.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:this.pricing}getAttributes(){return d.deepClone(this.attributes)}getVariants(){return this.variants.map(t=>({sku:t.sku,selectionAttributes:t.selectionAttributes,images:{primary:t.images.primary,gallery:t.images.gallery}}))}getImagesBySelectionAttributes(t){let e=n.generateSelectionAttributesKey(t),i=this.variants.find(r=>n.generateSelectionAttributesKey(r.selectionAttributes)===e);return i?i.images:null}getImages(t,e){switch(e){case"PRIMARY":return this.getImagesBySelectionAttributes(t)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(t)?.gallery??[];default:return this.getImagesBySelectionAttributes(t)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return d.deepClone(this.categories)}getSpecifications(t){return t?d.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):d.deepClone(this.specifications)}getSearchTags(t){return t?d.deepClone(this.searchTags[t]??this.searchTags[C[t]]??this.searchTags.en):d.deepClone(this.searchTags)}getDetails(){let t=super.getDetails();return {id:this.getId(),key:this.getKey(),name:this.getName(),description:this.getDescription(),slug:this.getSlug(),brand:this.getBrand(),pricing:Object.keys(this.pricing).reduce((e,i)=>(this.pricing[i]&&(e[i]=this.pricing[i]?.getDetails()),e),{}),attributes:this.getAttributes(),variants:this.variants.map(e=>({sku:e.sku,selectionAttributes:d.deepClone(e.selectionAttributes),images:{primary:e.images.primary.getDetails(),gallery:e.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...t}}checkSelectionAttributes(t){if(!t||typeof t!="object")throw new x("Selection attributes are required");Object.keys(this.attributes).forEach(e=>{if(e.toLowerCase()==="size")return;let i=this.attributes[e],r=t[e];if(r===void 0)throw new x(`Selection attribute '${e}' is missing`);if(typeof i=="string"){if(typeof r!="string"||i!==r)throw new x(`Selection attribute '${e}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof r!="string"||!i.includes(r))throw new x(`Selection attribute '${e}' is invalid`)}else if(typeof r!="object"||!("name"in r)||i.findIndex(o=>o.name===r.name)<0)throw new x(`Selection attribute '${e}' is invalid`)}});}validateSelectionAttribute(t){let e=n.generateSelectionAttributesKey(t);return this.variants.some(i=>n.generateSelectionAttributesKey(i.selectionAttributes)===e)}validateSize(t){return this.attributes.size.includes(t)}};var P=class extends b{id;firstName;lastName;company;phone;email;addressLine1;addressLine2;city;postalCode;state;country;isBillingAddress;isShippingAddress;constructor(t,e=new Date){super(t,e),this.id=t.id,this.firstName=t.firstName,this.lastName=t.lastName||"",this.company=t.company||"",this.phone=t.phone,this.email=t.email,this.addressLine1=t.addressLine1,this.addressLine2=t.addressLine2||"",this.city=t.city,this.postalCode=t.postalCode,this.state=t.state,this.country=t.country,this.isBillingAddress=t.isBillingAddress,this.isShippingAddress=t.isShippingAddress;}getDetails(){return {...super.getDetails(),id:this.getId(),firstName:this.getFirstName(),lastName:this.getLastName(),company:this.getCompany(),phone:this.getPhone(),email:this.getEmail(),addressLine1:this.getAddressLine1(),addressLine2:this.getAddressLine2(),city:this.getCity(),postalCode:this.getPostalCode(),state:this.getState(),country:this.getCountry(),isBillingAddress:this.getIsBillingAddress(),isShippingAddress:this.getIsShippingAddress()}}getId(){return this.id}getFirstName(){return this.firstName}getLastName(){return this.lastName}getCompany(){return this.company}getPhone(){return this.phone}getEmail(){return this.email}getAddressLine1(){return this.addressLine1}getAddressLine2(){return this.addressLine2}getCity(){return this.city}getPostalCode(){return this.postalCode}getState(){return this.state}getCountry(){return this.country}getIsBillingAddress(){return this.isBillingAddress}getIsShippingAddress(){return this.isShippingAddress}getAddressType(){return this.isBillingAddress&&this.isShippingAddress?"billing&shipping":this.isBillingAddress?"billing":this.isShippingAddress?"shipping":"none"}static checkIfShippingAddress(t){return t==="shipping"||t==="billing&shipping"}static checkIfBillingAddress(t){return t==="billing"||t==="billing&shipping"}};var it=class{getBreakdown(t,e,i){let r=t*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,"");if(e==="IN"&&i?.merchantState&&i?.customerState)if(i.merchantState.toLowerCase().trim()===i.customerState.toLowerCase().trim()){let s=r/2%1===0?(r/2).toString():(r/2).toFixed(2).replace(/\.?0+$/,"");return {totalRate:t,label:`${s}% CGST + ${s}% SGST`,components:[{rate:t/2,label:`${s}% CGST`,type:"CGST"},{rate:t/2,label:`${s}% SGST`,type:"SGST"}]}}else return {totalRate:t,label:`${o}% IGST`,components:[{rate:t,label:`${o}% IGST`,type:"IGST"}]};return {totalRate:t,label:`${o}% GST`,components:[{rate:t,label:`${o}% GST`,type:"GST"}]}}getLongName(){return "Goods and Services Tax"}},lt={GST:new it},X=class n extends b{taxRuleId;taxSystem;taxCategory;country;slabs;effectiveFrom;effectiveTo;constructor(t,e=new Date){super(t,e),this.taxRuleId=t.taxRuleId,this.taxSystem=t.taxSystem,this.taxCategory=t.taxCategory,this.country=t.country,this.slabs=t.slabs.map(i=>({rate:i.rate,minUnitPrice:new l(i.minUnitPrice),maxUnitPrice:i.maxUnitPrice?new l(i.maxUnitPrice):void 0})),this.effectiveFrom=new Date(t.effectiveFrom),this.effectiveTo=t.effectiveTo?new Date(t.effectiveTo):void 0;}getTaxRuleId(){return this.taxRuleId}getTaxSystem(){return this.taxSystem}getTaxCategory(){return this.taxCategory}getCountry(){return this.country}getSlabs(){return this.slabs}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs().map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0})),effectiveFrom:this.effectiveFrom.toISOString(),effectiveTo:this.effectiveTo?this.effectiveTo.toISOString():void 0,...super.getDetails()}}appliesTo(t,e,i=new Date){return this.taxCategory===t&&this.country===e&&this.effectiveFrom<=i&&(this.effectiveTo?this.effectiveTo>=i:!0)}getApplicableTaxRate(t){return n.getApplicableTaxRate(t,this.slabs)}getTaxRateDisplayString(t,e){let i=this.getApplicableTaxRate(t);return n.getTaxRateDisplayString(i,{taxSystem:this.taxSystem,merchantState:e?.merchantState,customerState:e?.customerState})}getTaxRateBreakdown(t,e){let i=this.getApplicableTaxRate(t),r=lt[this.taxSystem];if(r)return r.getBreakdown(i,this.country,e);let o=i*100,c=`${o%1===0?o.toString():o.toFixed(2).replace(/\.?0+$/,"")}% ${this.taxSystem}`;return {totalRate:i,label:c,components:[{rate:i,label:c,type:this.taxSystem}]}}getFormattedTaxRate(t,e={}){let r=this.getApplicableTaxRate(t)*100,o=r%1===0?r.toString():r.toFixed(2).replace(/\.?0+$/,""),s=e.variant||"short",c="";switch(s){case"percentageOnly":c=`${o}%`;break;case"detailed":let u=this.getTaxRateBreakdown(t,e),a=e.separator||(e.multiline?`
2
+ `:" + ");c=u.components.map(p=>p.label).join(a);break;case"long":let m=lt[this.taxSystem],y=m?m.getLongName(this.country):this.taxSystem.toString();c=`${o}% ${y}`;break;case"short":default:c=`${o}% ${this.taxSystem}`;break}return e.includeTaxesSuffix&&(c+=" (Incl. Taxes)"),c}static getApplicableTaxRate(t,e){let i=e.filter(r=>(r.minUnitPrice===void 0||t.compareTo(r.minUnitPrice)>=0)&&(r.maxUnitPrice===void 0||t.compareTo(r.maxUnitPrice)<0));if(i.length!==1)throw new Q;return i[0].rate}static getTaxRateDisplayString(t,e){let i=t*100,r=i%1===0?i.toString():i.toFixed(2).replace(/\.?0+$/,"");if(e.taxSystem==="GST"&&e.merchantState&&e.customerState)if(e.merchantState.toLowerCase().trim()===e.customerState.toLowerCase().trim()){let o=i/2%1===0?(i/2).toString():(i/2).toFixed(2).replace(/\.?0+$/,"");return `${o}% CGST + ${o}% SGST`}else return `${r}% IGST`;return e.taxSystem?`${r}% ${e.taxSystem}`:`${r}%`}};var w=class{id;productKey;selectionAttributes;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){this.id=t.id,this.productKey=t.productKey,this.selectionAttributes=d.deepClone(t.selectionAttributes),this.name=d.deepClone(t.name),this.specifications=d.deepClone(t.specifications),this.primaryImage=new I(t.primaryImage),this.subItems=d.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new U(i.size);e.add(i.size);}),this.pricing={unitPrice:new l(t.pricing.unitPrice),tierPricing:new M(t.pricing.tierPricing),taxCategory:t.pricing.taxCategory,tax:{taxRuleId:t.pricing.tax.taxRuleId,taxSystem:t.pricing.tax.taxSystem,country:t.pricing.tax.country,rate:t.pricing.tax.rate,taxSlabs:t.pricing.tax.taxSlabs.map(i=>({rate:i.rate,minUnitPrice:new l(i.minUnitPrice),maxUnitPrice:i.maxUnitPrice?new l(i.maxUnitPrice):void 0}))}},this.state=t.state??"INITIAL",this.total={quantity:t.total.quantity,subtotal:new l(t.total.subtotal),discounts:Object.fromEntries(Object.entries(t.total.discounts).map(([i,r])=>[i,new l(r)])),taxableAmount:new l(t.total.taxableAmount),taxTotal:new l(t.total.taxTotal),grandTotal:new l(t.total.grandTotal)};}getId(){return this.id}getProductKey(){return this.productKey}getSelectionAttributes(){return d.deepClone(this.selectionAttributes)}getName(t){return t?d.deepClone(this.name[t]??this.name[C[t]]??this.name.en):d.deepClone(this.name)}getSpecifications(t){return t?d.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):d.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return d.deepClone(this.subItems)}getTotalQuantity(){return this.total.quantity}getPricing(){return {unitPrice:this.pricing.unitPrice,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:{taxRuleId:this.pricing.tax.taxRuleId,taxSystem:this.pricing.tax.taxSystem,country:this.pricing.tax.country,rate:this.pricing.tax.rate,taxSlabs:this.pricing.tax.taxSlabs}}}getState(){return this.state}getTotal(){return {quantity:this.total.quantity,subtotal:this.total.subtotal,taxableAmount:this.total.taxableAmount,taxTotal:this.total.taxTotal,discounts:Object.fromEntries(Object.entries(this.total.discounts).map(([t,e])=>[t,e])),grandTotal:this.total.grandTotal}}getDetails(){return {id:this.getId(),productKey:this.getProductKey(),selectionAttributes:this.getSelectionAttributes(),name:this.getName(),specifications:this.getSpecifications(),primaryImage:this.getImage().getDetails(),subItems:this.getSubItems(),pricing:{unitPrice:this.getPricing().unitPrice.getDetails(),tierPricing:this.getPricing().tierPricing.getDetails(),taxCategory:this.getPricing().taxCategory,tax:{taxRuleId:this.getPricing().tax.taxRuleId,taxSystem:this.getPricing().tax.taxSystem,country:this.getPricing().tax.country,rate:this.getPricing().tax.rate,taxSlabs:this.getPricing().tax.taxSlabs.map(t=>({rate:t.rate,minUnitPrice:t.minUnitPrice.getDetails(),maxUnitPrice:t.maxUnitPrice?t.maxUnitPrice.getDetails():void 0}))}},state:this.getState(),total:{quantity:this.getTotal().quantity,subtotal:this.getTotal().subtotal.getDetails(),taxableAmount:this.getTotal().taxableAmount.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),discounts:Object.fromEntries(Object.entries(this.getTotal().discounts).map(([t,e])=>[t,e.getDetails()])),grandTotal:this.getTotal().grandTotal.getDetails()}}}addSubItems(t,e){t.forEach(i=>{let r=this.subItems.find(o=>o.size===i.size);r?r.quantity=e?r.quantity+i.quantity:i.quantity:this.subItems.push(i);}),this.subItems=this.subItems.filter(i=>i.quantity>0),this.calculateTotals();}updateProductData(t,e,i){if(this.productKey!==t.getKey()||!t.validateSelectionAttribute(this.selectionAttributes))throw new B;if(!t.getIsActive())throw new F;this.subItems.forEach(c=>{if(!t.validateSize(c.size))throw new z});let r=t.getPriceDetails(e);if(!r||r.getBaseUnitPrice().getCurrency()!==i)throw new $;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttributes).primary;let o=this.subItems.reduce((c,u)=>c+u.quantity,0),{unitPrice:s}=r.getApplicableTier(o);this.pricing={unitPrice:s,tierPricing:r,taxCategory:r.getTaxCategory(),tax:this.pricing.tax},this.calculateTotals();}updateDiscounts(t){let e={};t.forEach(i=>{e[i.coupon.getCode()]=i.amount;}),this.total.discounts=e,this.calculateTotals();}updateTax(t){if(!t.appliesTo(this.pricing.taxCategory,this.pricing.tax.country))throw new V;let e=this.total.quantity>0?this.total.taxableAmount.divide(this.total.quantity):this.total.taxableAmount.zero();this.pricing.tax={taxRuleId:t.getTaxRuleId(),taxSystem:t.getTaxSystem(),country:t.getCountry(),rate:t.getApplicableTaxRate(e),taxSlabs:t.getSlabs()},this.calculateTotals();}calculateTotals(){let t=this.pricing.unitPrice.zero(),e=this.subItems.reduce((y,p)=>y+p.quantity,0),{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),r=i.multiply(e),o=Object.values(this.total.discounts).reduce((y,p)=>y.add(p),t),s=r.subtract(o),c=e>0?s.divide(e):t,u=X.getApplicableTaxRate(c,this.pricing.tax.taxSlabs),a=s.multiply(u).round(),m=r.subtract(o).add(a);this.total={quantity:e,subtotal:r,taxableAmount:s,taxTotal:a,discounts:this.total.discounts,grandTotal:m};}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttributes={color:{name:""}},this.name={en:""},this.primaryImage=new I({sources:{original:""}}),this.subItems=[],this.pricing={unitPrice:t,tierPricing:this.pricing.tierPricing,taxCategory:this.pricing.taxCategory,tax:this.pricing.tax},this.total={quantity:0,subtotal:t,taxableAmount:t,taxTotal:t,discounts:{},grandTotal:t};}};var R=class extends b{couponCode;name;description;type;customerId;validFrom;validTo;minCartValue;maxCartDiscount;discountMethod;percentageValue;applicableTo;category;constructor(t,e=new Date){if(super(t,e),this.couponCode=t.couponCode,this.name=d.deepClone(t.name),this.description=d.deepClone(t.description),this.type=t.type,this.customerId=t.customerId,this.validFrom=t.validFrom&&Date.parse(t.validFrom)?new Date(t.validFrom).toISOString():e.toISOString(),this.validTo=t.validTo&&Date.parse(t.validTo)?new Date(t.validTo).toISOString():e.toISOString(),this.minCartValue=Object.keys(t.minCartValue).reduce((i,r)=>{let o=t.minCartValue[r];return o&&(i[r]=new l(o)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,r)=>{let o=t.maxCartDiscount[r];return o&&(i[r]=new l(o)),i},{}),this.discountMethod=t.discountMethod,this.percentageValue=t.percentageValue??0,this.percentageValue>100)throw new f("Percentage value cannot be greater than 100");this.applicableTo=t.applicableTo,this.category=t.category;}getCode(){return this.couponCode}getName(t){return t?this.name[t]??this.name[C[t]]??this.name.en:{...this.name}}getDescription(t){return t?this.description[t]??this.description[C[t]]??this.description.en:{...this.description}}getType(){return this.type}getCustomerId(){return this.customerId??""}getValidFrom(){return this.validFrom}getValidTo(){return this.validTo}getMinCartValue(t){return t?this.minCartValue[t]:this.minCartValue}getMaxCartDiscount(t){return t?this.maxCartDiscount[t]:this.maxCartDiscount}getDiscountMethod(){return this.discountMethod}getPercentageValue(){return this.percentageValue}getApplicableTo(){return this.applicableTo}getCategory(){return this.category}getDetails(){return {...super.getDetails(),couponCode:this.getCode(),name:this.getName(),description:this.getDescription(),type:this.getType(),customerId:this.getCustomerId(),validFrom:this.getValidFrom(),validTo:this.getValidTo(),minCartValue:Object.keys(this.getMinCartValue()).reduce((t,e)=>{let i=this.getMinCartValue(e);return i&&(t[e]=i.getDetails()),t},{}),maxCartDiscount:Object.keys(this.getMaxCartDiscount()).reduce((t,e)=>{let i=this.getMaxCartDiscount(e);return i&&(t[e]=i.getDetails()),t},{}),discountMethod:this.getDiscountMethod(),percentageValue:this.getPercentageValue(),applicableTo:this.getApplicableTo(),category:this.getCategory()}}isActive(){return new Date(this.validFrom)<=new Date&&new Date(this.validTo)>=new Date}isApplicableTo(t){return this.applicableTo==="all"||this.applicableTo==="ftb"&&t}calculateApplicableCouponDiscount(t,e,i,r,o=!0){let s=new l({amount:0,currency:r}),c;if(o&&!this.isActive())return s;let u=this.getMinCartValue(i),a=this.getMaxCartDiscount(i);if(!u||u.compareTo(t)>0||!a)return s;let m=this.getCategory(),y=this.getDiscountMethod(),p=m==="SHIPPING"?e:t;if(p.getAmount()<=0)return s;switch(y){case"flat":let dt=a;c=p.min(dt);break;case"percentage":c=p.multiply(this.getPercentageValue()/100).round();break;default:return s}return c.min(a)}};var N=class extends b{id;customerId;customerEmail;anonymousId;lineItems;shippingDetails;shippingAddress;billingAddress;coupons;total;country;currency;locale;constructor(t,e=new Date){super(t,e),this.id=t.id,this.customerId=t.customerId,this.customerEmail=t.customerEmail,this.anonymousId=t.anonymousId,this.country=t.country,this.currency=t.currency,this.locale=t.locale,this.lineItems=(t.lineItems??[]).map(i=>new w(i)),this.billingAddress=t.billingAddress?new P(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new P(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new R(i)),this.shippingDetails=t.shippingDetails?d.deepClone(t.shippingDetails):null,this.total={subtotal:new l(t.total.subtotal),shipping:new l(t.total.shipping),effectiveShipping:new l(t.total.effectiveShipping),taxTotal:new l(t.total.taxTotal),couponTotal:Object.fromEntries(Object.entries(t.total.couponTotal).map(([i,r])=>[i,new l(r)])),couponDiscountTotal:new l(t.total.couponDiscountTotal),grandTotal:new l(t.total.grandTotal)};}getId(){return this.id}getCustomerId(){return this.customerId}getCustomerEmail(){return this.customerEmail}getAnonymousId(){return this.anonymousId}getLineItems(){return this.lineItems.map(t=>new w(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new P(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new P(this.billingAddress.getDetails()):null}getCoupons(){return this.coupons}getCountry(){return this.country}getCurrency(){return this.currency}getLocale(){return this.locale}getTotal(){return this.total}getDetails(){return {...super.getDetails(),id:this.getId(),customerId:this.getCustomerId(),customerEmail:this.getCustomerEmail(),anonymousId:this.getAnonymousId(),lineItems:this.getLineItems().map(t=>t.getDetails()),shippingDetails:this.getShippingDetails(),shippingAddress:this.getShippingAddress()?.getDetails()||null,billingAddress:this.getBillingAddress()?.getDetails()||null,coupons:this.getCoupons().map(t=>t.getDetails()),total:{subtotal:this.getTotal().subtotal.getDetails(),shipping:this.getTotal().shipping.getDetails(),effectiveShipping:this.getTotal().effectiveShipping.getDetails(),taxTotal:this.getTotal().taxTotal.getDetails(),couponTotal:Object.fromEntries(Object.entries(this.getTotal().couponTotal).map(([t,e])=>[t,e.getDetails()])),couponDiscountTotal:this.getTotal().couponDiscountTotal.getDetails(),grandTotal:this.getTotal().grandTotal.getDetails()},country:this.getCountry(),currency:this.getCurrency(),locale:this.getLocale()}}calculateTotals(){let t=new l({amount:0,currency:this.currency}),e=this.lineItems.filter(p=>p.getState()!=="CANCELLED"),i=e.reduce((p,A)=>p.add(A.getTotal().subtotal),t),r=new l({amount:this.shippingDetails?.cost||0,currency:this.currency}).round(),o=t,s={},c={};this.coupons.forEach(p=>{let A=p.calculateApplicableCouponDiscount(i,r,this.country,this.currency);o=o.add(A),s[p.getCode()]=A,p.getCategory()!=="SHIPPING"&&(c[p.getCode()]=A);}),this.applyDiscountsInLineItem(c);let u=e.reduce((p,A)=>p.add(A.getTotal().taxTotal),t),a=this.coupons.find(p=>p.getCategory()==="SHIPPING"),m=a?r.subtract(s[a.getCode()]||t):r,y=i.add(r).add(u).subtract(o);this.total={subtotal:i,shipping:r,effectiveShipping:m,couponTotal:s,couponDiscountTotal:o,taxTotal:u,grandTotal:y};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(r=>r.getCategory()==="SHIPPING"),i=t.filter(r=>r.getCategory()!=="SHIPPING");this.coupons=[],this.total.couponDiscountTotal=this.total.subtotal.zero(),this.total.couponTotal={},i.length&&this.applyNonShippingCoupons(i),this.applyDiscountsInLineItem(this.total.couponTotal),e.length&&this.applyShippingCoupons(e),this.calculateTotals();}applyDiscountsInLineItem(t){let e=Array.from(Object.entries(t)).filter(r=>!r[1].isZero()),i=new Map;this.lineItems.forEach(r=>i.set(r.getId(),[])),e.forEach(([r,o])=>{let s=this.coupons.find(a=>a.getCode()===r);if(!s||o.isZero())return;let c=this.lineItems.filter(a=>a.getState()!=="CANCELLED"&&!a.getTotal().subtotal.isZero()).sort((a,m)=>a.getTotal().subtotal.compareTo(m.getTotal().subtotal)),u=new l({amount:0,currency:this.currency});c.forEach((a,m)=>{let y;m===c.length-1?y=o.subtract(u):y=o.multiply(a.getTotal().subtotal).divide(this.total.subtotal).round(),u=u.add(y),i.get(a.getId())?.push({coupon:s,amount:y});});}),this.lineItems.forEach(r=>{r.getState()==="CANCELLED"||this.total.subtotal.isZero()?r.updateDiscounts([]):r.updateDiscounts(i.get(r.getId())||[]);});}updateTax(t){this.lineItems.forEach(e=>{e.updateTax(t[e.getPricing().taxCategory]);}),this.calculateTotals();}applyNonShippingCoupons(t){let e=t.filter(i=>i.getType()==="coupon");if(e.length===1){let i=e[0].calculateApplicableCouponDiscount(this.total.subtotal,this.total.shipping,this.country,this.currency);i.getAmount()>0&&(this.coupons.push(e[0]),this.total.couponTotal[e[0].getCode()]=i,this.total.couponDiscountTotal=i);}}applyShippingCoupons(t){if(this.total.shipping.getAmount()>0&&t.length>0){let e=this.total.subtotal.subtract(this.total.couponDiscountTotal),i=t.reduce((o,s)=>{if(!o)return s;let c=s.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping),u=o.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);return c===u?s.getType()==="coupon"?s:o:c>u?s:o}),r=i.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);r.getAmount()>0&&(this.coupons.push(i),this.total.couponTotal[i.getCode()]=r,this.total.couponDiscountTotal=this.total.couponDiscountTotal.add(r),this.total.effectiveShipping=this.total.shipping.subtract(r));}}};var Pt=(r=>(r.ACTIVE="ACTIVE",r.FROZEN="FROZEN",r.MERGED="MERGED",r.ORDERED="ORDERED",r))(Pt||{}),Dt={expiresAtInSeconds:120*24*60*60},rt=class extends N{state;expireAt;config;constructor(t,e=new Date,i=Dt){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+i.expiresAtInSeconds,this.config=i;}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}clearCartItems(){this.lineItems=[],this.coupons=[],this.shippingDetails=null,this.total.couponTotal={},this.calculateTotals();}validateLineItems(t){this.lineItems=this.lineItems.map(e=>{try{e.updateProductData(t[e.getProductKey()],this.country,this.currency);}catch(i){console.error(`Error recalculating line item ${e.getId()}:`,i),e.clearLineItem();}return e}).filter(e=>e.getId()),this.calculateTotals();}addLineItem(t){let e=t.getProductKey(),i=t.getSelectionAttributes(),r=S.generateSelectionAttributesKey(i),o=this.lineItems.findIndex(s=>s.getProductKey()===e&&S.generateSelectionAttributesKey(s.getSelectionAttributes())===r);return o>=0?this.lineItems[o].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.calculateTotals(),o>=0?o:this.lineItems.length-1}updateLineItem(t,e,i){let r=this.lineItems,o=r.findIndex(s=>s.getId()===t);if(o<0)throw new L(t);return r[o].addSubItems([{size:e,quantity:i}],!1),this.calculateTotals(),o}removeLineItem(t){let i=this.lineItems.findIndex(r=>r.getId()===t);if(i<0)throw new L(t);return this.lineItems.splice(i,1),this.calculateTotals(),i}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};exports.CartState=Pt;exports.DEFAULT_CART_CONFIG=Dt;exports.default=rt;//# sourceMappingURL=Cart.js.map
2
3
  //# sourceMappingURL=Cart.js.map