b23-lib 2.0.2 → 2.0.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Auth/index.js +1 -1
- package/dist/Auth/index.js.map +1 -1
- package/dist/Auth/index.mjs +1 -1
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Coupon.js +1 -1
- package/dist/Classes/Coupon.js.map +1 -1
- package/dist/Classes/Coupon.mjs +1 -1
- package/dist/Classes/Inventory.js +1 -1
- package/dist/Classes/Inventory.js.map +1 -1
- package/dist/Classes/Inventory.mjs +1 -1
- package/dist/Classes/LineItem.js +1 -1
- package/dist/Classes/LineItem.js.map +1 -1
- package/dist/Classes/LineItem.mjs +1 -1
- package/dist/Classes/Order.js +1 -1
- package/dist/Classes/Order.js.map +1 -1
- package/dist/Classes/Order.mjs +1 -1
- package/dist/Classes/Product.d.mts +5 -0
- package/dist/Classes/Product.d.ts +5 -0
- package/dist/Classes/Product.js +1 -1
- package/dist/Classes/Product.js.map +1 -1
- package/dist/Classes/Product.mjs +1 -1
- package/dist/Classes/ShoppingContainer.js +1 -1
- package/dist/Classes/ShoppingContainer.js.map +1 -1
- package/dist/Classes/ShoppingContainer.mjs +1 -1
- package/dist/Classes/TaxRule.js +1 -1
- package/dist/Classes/TaxRule.js.map +1 -1
- package/dist/Classes/TaxRule.mjs +1 -1
- package/dist/{chunk-QLLM365R.mjs → chunk-3DSTZDT6.mjs} +2 -2
- package/dist/{chunk-QLLM365R.mjs.map → chunk-3DSTZDT6.mjs.map} +1 -1
- package/dist/{chunk-M4BZMGTB.mjs → chunk-B7VG6LHU.mjs} +2 -2
- package/dist/{chunk-M4BZMGTB.mjs.map → chunk-B7VG6LHU.mjs.map} +1 -1
- package/dist/chunk-HUDDEQPH.mjs +2 -0
- package/dist/chunk-HUDDEQPH.mjs.map +1 -0
- package/dist/{chunk-LXJGGXF3.mjs → chunk-V2IDNBA2.mjs} +2 -2
- package/dist/{chunk-LXJGGXF3.mjs.map → chunk-V2IDNBA2.mjs.map} +1 -1
- package/dist/{chunk-SFTIM3X7.mjs → chunk-X7DG44HI.mjs} +2 -2
- package/dist/{chunk-SFTIM3X7.mjs.map → chunk-X7DG44HI.mjs.map} +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/package.json +1 -1
- package/dist/chunk-ISS46WVH.mjs +0 -2
- package/dist/chunk-ISS46WVH.mjs.map +0 -1
package/dist/Auth/index.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a as a$1,b,d,c as c$1}from'../chunk-AMIRIUMH.mjs';import {a as a$2}from'../chunk-
|
|
1
|
+
import {a as a$1,b,d,c as c$1}from'../chunk-AMIRIUMH.mjs';import {a as a$2}from'../chunk-HUDDEQPH.mjs';import'../chunk-KWH7GE23.mjs';import'../chunk-54RUAXYE.mjs';import'../chunk-72DR3HF2.mjs';import'../chunk-NUTKOIGY.mjs';import'../chunk-NJKSUUOB.mjs';import'../chunk-55SOBG62.mjs';import {importPKCS8,SignJWT,importSPKI,jwtVerify,decodeJwt}from'jose';import a from'assert';var c=class l{static instance=null;id;type;token;initializedAt;lambdaName;requestId;constructor(e,t,i,r){this.id=e,this.type=t,this.token=i,this.lambdaName=process.env.AWS_LAMBDA_FUNCTION_NAME,this.initializedAt=new Date;}static getInstance(){return a(l.instance,a$1.AUTH_CONTEXT_NOT_INITIALIZED),l.instance}static init(e,t,i,r){return l.instance=new l(e,t,i,r),l.instance}static uninit(){l.instance=null;}getId(){return this.id}getType(){return this.type}getToken(){return this.token}getLambdaName(){return this.lambdaName}getRequestId(){return this.requestId}getInitializedAt(){return this.initializedAt}getSystemID(e){let t=this.lambdaName||e;return this.requestId?`${t} - ${this.requestId}`:t}};var K={userTokenAge:"30 days",userPrivateKeys:"[]",userPublicKeys:"[]",anonymousTokenAge:"30 days",anonymousPrivateKeys:"[]",anonymousPublicKeys:"[]",systemTokenAge:"5 min",systemPrivateKeys:"[]",systemPublicKeys:"[]",adminTokenAge:"30 days",adminPrivateKeys:"[]",adminPublicKeys:"[]",cdnKeys:"[]"},U=(n=>(n.ANON="Anon",n.USER="User",n.SYSTEM="System",n.ADMIN="Admin",n.CDN="CDN",n))(U||{}),v={allowAnonymous:!1,allowSystem:!0,allowUser:!0,allowCDN:!1},N=class{userTokenAge;userPrivateKeys;userPublicKeys;anonymousTokenAge;anonymousPrivateKeys;anonymousPublicKeys;systemTokenAge;systemPrivateKeys;systemPublicKeys;adminTokenAge;adminPrivateKeys;adminPublicKeys;cdnKeys;constructor(e=K){let{userTokenAge:t,userPrivateKeys:i,userPublicKeys:r,anonymousTokenAge:n,anonymousPrivateKeys:g,anonymousPublicKeys:h,systemTokenAge:m,systemPrivateKeys:T,systemPublicKeys:A,adminTokenAge:u,adminPrivateKeys:d,adminPublicKeys:S,cdnKeys:f}={...K,...e};this.userTokenAge=t,this.userPrivateKeys=this.parseKeyArray(i,"user private"),this.userPublicKeys=this.parseKeyArray(r,"user public"),this.anonymousTokenAge=n,this.anonymousPrivateKeys=this.parseKeyArray(g,"anonymous private"),this.anonymousPublicKeys=this.parseKeyArray(h,"anonymous public"),this.systemTokenAge=m,this.systemPrivateKeys=this.parseKeyArray(T,"system private"),this.systemPublicKeys=this.parseKeyArray(A,"system public"),this.adminTokenAge=u,this.adminPrivateKeys=this.parseKeyArray(d,"admin private"),this.adminPublicKeys=this.parseKeyArray(S,"admin public"),this.cdnKeys=this.parseKeyArray(f,"cdn"),this.logWarnings();}parseKeyArray(e,t){try{let i=JSON.parse(e);return !Array.isArray(i)||!i.every(r=>typeof r=="string")?(b.logError("AuthUtility",`Invalid format for ${t} keys in config: Expected stringified array of strings.`),[]):i}catch(i){return b.logError("AuthUtility",`Failed to parse ${t} keys from config: ${i}`),[]}}logWarnings(){let e=(t,i,r)=>i.length>r&&b.logWarning("AuthUtility",`More than ${r} ${t} keys provided. This is not recommended.`);e("user private",this.userPrivateKeys,3),e("user public",this.userPublicKeys,3),e("anonymous private",this.anonymousPrivateKeys,1),e("anonymous public",this.anonymousPublicKeys,3),e("system private",this.systemPrivateKeys,1),e("system public",this.systemPublicKeys,3),e("admin private",this.adminPrivateKeys,1),e("admin public",this.adminPublicKeys,3);}async createSignedJWT(e,t,i){let r=await importPKCS8(t,"RS256");return await new SignJWT(e).setProtectedHeader({alg:"RS256"}).setExpirationTime(i).setIssuedAt().sign(r)}async verifySignedJWT(e,t,i){for(let r=t.length-1;r>=0;r--)try{let n=await importSPKI(t[r],"RS256");return (await jwtVerify(e,n,{clockTolerance:30,maxTokenAge:i})).payload}catch(n){if(r===0)throw n;continue}throw new Error(a$1.INVALID_TOKEN)}async createAnonymousToken(e,t){a(this.anonymousPrivateKeys.length,a$1.ANONYMOUS_PRIVATE_KEY_NOT_FOUND),a(a$2.isUUID(e),a$1.INVALID_UUID);let i={id:e,type:"Anon",...t};return await this.createSignedJWT(i,this.anonymousPrivateKeys[this.anonymousPrivateKeys.length-1],this.anonymousTokenAge)}async verifyAnonymousToken(e){a(this.anonymousPublicKeys.length,a$1.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.anonymousPublicKeys,this.anonymousTokenAge);return a(t.type==="Anon",a$1.INVALID_AUTH_TYPE),t}async createUserToken(e,t){a(this.userPrivateKeys.length,a$1.USER_PRIVATE_KEY_NOT_FOUND),a(a$2.isUUID(e),a$1.INVALID_UUID);let i={id:e,type:"User",...t};return await this.createSignedJWT(i,this.userPrivateKeys[this.userPrivateKeys.length-1],this.userTokenAge)}async verifyUserToken(e){a(this.userPublicKeys.length,a$1.USER_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.userPublicKeys,this.userTokenAge);return a(t.type==="User",a$1.INVALID_AUTH_TYPE),t}async createSystemToken(e,t){a(this.systemPrivateKeys.length,a$1.SYSTEM_PRIVATE_KEY_NOT_FOUND);let i={id:e,type:"System",...t};return await this.createSignedJWT(i,this.systemPrivateKeys[this.systemPrivateKeys.length-1],this.systemTokenAge)}async verifySystemToken(e){a(this.systemPublicKeys.length,a$1.USER_PUBLIC_KEY_NOT_FOUND);let t=await this.verifySignedJWT(e,this.systemPublicKeys,this.systemTokenAge);return a(t.type==="System",a$1.INVALID_AUTH_TYPE),t}async createAdminToken(e,t,i){a(this.adminPrivateKeys.length,a$1.ADMIN_PRIVATE_KEY_NOT_FOUND),a(a$2.isEmail(e),a$1.INVALID_EMAIL),a(a$2.isURL(t),a$1.INVALID_VERIFIER);let r={id:e,type:"Admin",verifier:t,...i};return await this.createSignedJWT(r,this.adminPrivateKeys[this.adminPrivateKeys.length-1],this.adminTokenAge)}async verifyAdminToken(e,t,i){a(this.adminPublicKeys.length,a$1.ADMIN_PUBLIC_KEY_NOT_FOUND);let r=await this.verifySignedJWT(e,this.adminPublicKeys,this.adminTokenAge);if(a(r.type==="Admin",a$1.INVALID_AUTH_TYPE),i){let n=await d(r.verifier,"","POST",{},{token:e,permissions:t});if(a(n.data.isTokenValid===!0,a$1.INVALID_TOKEN),n.data.hasPermissions!==!0)throw c$1.generateError(403,a$1.INVALID_PERMISSIONS)}return r}async verifyCDNToken(e){return a(this.cdnKeys.includes(e),a$1.INVALID_TOKEN),{id:e,type:"CDN"}}AuthMiddleware(e=v,t=[]){let{allowAnonymous:i,allowSystem:r,allowUser:n,allowCDN:g}={...v,...e};return async(h,m,T)=>{try{let[A,u]=h.get("Authorization")?.split(" ")||[];if(!u)throw new Error(a$1.INVALID_TOKEN);let d;switch(A){case"Anon":if(!i)throw c$1.generateError(403,a$1.ANONYMOUS_SESSION_NOT_ALLOWED);d=await this.verifyAnonymousToken(u);break;case"User":if(!n)throw c$1.generateError(403,a$1.USER_SESSION_NOT_ALLOWED);d=await this.verifyUserToken(u);break;case"System":if(!r)throw c$1.generateError(403,a$1.SYSTEM_SESSION_NOT_ALLOWED);d=await this.verifySystemToken(u);break;case"Admin":d=await this.verifyAdminToken(u,t,!0);break;case"CDN":if(!g)throw c$1.generateError(403,a$1.CDN_SESSION_NOT_ALLOWED);d=await this.verifyCDNToken(u);break;default:throw c$1.generateError(403,a$1.INVALID_AUTH_TYPE)}T();}catch(A){b.logError("AuthMiddleware",A),c$1.handleException("AuthMiddleware",c$1.generateError(401,A.error||a$1.TOKEN_EXPIRED,!0),m);}}}decodeJWTPayloadWithJose(e){if(!e||typeof e!="string")return b.logError("AuthContextMiddleware","Invalid token provided for decoding."),null;try{return decodeJwt(e)}catch(t){return b.logError("AuthContextMiddleware",`Failed to decode JWT payload: ${t}`),null}}AuthContextMiddleware(){return async(e,t,i)=>{try{let[r,n]=e.get("Authorization")?.split(" ")||[],g=r==="CDN"?{id:n,type:"CDN"}:r?this.decodeJWTPayloadWithJose(n):{},h=c.init(g?.id||n,g?.type||r,n,e.get("x-request-id"));b.logMessage("AuthContextMiddleware",`AuthContext initialized: ${h.getType()||"No-Type"} - ${h.getId()||"No-Id"}`),t.on("finish",()=>{b.logMessage("AuthContextMiddleware","Uninitializing AuthContext"),c.uninit();}),i();}catch(r){b.logError("AuthContextMiddleware",r),c$1.handleException("AuthContextMiddleware",c$1.generateError(500,r.error||a$1.INTERNAL_SERVER_ERROR,!0),t);}}}},j=N;export{c as AuthContext,U as AuthType,v as DefaultAuthMiddlewareConfig,K as DefaultAuthUtilityConfig,j as default};//# sourceMappingURL=index.mjs.map
|
|
2
2
|
//# sourceMappingURL=index.mjs.map
|
package/dist/Classes/Cart.js
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var ut=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ut__default=/*#__PURE__*/_interopDefault(ut);var L=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},R=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},U=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},O=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},B=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";}},F=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";}},$=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";}},K=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},q=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";}},S=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},x=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";}},w=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var j=new Uint8Array(256),H=j.length;function X(){return H>j.length-16&&(ut__default.default.randomFillSync(j),H=0),j.slice(H,H+=16)}var it=/^(?:[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 lt(r){return typeof r=="string"&&it.test(r)}var rt=lt;var m=[];for(let r=0;r<256;++r)m.push((r+256).toString(16).slice(1));function Z(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 dt(r){if(!rt(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=dt;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 gt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",mt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function W(r,t,e){function i(o,n,s,d){var u;if(typeof o=="string"&&(o=pt(o)),typeof n=="string"&&(n=ot(n)),((u=n)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(n),c.set(o,n.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,s){d=d||0;for(let h=0;h<16;++h)s[d+h]=c[h];return s}return Z(c)}try{i.name=r;}catch{}return i.DNS=gt,i.URL=mt,i}var J={randomUUID:ut__default.default.randomUUID};function yt(r,t,e){if(J.randomUUID&&!t&&!r)return J.randomUUID();r=r||{};let i=r.random||(r.rng||X)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let o=0;o<16;++o)t[e+o]=i[o];return t}return Z(i)}var _=yt;function bt(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),ut__default.default.createHash("sha1").update(r).digest()}var nt=bt;var Ct=W("v5",80,nt),tt=Ct;var xt={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?tt(r,t):_(),generateSearchId:(r,t)=>`${r}#${A.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:r=>{let[t,e]=r.split("#");return {key:t,selectionAttribute:e}},deepClone(r){return structuredClone(r)}},a=xt;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,o){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:o};}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 st={INR:"\u20B9"},at={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 w("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 w("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 r{amount;currency;constructor(t){if(t.amount<0)throw new v("Amount cannot be negative.");if(!t.currency)throw new S("Currency code is required.");this.amount=t.amount,this.currency=t.currency;}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(t){if(t instanceof r){if(this.currency!==t.getCurrency())throw new x("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(t instanceof r){if(this.currency!==t.getCurrency())throw new x("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(t instanceof r){if(this.currency!==t.getCurrency())throw new x("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(t instanceof r){if(this.currency!==t.getCurrency())throw new x("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(t instanceof r){if(this.currency!==t.getCurrency())throw new x("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(i instanceof r){if(e.getCurrency()!==i.getCurrency())throw new x("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(i instanceof r){if(e.getCurrency()!==i.getCurrency())throw new x("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)}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let o=at[e];if(!e||!o)throw new S("Invalid currency code for formatting.");let n=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&&(n=Math.ceil(n));try{return new Intl.NumberFormat(o,d).format(n)}catch(u){return console.error(`Error formatting price for currency "${e}" and locale "${o}":`,u),`${st[e]??e} ${r.addThousandSeparators(n.toFixed(s))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],o=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+o}static getRoundedAmount(t,e){if(t<0)throw new v("Amount cannot be negative for rounding.");if(e===void 0)throw new S("Invalid currency code for rounding.");let i=r.getDecimalPlaces(e),o=Math.pow(10,i);return Math.round(t*o)/o}};var P=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,c)=>u.minQuantity-c.minQuantity);if(i.some(u=>u.minQuantity<=0))throw new $;let n=i.some(u=>u.unitPrice.getCurrency()!==e.getCurrency()),s=i.some((u,c)=>c>0&&u.unitPrice.compareTo(i[c-1].unitPrice)>0),d=i[0]?.unitPrice.compareTo(e)>0;if(n||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 K;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new q(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){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("|")}static parseSelectionAttributesKey(t){try{let e={},i=t.split("|");for(let o of i){let[n,s]=o.split(":");s.startsWith("c+")?e[n]={name:s.slice(2)}:e[n]=s;}return e}catch(e){throw new B(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((i,o)=>(t.pricing[o]&&(i[o]=new P(t.pricing[o])),i),{}),this.targetGender=t.targetGender,this.attributes=a.deepClone(t.attributes),this.specifications=a.deepClone(t.specifications),this.categories=a.deepClone(t.categories),this.variants=(t.variants||[]).map(i=>({sku:i.sku,selectionAttributes:i.selectionAttributes,images:{primary:new I(i.images.primary),gallery:(i.images.gallery||[]).map(o=>new I(o))}})),this.isActive=t.isActive,this.searchTags=t.searchTags?a.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:a.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[C[t]]??this.description.en:a.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[C[t]]??this.slug.en:a.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:this.pricing}getAttributes(){return a.deepClone(this.attributes)}getImagesBySelectionAttributes(t){let e=r.generateSelectionAttributesKey(t),i=this.variants.find(o=>r.generateSelectionAttributesKey(o.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 a.deepClone(this.categories)}getSpecifications(t){return t?a.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):a.deepClone(this.specifications)}getSearchTags(t){return t?a.deepClone(this.searchTags[t]??this.searchTags[C[t]]??this.searchTags.en):a.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:a.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}}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 D=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 Y=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=a.deepClone(t.slabs),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 a.deepClone(this.slabs)}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs(),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)}static getApplicableTaxRate(t,e){let i=t.getAmount(),o=e.filter(n=>(n.minUnitPrice===void 0||i>=n.minUnitPrice)&&(n.maxUnitPrice===void 0||i<n.maxUnitPrice));if(o.length!==1)throw new Q;return o[0].rate}};var M=class{id;productKey;selectionAttribute;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){this.id=t.id,this.productKey=t.productKey,this.selectionAttribute=a.deepClone(t.selectionAttribute),this.name=a.deepClone(t.name),this.specifications=a.deepClone(t.specifications),this.primaryImage=new I(t.primaryImage),this.subItems=a.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new R(i.size);e.add(i.size);}),this.pricing={unitPrice:new l(t.pricing.unitPrice),tierPricing:new P(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:a.deepClone(t.pricing.tax.taxSlabs)}},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,o])=>[i,new l(o)])),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}getSelectionAttribute(){return a.deepClone(this.selectionAttribute)}getName(t){return t?a.deepClone(this.name[t]??this.name[C[t]]??this.name.en):a.deepClone(this.name)}getSpecifications(t){return t?a.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):a.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return a.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:a.deepClone(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(),selectionAttribute:this.getSelectionAttribute(),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:this.getPricing().tax},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 o=this.subItems.find(n=>n.size===i.size);o?o.quantity=e?o.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.selectionAttribute))throw new U;if(!t.getIsActive())throw new O;this.subItems.forEach(d=>{if(!t.validateSize(d.size))throw new z});let o=t.getPriceDetails(e);if(!o||o.getBaseUnitPrice().getCurrency()!==i)throw new F;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttribute).primary;let n=this.subItems.reduce((d,u)=>d+u.quantity,0),{unitPrice:s}=o.getApplicableTier(n);this.pricing={unitPrice:s,tierPricing:o,taxCategory:o.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.taxableAmount.divide(this.total.quantity);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,g)=>b+g.quantity,0),{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),o=i.multiply(e),n=Object.values(this.total.discounts).reduce((b,g)=>b.add(g),t),s=o.subtract(n),d=s.divide(e),u=Y.getApplicableTaxRate(d,this.pricing.tax.taxSlabs),c=s.multiply(u).round(),h=o.subtract(n).add(c);this.total={quantity:e,subtotal:o,taxableAmount:s,taxTotal:c,discounts:this.total.discounts,grandTotal:h};}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttribute={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 E=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=a.deepClone(t.name),this.description=a.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,o)=>{let n=t.minCartValue[o];return n&&(i[o]=new l(n)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,o)=>{let n=t.maxCartDiscount[o];return n&&(i[o]=new l(n)),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,o,n=!0){let s=new l({amount:0,currency:o}),d;if(n&&!this.isActive())return s;let u=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!u||u.compareTo(t)>0||!c)return s;let h=this.getCategory(),b=this.getDiscountMethod(),g=h==="SHIPPING"?e:t;if(g.getAmount()<=0)return s;switch(b){case"flat":let ct=c;d=g.min(ct);break;case"percentage":d=g.multiply(this.getPercentageValue()/100).round();break;default:return s}return d.min(c)}};var N=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 M(i)),this.billingAddress=t.billingAddress?new D(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new D(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new E(i)),this.shippingDetails=t.shippingDetails?a.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,o])=>[i,new l(o)])),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 M(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new D(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new D(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(g=>g.getState()!=="CANCELLED"),i=e.reduce((g,T)=>g.add(T.getTotal().subtotal),t),o=new l({amount:this.shippingDetails?.cost||0,currency:this.currency}).round(),n=t,s={},d={};this.coupons.forEach(g=>{let T=g.calculateApplicableCouponDiscount(i,o,this.country,this.currency);n=n.add(T),s[g.getCode()]=T,g.getCategory()!=="SHIPPING"&&(d[g.getCode()]=T);}),this.applyDiscountsInLineItem(d);let u=e.reduce((g,T)=>g.add(T.getTotal().taxTotal),t),c=this.coupons.find(g=>g.getCategory()==="SHIPPING"),h=c?o.subtract(s[c.getCode()]||t):o,b=i.add(o).add(u).subtract(n);this.total={subtotal:i,shipping:o,effectiveShipping:h,couponTotal:s,couponDiscountTotal:n,taxTotal:u,grandTotal:b};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(o=>o.getCategory()==="SHIPPING"),i=t.filter(o=>o.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(o=>!o[1].isZero()),i=new Map;this.lineItems.forEach(o=>i.set(o.getId(),[])),e.forEach(([o,n])=>{let s=this.coupons.find(c=>c.getCode()===o);if(!s)return;let d=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,h)=>c.getTotal().subtotal.compareTo(h.getTotal().subtotal)),u=new l({amount:0,currency:this.currency});d.forEach((c,h)=>{let b;h===d.length-1?b=n.subtract(u):b=n.multiply(c.getTotal().subtotal).divide(this.total.subtotal).round(),u=u.add(b),i.get(c.getId())?.push({coupon:s,amount:b});});}),this.lineItems.forEach(o=>{o.getState()==="CANCELLED"||this.total.subtotal.isZero()?o.updateDiscounts([]):o.updateDiscounts(i.get(o.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((n,s)=>{if(!n)return s;let d=s.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping),u=n.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);return d===u?s.getType()==="coupon"?s:n:d>u?s:n}),o=i.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);o.getAmount()>0&&(this.coupons.push(i),this.total.couponTotal[i.getCode()]=o,this.total.couponDiscountTotal=this.total.couponDiscountTotal.add(o),this.total.effectiveShipping=this.total.shipping.subtract(o));}}};var Tt=(o=>(o.ACTIVE="ACTIVE",o.FROZEN="FROZEN",o.MERGED="MERGED",o.ORDERED="ORDERED",o))(Tt||{}),At={expiresAtInSeconds:120*24*60*60},et=class extends N{state;expireAt;config;constructor(t,e=new Date,i=At){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.getSelectionAttribute(),o=A.generateSelectionAttributesKey(i),n=this.lineItems.findIndex(s=>s.getProductKey()===e&&A.generateSelectionAttributesKey(s.getSelectionAttribute())===o);return n>=0?this.lineItems[n].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.calculateTotals(),n>=0?n:this.lineItems.length-1}updateLineItem(t,e,i){let o=this.lineItems,n=o.findIndex(s=>s.getId()===t);if(n<0)throw new L(t);return o[n].addSubItems([{size:e,quantity:i}],!1),this.calculateTotals(),n}removeLineItem(t){let i=this.lineItems.findIndex(o=>o.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=Tt;exports.DEFAULT_CART_CONFIG=At;exports.default=et;//# sourceMappingURL=Cart.js.map
|
|
1
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:true});var ut=require('crypto');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var ut__default=/*#__PURE__*/_interopDefault(ut);var L=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError";}},R=class extends Error{constructor(t){super(`Duplicate size found: ${t}`),this.name="DuplicateSizeError";}},U=class extends Error{constructor(t="Product and selection attributes do not match."){super(`ProductMismatch: ${t}`),this.name="ProductMismatchError";}},O=class extends Error{constructor(t="Product is not active."){super(`ProductInactive: ${t}`),this.name="ProductInactiveError";}},B=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";}},F=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";}},$=class extends Error{constructor(t){super(`InvalidTieredPrice: ${t}`),this.name="InvalidTieredPriceError";}},K=class extends Error{constructor(t="Quantity must be greater than zero."){super(`InvalidQuantity: ${t}`),this.name="InvalidQuantityError";}},q=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";}},S=class extends Error{constructor(t="Currency code is required."){super(`InvalidCurrency: ${t}`),this.name="InvalidCurrencyCodeError";}},x=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";}},w=class extends Error{constructor(t="Invalid image source configuration."){super(`InvalidImageSource: ${t}`),this.name="InvalidImageSourceError";}};var j=new Uint8Array(256),H=j.length;function X(){return H>j.length-16&&(ut__default.default.randomFillSync(j),H=0),j.slice(H,H+=16)}var it=/^(?:[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 lt(r){return typeof r=="string"&&it.test(r)}var rt=lt;var m=[];for(let r=0;r<256;++r)m.push((r+256).toString(16).slice(1));function Z(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 dt(r){if(!rt(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=dt;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 gt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",mt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function W(r,t,e){function i(o,n,s,d){var u;if(typeof o=="string"&&(o=pt(o)),typeof n=="string"&&(n=ot(n)),((u=n)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let c=new Uint8Array(16+o.length);if(c.set(n),c.set(o,n.length),c=e(c),c[6]=c[6]&15|t,c[8]=c[8]&63|128,s){d=d||0;for(let h=0;h<16;++h)s[d+h]=c[h];return s}return Z(c)}try{i.name=r;}catch{}return i.DNS=gt,i.URL=mt,i}var J={randomUUID:ut__default.default.randomUUID};function yt(r,t,e){if(J.randomUUID&&!t&&!r)return J.randomUUID();r=r||{};let i=r.random||(r.rng||X)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,t){e=e||0;for(let o=0;o<16;++o)t[e+o]=i[o];return t}return Z(i)}var _=yt;function bt(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),ut__default.default.createHash("sha1").update(r).digest()}var nt=bt;var Ct=W("v5",80,nt),tt=Ct;var xt={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?tt(r,t):_(),generateSearchId:(r,t)=>`${r}#${A.generateSelectionAttributesKey(t)}`,getKeyfromSearchId:r=>{let[t,e]=r.split("#");return {key:t,selectionAttribute:e}},deepClone(r){return structuredClone(r)}},a=xt;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,o){this.modifiedBy={id:t,authType:e,requestId:i,lambdaName:o};}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 st={INR:"\u20B9"},at={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 w("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 w("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 r{amount;currency;constructor(t){if(t.amount<0)throw new v("Amount cannot be negative.");if(!t.currency)throw new S("Currency code is required.");this.amount=t.amount,this.currency=t.currency;}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}compareTo(t){if(t instanceof r){if(this.currency!==t.getCurrency())throw new x("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return this.amount-t.getAmount()}add(t){if(t instanceof r){if(this.currency!==t.getCurrency())throw new x("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(t instanceof r){if(this.currency!==t.getCurrency())throw new x("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(t instanceof r){if(this.currency!==t.getCurrency())throw new x("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(t instanceof r){if(this.currency!==t.getCurrency())throw new x("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(i instanceof r){if(e.getCurrency()!==i.getCurrency())throw new x("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(i instanceof r){if(e.getCurrency()!==i.getCurrency())throw new x("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)}static getFormattedString(t,e,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let o=at[e];if(!e||!o)throw new S("Invalid currency code for formatting.");let n=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&&(n=Math.ceil(n));try{return new Intl.NumberFormat(o,d).format(n)}catch(u){return console.error(`Error formatting price for currency "${e}" and locale "${o}":`,u),`${st[e]??e} ${r.addThousandSeparators(n.toFixed(s))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),i=e[0],o=e.length>1?"."+e[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+o}static getRoundedAmount(t,e){if(t<0)throw new v("Amount cannot be negative for rounding.");if(e===void 0)throw new S("Invalid currency code for rounding.");let i=r.getDecimalPlaces(e),o=Math.pow(10,i);return Math.round(t*o)/o}};var P=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,c)=>u.minQuantity-c.minQuantity);if(i.some(u=>u.minQuantity<=0))throw new k;let n=i.some(u=>u.unitPrice.getCurrency()!==e.getCurrency()),s=i.some((u,c)=>c>0&&u.unitPrice.compareTo(i[c-1].unitPrice)>0),d=i[0]?.unitPrice.compareTo(e)>0;if(n||s||d)throw new $("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 K;for(let e=this.tiers.length-1;e>=0;e--)if(t>=this.tiers[e].minQuantity)return this.tiers[e];throw new q(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){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("|")}static parseSelectionAttributesKey(t){try{let e={},i=t.split("|");for(let o of i){let[n,s]=o.split(":");s.startsWith("c+")?e[n]={name:s.slice(2)}:e[n]=s;}return e}catch(e){throw new B(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((i,o)=>(t.pricing[o]&&(i[o]=new P(t.pricing[o])),i),{}),this.targetGender=t.targetGender,this.attributes=a.deepClone(t.attributes),this.specifications=a.deepClone(t.specifications),this.categories=a.deepClone(t.categories),this.variants=(t.variants||[]).map(i=>({sku:i.sku,selectionAttributes:i.selectionAttributes,images:{primary:new I(i.images.primary),gallery:(i.images.gallery||[]).map(o=>new I(o))}})),this.isActive=t.isActive,this.searchTags=t.searchTags?a.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:a.deepClone(this.name)}getDescription(t){return t?this.description[t]??this.description[C[t]]??this.description.en:a.deepClone(this.description)}getSlug(t){return t?this.slug[t]??this.slug[C[t]]??this.slug.en:a.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(t){return t?this.pricing[t]??null:this.pricing}getAttributes(){return a.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(o=>r.generateSelectionAttributesKey(o.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 a.deepClone(this.categories)}getSpecifications(t){return t?a.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):a.deepClone(this.specifications)}getSearchTags(t){return t?a.deepClone(this.searchTags[t]??this.searchTags[C[t]]??this.searchTags.en):a.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:a.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}}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 D=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 Y=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=a.deepClone(t.slabs),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 a.deepClone(this.slabs)}getDetails(){return {taxRuleId:this.getTaxRuleId(),taxSystem:this.getTaxSystem(),taxCategory:this.getTaxCategory(),country:this.getCountry(),slabs:this.getSlabs(),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)}static getApplicableTaxRate(t,e){let i=t.getAmount(),o=e.filter(n=>(n.minUnitPrice===void 0||i>=n.minUnitPrice)&&(n.maxUnitPrice===void 0||i<n.maxUnitPrice));if(o.length!==1)throw new Q;return o[0].rate}};var M=class{id;productKey;selectionAttribute;name;specifications;primaryImage;subItems;pricing;state;total;constructor(t){this.id=t.id,this.productKey=t.productKey,this.selectionAttribute=a.deepClone(t.selectionAttribute),this.name=a.deepClone(t.name),this.specifications=a.deepClone(t.specifications),this.primaryImage=new I(t.primaryImage),this.subItems=a.deepClone(t.subItems);let e=new Set;this.subItems.forEach(i=>{if(e.has(i.size))throw new R(i.size);e.add(i.size);}),this.pricing={unitPrice:new l(t.pricing.unitPrice),tierPricing:new P(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:a.deepClone(t.pricing.tax.taxSlabs)}},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,o])=>[i,new l(o)])),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}getSelectionAttribute(){return a.deepClone(this.selectionAttribute)}getName(t){return t?a.deepClone(this.name[t]??this.name[C[t]]??this.name.en):a.deepClone(this.name)}getSpecifications(t){return t?a.deepClone(this.specifications[t]??this.specifications[C[t]]??this.specifications.en):a.deepClone(this.specifications)}getImage(){return this.primaryImage}getSubItems(){return a.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:a.deepClone(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(),selectionAttribute:this.getSelectionAttribute(),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:this.getPricing().tax},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 o=this.subItems.find(n=>n.size===i.size);o?o.quantity=e?o.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.selectionAttribute))throw new U;if(!t.getIsActive())throw new O;this.subItems.forEach(d=>{if(!t.validateSize(d.size))throw new z});let o=t.getPriceDetails(e);if(!o||o.getBaseUnitPrice().getCurrency()!==i)throw new F;this.name=t.getName(),this.specifications=t.getSpecifications(),this.primaryImage=t.getImages(this.selectionAttribute).primary;let n=this.subItems.reduce((d,u)=>d+u.quantity,0),{unitPrice:s}=o.getApplicableTier(n);this.pricing={unitPrice:s,tierPricing:o,taxCategory:o.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.taxableAmount.divide(this.total.quantity);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,g)=>b+g.quantity,0),{unitPrice:i}=this.pricing.tierPricing.getApplicableTier(e),o=i.multiply(e),n=Object.values(this.total.discounts).reduce((b,g)=>b.add(g),t),s=o.subtract(n),d=s.divide(e),u=Y.getApplicableTaxRate(d,this.pricing.tax.taxSlabs),c=s.multiply(u).round(),h=o.subtract(n).add(c);this.total={quantity:e,subtotal:o,taxableAmount:s,taxTotal:c,discounts:this.total.discounts,grandTotal:h};}clearLineItem(){let t=this.pricing.unitPrice.zero();this.id="",this.productKey="",this.selectionAttribute={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 E=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=a.deepClone(t.name),this.description=a.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,o)=>{let n=t.minCartValue[o];return n&&(i[o]=new l(n)),i},{}),this.maxCartDiscount=Object.keys(t.maxCartDiscount).reduce((i,o)=>{let n=t.maxCartDiscount[o];return n&&(i[o]=new l(n)),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,o,n=!0){let s=new l({amount:0,currency:o}),d;if(n&&!this.isActive())return s;let u=this.getMinCartValue(i),c=this.getMaxCartDiscount(i);if(!u||u.compareTo(t)>0||!c)return s;let h=this.getCategory(),b=this.getDiscountMethod(),g=h==="SHIPPING"?e:t;if(g.getAmount()<=0)return s;switch(b){case"flat":let ct=c;d=g.min(ct);break;case"percentage":d=g.multiply(this.getPercentageValue()/100).round();break;default:return s}return d.min(c)}};var N=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 M(i)),this.billingAddress=t.billingAddress?new D(t.billingAddress,e):null,this.shippingAddress=t.shippingAddress?new D(t.shippingAddress,e):null,this.coupons=(t.coupons??[]).map(i=>new E(i)),this.shippingDetails=t.shippingDetails?a.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,o])=>[i,new l(o)])),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 M(t.getDetails()))}getLineItemsCount(){return this.lineItems.length}getShippingDetails(){return this.shippingDetails?{...this.shippingDetails}:null}getShippingAddress(){return this.shippingAddress?new D(this.shippingAddress.getDetails()):null}hasShippingAddress(){return !!this.shippingAddress}hasBillingAddress(){return !!this.billingAddress}getBillingAddress(){return this.billingAddress?new D(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(g=>g.getState()!=="CANCELLED"),i=e.reduce((g,T)=>g.add(T.getTotal().subtotal),t),o=new l({amount:this.shippingDetails?.cost||0,currency:this.currency}).round(),n=t,s={},d={};this.coupons.forEach(g=>{let T=g.calculateApplicableCouponDiscount(i,o,this.country,this.currency);n=n.add(T),s[g.getCode()]=T,g.getCategory()!=="SHIPPING"&&(d[g.getCode()]=T);}),this.applyDiscountsInLineItem(d);let u=e.reduce((g,T)=>g.add(T.getTotal().taxTotal),t),c=this.coupons.find(g=>g.getCategory()==="SHIPPING"),h=c?o.subtract(s[c.getCode()]||t):o,b=i.add(o).add(u).subtract(n);this.total={subtotal:i,shipping:o,effectiveShipping:h,couponTotal:s,couponDiscountTotal:n,taxTotal:u,grandTotal:b};}updateShippingDetails(t){this.shippingDetails=t,this.calculateTotals();}applyCoupons(t){let e=t.filter(o=>o.getCategory()==="SHIPPING"),i=t.filter(o=>o.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(o=>!o[1].isZero()),i=new Map;this.lineItems.forEach(o=>i.set(o.getId(),[])),e.forEach(([o,n])=>{let s=this.coupons.find(c=>c.getCode()===o);if(!s)return;let d=this.lineItems.filter(c=>c.getState()!=="CANCELLED"&&!c.getTotal().subtotal.isZero()).sort((c,h)=>c.getTotal().subtotal.compareTo(h.getTotal().subtotal)),u=new l({amount:0,currency:this.currency});d.forEach((c,h)=>{let b;h===d.length-1?b=n.subtract(u):b=n.multiply(c.getTotal().subtotal).divide(this.total.subtotal).round(),u=u.add(b),i.get(c.getId())?.push({coupon:s,amount:b});});}),this.lineItems.forEach(o=>{o.getState()==="CANCELLED"||this.total.subtotal.isZero()?o.updateDiscounts([]):o.updateDiscounts(i.get(o.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((n,s)=>{if(!n)return s;let d=s.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping),u=n.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);return d===u?s.getType()==="coupon"?s:n:d>u?s:n}),o=i.calculateApplicableCouponDiscount(e,this.total.shipping,this.country,this.currency).min(this.total.shipping);o.getAmount()>0&&(this.coupons.push(i),this.total.couponTotal[i.getCode()]=o,this.total.couponDiscountTotal=this.total.couponDiscountTotal.add(o),this.total.effectiveShipping=this.total.shipping.subtract(o));}}};var Tt=(o=>(o.ACTIVE="ACTIVE",o.FROZEN="FROZEN",o.MERGED="MERGED",o.ORDERED="ORDERED",o))(Tt||{}),At={expiresAtInSeconds:120*24*60*60},et=class extends N{state;expireAt;config;constructor(t,e=new Date,i=At){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.getSelectionAttribute(),o=A.generateSelectionAttributesKey(i),n=this.lineItems.findIndex(s=>s.getProductKey()===e&&A.generateSelectionAttributesKey(s.getSelectionAttribute())===o);return n>=0?this.lineItems[n].addSubItems(t.getSubItems(),!0):this.lineItems.push(t),this.calculateTotals(),n>=0?n:this.lineItems.length-1}updateLineItem(t,e,i){let o=this.lineItems,n=o.findIndex(s=>s.getId()===t);if(n<0)throw new L(t);return o[n].addSubItems([{size:e,quantity:i}],!1),this.calculateTotals(),n}removeLineItem(t){let i=this.lineItems.findIndex(o=>o.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=Tt;exports.DEFAULT_CART_CONFIG=At;exports.default=et;//# sourceMappingURL=Cart.js.map
|
|
2
2
|
//# sourceMappingURL=Cart.js.map
|