b23-lib 3.9.5 → 3.9.7

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.
Files changed (67) hide show
  1. package/dist/Auth/index.js +1 -1
  2. package/dist/Auth/index.js.map +1 -1
  3. package/dist/Auth/index.mjs +1 -1
  4. package/dist/Classes/Cart.d.mts +1 -1
  5. package/dist/Classes/Cart.d.ts +1 -1
  6. package/dist/Classes/Cart.js +1 -1
  7. package/dist/Classes/Cart.js.map +1 -1
  8. package/dist/Classes/Cart.mjs +1 -1
  9. package/dist/Classes/Charge.js +1 -1
  10. package/dist/Classes/Charge.js.map +1 -1
  11. package/dist/Classes/Charge.mjs +1 -1
  12. package/dist/Classes/Coupon.js +1 -1
  13. package/dist/Classes/Coupon.js.map +1 -1
  14. package/dist/Classes/Coupon.mjs +1 -1
  15. package/dist/Classes/Inventory.d.mts +1 -1
  16. package/dist/Classes/Inventory.d.ts +1 -1
  17. package/dist/Classes/Inventory.js +1 -1
  18. package/dist/Classes/Inventory.js.map +1 -1
  19. package/dist/Classes/Inventory.mjs +1 -1
  20. package/dist/Classes/Invoice.d.mts +1 -1
  21. package/dist/Classes/Invoice.d.ts +1 -1
  22. package/dist/Classes/LineItem.d.mts +1 -1
  23. package/dist/Classes/LineItem.d.ts +1 -1
  24. package/dist/Classes/LineItem.js +1 -1
  25. package/dist/Classes/LineItem.js.map +1 -1
  26. package/dist/Classes/LineItem.mjs +1 -1
  27. package/dist/Classes/Order.d.mts +1 -1
  28. package/dist/Classes/Order.d.ts +1 -1
  29. package/dist/Classes/Order.js +1 -1
  30. package/dist/Classes/Order.js.map +1 -1
  31. package/dist/Classes/Order.mjs +1 -1
  32. package/dist/Classes/Product.d.mts +1 -1
  33. package/dist/Classes/Product.d.ts +1 -1
  34. package/dist/Classes/Product.js +1 -1
  35. package/dist/Classes/Product.js.map +1 -1
  36. package/dist/Classes/Product.mjs +1 -1
  37. package/dist/Classes/ShoppingContainer.d.mts +1 -1
  38. package/dist/Classes/ShoppingContainer.d.ts +1 -1
  39. package/dist/Classes/ShoppingContainer.js +1 -1
  40. package/dist/Classes/ShoppingContainer.js.map +1 -1
  41. package/dist/Classes/ShoppingContainer.mjs +1 -1
  42. package/dist/Classes/TieredPrice.d.mts +1 -1
  43. package/dist/Classes/TieredPrice.d.ts +1 -1
  44. package/dist/Classes/TieredPrice.js +1 -1
  45. package/dist/Classes/TieredPrice.js.map +1 -1
  46. package/dist/Classes/TieredPrice.mjs +1 -1
  47. package/dist/{TieredPrice-CuMNmrzq.d.mts → TieredPrice-BMG5DJMm.d.mts} +8 -2
  48. package/dist/{TieredPrice-DhFaSgL8.d.ts → TieredPrice-CyJHtYB9.d.ts} +8 -2
  49. package/dist/{chunk-2A22PHHR.mjs → chunk-BUIVLPJZ.mjs} +2 -2
  50. package/dist/{chunk-2A22PHHR.mjs.map → chunk-BUIVLPJZ.mjs.map} +1 -1
  51. package/dist/chunk-JH55QR67.mjs +2 -0
  52. package/dist/chunk-JH55QR67.mjs.map +1 -0
  53. package/dist/{chunk-BHPYMPAX.mjs → chunk-OO7JQS5Z.mjs} +2 -2
  54. package/dist/{chunk-BHPYMPAX.mjs.map → chunk-OO7JQS5Z.mjs.map} +1 -1
  55. package/dist/{chunk-ORSFINNO.mjs → chunk-RHTYUZ7J.mjs} +2 -2
  56. package/dist/{chunk-ORSFINNO.mjs.map → chunk-RHTYUZ7J.mjs.map} +1 -1
  57. package/dist/{chunk-Z3IGFT5Q.mjs → chunk-VVW4UHMN.mjs} +2 -2
  58. package/dist/{chunk-Z3IGFT5Q.mjs.map → chunk-VVW4UHMN.mjs.map} +1 -1
  59. package/dist/index.d.mts +80 -77
  60. package/dist/index.d.ts +80 -77
  61. package/dist/index.js +2 -2
  62. package/dist/index.js.map +1 -1
  63. package/dist/index.mjs +2 -2
  64. package/dist/index.mjs.map +1 -1
  65. package/package.json +1 -1
  66. package/dist/chunk-E33TTQZM.mjs +0 -2
  67. package/dist/chunk-E33TTQZM.mjs.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/Classes/Coupon.ts"],"names":["CouponType","CouponDiscountMethod","CouponCategory","ApplicableTo","CouponModel","BaseModel","data","date","Utils_default","acc","country","priceData","PriceModel","InvalidArgumentError","locale","LocaleLanguageMap","priceModel","ftbCustomer","cartValue","shippingCost","currency","checkExpiry","zeroDiscount","potentialDiscount","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","targetValue","flatAmount"],"mappings":"uMAOO,IAAKA,CACVA,CAAAA,CAAAA,CAAAA,GAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,SAAY,CAAA,WAAA,CAFFA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CAKAC,OACVA,CAAA,CAAA,IAAA,CAAO,MACPA,CAAAA,CAAAA,CAAA,WAAa,YAFHA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,CAAA,CAAA,QAAA,CAAW,UACXA,CAAAA,CAAAA,CAAA,SAAW,UAFDA,CAAAA,CAAAA,CAAAA,EAAAA,CAAAA,EAAA,EAKAC,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,CAAAA,GACVA,EAAA,GAAM,CAAA,KAAA,CACNA,CAAA,CAAA,GAAA,CAAM,MAFIA,CAAA,CAAA,EAAA,CAAA,EAAA,EAAA,CAAA,CA0BSC,CAArB,CAAA,cAAyCC,GAAU,CACvC,UACA,CAAA,IAAA,CACA,YACA,IACA,CAAA,UAAA,CACA,SACA,CAAA,OAAA,CACA,aAGA,eAGA,CAAA,cAAA,CACA,eACA,CAAA,YAAA,CACA,SAOV,WAAYC,CAAAA,CAAAA,CAAuBC,CAAa,CAAA,IAAI,IAAQ,CAAA,CA0B1D,GAzBA,KAAA,CAAMD,EAAMC,CAAI,CAAA,CAEhB,IAAK,CAAA,UAAA,CAAaD,EAAK,UACvB,CAAA,IA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AEH,IAAME,CAAaJ,CAAAA,CAAAA,CACnBF,CAAoBK,CAAAA,CAAAA,CAAY,IAAIC,CAAU,CAAA,CAC9C,MACF,IAAK,aAEHN,CAAoBK,CAAAA,CAAAA,CAAY,QAAS,CAAA,IAAA,CAAK,oBAAuB,CAAA,GAAG,CAAE,CAAA,KAAA,GAC1E,MACF,QAEE,OAAON,CACX,CAKA,OAFsBC,CAAAA,CAAkB,GAAIE,CAAAA,CAAkB,CAGhE,CACF","file":"chunk-Z3IGFT5Q.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, CurrencyCode, ISODateTimeUTC, LocaleCode, LocalizedString, RegionalPrice } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\nimport { InvalidArgumentError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\n\r\nexport enum CouponType {\r\n COUPON = \"coupon\",\r\n AUTOMATIC = \"automatic\",\r\n}\r\n\r\nexport enum CouponDiscountMethod {\r\n FLAT = \"flat\",\r\n PERCENTAGE = \"percentage\",\r\n}\r\n\r\nexport enum CouponCategory {\r\n SHIPPING = \"SHIPPING\",\r\n CUSTOMER = \"CUSTOMER\",\r\n}\r\n\r\nexport enum ApplicableTo {\r\n ALL = \"all\",\r\n FTB = \"ftb\",\r\n}\r\n\r\nexport type CouponAttribute = BaseAttributes & {\r\n couponCode: string;\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n type: CouponType;\r\n customerId?: string;\r\n validFrom: ISODateTimeUTC;\r\n validTo: ISODateTimeUTC;\r\n minCartValue: RegionalPrice;\r\n maxCartDiscount: RegionalPrice;\r\n discountMethod: CouponDiscountMethod;\r\n percentageValue?: number;\r\n applicableTo: ApplicableTo;\r\n category: CouponCategory;\r\n};\r\n\r\nexport type CouponData = Required<CouponAttribute>\r\n\r\n/**\r\n * Represents a discount coupon, extending BaseModel.\r\n */\r\nexport default class CouponModel extends BaseModel {\r\n protected couponCode: string;\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected type: CouponType;\r\n protected customerId?: string;\r\n protected validFrom: ISODateTimeUTC;\r\n protected validTo: ISODateTimeUTC;\r\n protected minCartValue: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected maxCartDiscount: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected discountMethod: CouponDiscountMethod;\r\n protected percentageValue: number;\r\n protected applicableTo: ApplicableTo;\r\n protected category: CouponCategory;\r\n\r\n /**\r\n * Creates an instance of CouponModel.\r\n * @param data - The initial coupon attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: CouponAttribute, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.couponCode = data.couponCode;\r\n this.name = Utils.deepClone(data.name);\r\n this.description = Utils.deepClone(data.description);\r\n this.type = data.type;\r\n this.customerId = data.customerId;\r\n this.validFrom = data.validFrom && Date.parse(data.validFrom) ? new Date(data.validFrom).toISOString() : date.toISOString();\r\n this.validTo = data.validTo && Date.parse(data.validTo) ? new Date(data.validTo).toISOString() : date.toISOString();\r\n this.minCartValue = (Object.keys(data.minCartValue) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.minCartValue[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.maxCartDiscount = (Object.keys(data.maxCartDiscount) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.maxCartDiscount[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.discountMethod = data.discountMethod;\r\n this.percentageValue = data.percentageValue ?? 0;\r\n if (this.percentageValue > 100) {\r\n throw new InvalidArgumentError('Percentage value cannot be greater than 100');\r\n }\r\n\r\n this.applicableTo = data.applicableTo;\r\n this.category = data.category;\r\n }\r\n\r\n /** Gets the unique coupon code. */\r\n getCode(): string {\r\n return this.couponCode;\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the coupon name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon description object.\r\n * @returns A copy of the LocalizedString object for the description, or undefined.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the coupon description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /** Gets the type of coupon (COUPON or AUTOMATIC). */\r\n getType(): CouponType {\r\n return this.type;\r\n }\r\n\r\n /** Gets the specific customer ID this coupon is limited to, if any. */\r\n getCustomerId(): string {\r\n return this.customerId ?? '';\r\n }\r\n\r\n /** Gets the ISO date string from when the coupon is valid. */\r\n getValidFrom(): ISODateTimeUTC {\r\n return this.validFrom;\r\n }\r\n\r\n /** Gets the ISO date string until when the coupon is valid. */\r\n getValidTo(): ISODateTimeUTC {\r\n return this.validTo;\r\n }\r\n\r\n /**\r\n * Gets the list of minimum cart values required for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional minimum cart values.\r\n */\r\n getMinCartValue(): { [country in CountryCode]?: PriceModel }\r\n\r\n /**\r\n * Gets the minimum cart value required for the coupon for a specific country.\r\n * @param country - The country code to filter the minimum value for.\r\n * @returns The regional minimum cart value for the specified country, or undefined if not set for that country.\r\n */\r\n getMinCartValue(country: CountryCode): PriceModel | undefined\r\n getMinCartValue(country?: CountryCode) {\r\n if (country) {\r\n return this.minCartValue[country];\r\n }\r\n return { ...this.minCartValue };\r\n }\r\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): { [country in CountryCode]?: PriceModel }\r\n /**\r\n * Gets the maximum discount amount allowed for the coupon for a specific country.\r\n * @param country - The country code to filter the maximum discount for.\r\n * @returns The regional maximum discount cap for the specified country, or undefined if not set for that country.\r\n */\r\n getMaxCartDiscount(country: CountryCode): PriceModel | undefined\r\n getMaxCartDiscount(country?: CountryCode) {\r\n if (country) {\r\n return this.maxCartDiscount[country];\r\n }\r\n return { ...this.maxCartDiscount };\r\n }\r\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: (Object.keys(this.getMinCartValue()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMinCartValue(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n maxCartDiscount: (Object.keys(this.getMaxCartDiscount()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMaxCartDiscount(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n discountMethod: this.getDiscountMethod(),\r\n percentageValue: this.getPercentageValue(),\r\n applicableTo: this.getApplicableTo(),\r\n category: this.getCategory(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the coupon is currently active based on its validity dates.\r\n * @returns True if the coupon is currently within its validity period, false otherwise.\r\n */\r\n isActive(): boolean {\r\n return new Date(this.validFrom) <= new Date() && new Date(this.validTo) >= new Date();\r\n }\r\n\r\n\r\n /**\r\n * Checks if the coupon is applicable to a customer based on their status (e.g., first-time buyer).\r\n * @param ftbCustomer - A boolean indicating whether the customer is a first-time buyer.\r\n * @returns True if the coupon's applicability rule matches the customer's status, false otherwise.\r\n */\r\n isApplicableTo(ftbCustomer: boolean): boolean {\r\n return this.applicableTo === ApplicableTo.ALL || (this.applicableTo === ApplicableTo.FTB && ftbCustomer);\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param cartValue - The cart subtotal as a PriceModel.\r\n * @param shippingCost - The cart shipping cost.\r\n * @param country - The country code.\r\n * @param currency - The currency code.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(cartValue: PriceModel, shippingCost: PriceModel, country: CountryCode, currency: CurrencyCode, checkExpiry: boolean = true): PriceModel {\r\n let zeroDiscount: PriceModel = new PriceModel({ amount: 0, currency });\r\n let potentialDiscount: PriceModel;\r\n\r\n // 1. Basic validation (active)\r\n if (checkExpiry && !this.isActive()) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = this.getMinCartValue(country);\r\n const maxCartDiscountCap = this.getMaxCartDiscount(country);\r\n\r\n // If minCartValueReq is not set or the cart value is less than the minimum required, return zero discount\r\n if (!minCartValueReq || minCartValueReq.compareTo(cartValue) > 0) {\r\n return zeroDiscount;\r\n }\r\n\r\n // If maxCartDiscountCap is not set, return zero discount\r\n if (!maxCartDiscountCap) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = this.getCategory();\r\n const discountMethod = this.getDiscountMethod();\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? shippingCost : cartValue;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue.getAmount() <= 0) return zeroDiscount;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = targetValue.min(flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue.multiply(this.getPercentageValue() / 100).round();\r\n break;\r\n default:\r\n // Unknown discount method\r\n return zeroDiscount;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = potentialDiscount.min(maxCartDiscountCap);\r\n\r\n return finalDiscount;\r\n }\r\n}\r\n"]}
1
+ {"version":3,"sources":["../src/Classes/Coupon.ts"],"names":["CouponType","CouponDiscountMethod","CouponCategory","ApplicableTo","CouponModel","BaseModel","data","date","Utils_default","acc","country","priceData","PriceModel","InvalidArgumentError","locale","LocaleLanguageMap","priceModel","ftbCustomer","cartValue","shippingCost","currency","checkExpiry","zeroDiscount","potentialDiscount","minCartValueReq","maxCartDiscountCap","couponCategory","discountMethod","targetValue","flatAmount"],"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F","file":"chunk-VVW4UHMN.mjs","sourcesContent":["import Utils from \"../Utils\";\r\nimport BaseModel, { BaseAttributes } from \"./Base\";\r\nimport { CountryCode, CurrencyCode, ISODateTimeUTC, LocaleCode, LocalizedString, RegionalPrice } from \"./Common\";\r\nimport { LocaleLanguageMap } from \"./Enum\";\r\nimport { InvalidArgumentError } from \"./Error\";\r\nimport PriceModel, { PriceData } from \"./Price\";\r\n\r\nexport enum CouponType {\r\n COUPON = \"coupon\",\r\n AUTOMATIC = \"automatic\",\r\n}\r\n\r\nexport enum CouponDiscountMethod {\r\n FLAT = \"flat\",\r\n PERCENTAGE = \"percentage\",\r\n}\r\n\r\nexport enum CouponCategory {\r\n SHIPPING = \"SHIPPING\",\r\n CUSTOMER = \"CUSTOMER\",\r\n}\r\n\r\nexport enum ApplicableTo {\r\n ALL = \"all\",\r\n FTB = \"ftb\",\r\n}\r\n\r\nexport type CouponAttribute = BaseAttributes & {\r\n couponCode: string;\r\n name: LocalizedString;\r\n description: LocalizedString;\r\n type: CouponType;\r\n customerId?: string;\r\n validFrom: ISODateTimeUTC;\r\n validTo: ISODateTimeUTC;\r\n minCartValue: RegionalPrice;\r\n maxCartDiscount: RegionalPrice;\r\n discountMethod: CouponDiscountMethod;\r\n percentageValue?: number;\r\n applicableTo: ApplicableTo;\r\n category: CouponCategory;\r\n};\r\n\r\nexport type CouponData = Required<CouponAttribute>\r\n\r\n/**\r\n * Represents a discount coupon, extending BaseModel.\r\n */\r\nexport default class CouponModel extends BaseModel {\r\n protected couponCode: string;\r\n protected name: LocalizedString;\r\n protected description: LocalizedString;\r\n protected type: CouponType;\r\n protected customerId?: string;\r\n protected validFrom: ISODateTimeUTC;\r\n protected validTo: ISODateTimeUTC;\r\n protected minCartValue: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected maxCartDiscount: {\r\n [country in CountryCode]?: PriceModel;\r\n };\r\n protected discountMethod: CouponDiscountMethod;\r\n protected percentageValue: number;\r\n protected applicableTo: ApplicableTo;\r\n protected category: CouponCategory;\r\n\r\n /**\r\n * Creates an instance of CouponModel.\r\n * @param data - The initial coupon attributes.\r\n * @param date - Optional date for setting creation/modification times (defaults to now).\r\n */\r\n constructor(data: CouponAttribute, date: Date = new Date()) {\r\n super(data, date);\r\n\r\n this.couponCode = data.couponCode;\r\n this.name = Utils.deepClone(data.name);\r\n this.description = Utils.deepClone(data.description);\r\n this.type = data.type;\r\n this.customerId = data.customerId;\r\n this.validFrom = data.validFrom && Date.parse(data.validFrom) ? new Date(data.validFrom).toISOString() : date.toISOString();\r\n this.validTo = data.validTo && Date.parse(data.validTo) ? new Date(data.validTo).toISOString() : date.toISOString();\r\n this.minCartValue = (Object.keys(data.minCartValue) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.minCartValue[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.maxCartDiscount = (Object.keys(data.maxCartDiscount) as CountryCode[]).reduce((acc, country) => {\r\n const priceData = data.maxCartDiscount[country] as PriceData;\r\n if (priceData) {\r\n acc[country] = new PriceModel(priceData);\r\n }\r\n return acc;\r\n }, {} as { [country in CountryCode]?: PriceModel });\r\n this.discountMethod = data.discountMethod;\r\n this.percentageValue = data.percentageValue ?? 0;\r\n if (this.percentageValue > 100) {\r\n throw new InvalidArgumentError('Percentage value cannot be greater than 100');\r\n }\r\n\r\n this.applicableTo = data.applicableTo;\r\n this.category = data.category;\r\n }\r\n\r\n /** Gets the unique coupon code. */\r\n getCode(): string {\r\n return this.couponCode;\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon name object.\r\n * @returns A copy of the LocalizedString object for the name.\r\n */\r\n getName(): LocalizedString\r\n /**\r\n * Gets the coupon name for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The name string for the specified locale.\r\n */\r\n getName(locale: LocaleCode): string\r\n getName(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.name[locale] ?? this.name[LocaleLanguageMap[locale]] ?? this.name.en;\r\n } else {\r\n return { ...this.name };\r\n }\r\n }\r\n\r\n /**\r\n * Gets the full localized coupon description object.\r\n * @returns A copy of the LocalizedString object for the description, or undefined.\r\n */\r\n getDescription(): LocalizedString\r\n /**\r\n * Gets the coupon description for a specific locale, falling back to English ('en').\r\n * @param locale - The desired locale code.\r\n * @returns The description string for the specified locale.\r\n */\r\n getDescription(locale: LocaleCode): string\r\n getDescription(locale?: LocaleCode): LocalizedString | string {\r\n if (locale) {\r\n return this.description[locale] ?? this.description[LocaleLanguageMap[locale]] ?? this.description.en;\r\n } else {\r\n return { ...this.description };\r\n }\r\n }\r\n\r\n /** Gets the type of coupon (COUPON or AUTOMATIC). */\r\n getType(): CouponType {\r\n return this.type;\r\n }\r\n\r\n /** Gets the specific customer ID this coupon is limited to, if any. */\r\n getCustomerId(): string {\r\n return this.customerId ?? '';\r\n }\r\n\r\n /** Gets the ISO date string from when the coupon is valid. */\r\n getValidFrom(): ISODateTimeUTC {\r\n return this.validFrom;\r\n }\r\n\r\n /** Gets the ISO date string until when the coupon is valid. */\r\n getValidTo(): ISODateTimeUTC {\r\n return this.validTo;\r\n }\r\n\r\n /**\r\n * Gets the list of minimum cart values required for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional minimum cart values.\r\n */\r\n getMinCartValue(): { [country in CountryCode]?: PriceModel }\r\n\r\n /**\r\n * Gets the minimum cart value required for the coupon for a specific country.\r\n * @param country - The country code to filter the minimum value for.\r\n * @returns The regional minimum cart value for the specified country, or undefined if not set for that country.\r\n */\r\n getMinCartValue(country: CountryCode): PriceModel | undefined\r\n getMinCartValue(country?: CountryCode) {\r\n if (country) {\r\n return this.minCartValue[country];\r\n }\r\n return { ...this.minCartValue };\r\n }\r\n\r\n /**\r\n * Gets the list of maximum discount amounts allowed for the coupon across different regions.\r\n * Returns copies of the price objects.\r\n * @returns The full list of regional maximum discount caps.\r\n */\r\n getMaxCartDiscount(): { [country in CountryCode]?: PriceModel }\r\n /**\r\n * Gets the maximum discount amount allowed for the coupon for a specific country.\r\n * @param country - The country code to filter the maximum discount for.\r\n * @returns The regional maximum discount cap for the specified country, or undefined if not set for that country.\r\n */\r\n getMaxCartDiscount(country: CountryCode): PriceModel | undefined\r\n getMaxCartDiscount(country?: CountryCode) {\r\n if (country) {\r\n return this.maxCartDiscount[country];\r\n }\r\n return { ...this.maxCartDiscount };\r\n }\r\n\r\n /** Gets the discount method (FLAT or PERCENTAGE). */\r\n getDiscountMethod(): CouponDiscountMethod {\r\n return this.discountMethod;\r\n }\r\n\r\n /** Gets the percentage discount value (0-100). */\r\n getPercentageValue(): number {\r\n return this.percentageValue;\r\n }\r\n\r\n /** Gets the customer applicability rule (ALL or FTB). */\r\n getApplicableTo(): ApplicableTo {\r\n return this.applicableTo;\r\n }\r\n\r\n /** Gets the category of the coupon (SHIPPING or CUSTOMER). */\r\n getCategory(): CouponCategory {\r\n return this.category;\r\n }\r\n\r\n /**\r\n * Gets a plain data object representing the coupon's details.\r\n * @returns A CouponData object.\r\n */\r\n getDetails(): CouponData {\r\n return {\r\n ...super.getDetails(),\r\n couponCode: this.getCode(),\r\n name: this.getName(),\r\n description: this.getDescription(),\r\n type: this.getType(),\r\n customerId: this.getCustomerId(),\r\n validFrom: this.getValidFrom(),\r\n validTo: this.getValidTo(),\r\n minCartValue: (Object.keys(this.getMinCartValue()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMinCartValue(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n maxCartDiscount: (Object.keys(this.getMaxCartDiscount()) as CountryCode[]).reduce((acc, country) => {\r\n const priceModel = this.getMaxCartDiscount(country);\r\n if (priceModel) {\r\n acc[country] = priceModel.getDetails();\r\n }\r\n return acc;\r\n }, {} as RegionalPrice),\r\n discountMethod: this.getDiscountMethod(),\r\n percentageValue: this.getPercentageValue(),\r\n applicableTo: this.getApplicableTo(),\r\n category: this.getCategory(),\r\n };\r\n }\r\n\r\n /**\r\n * Checks if the coupon is currently active based on its validity dates.\r\n * @returns True if the coupon is currently within its validity period, false otherwise.\r\n */\r\n isActive(): boolean {\r\n return new Date(this.validFrom) <= new Date() && new Date(this.validTo) >= new Date();\r\n }\r\n\r\n\r\n /**\r\n * Checks if the coupon is applicable to a customer based on their status (e.g., first-time buyer).\r\n * @param ftbCustomer - A boolean indicating whether the customer is a first-time buyer.\r\n * @returns True if the coupon's applicability rule matches the customer's status, false otherwise.\r\n */\r\n isApplicableTo(ftbCustomer: boolean): boolean {\r\n return this.applicableTo === ApplicableTo.ALL || (this.applicableTo === ApplicableTo.FTB && ftbCustomer);\r\n }\r\n\r\n /**\r\n * Calculates the discount value for a given coupon based on the current container state.\r\n * Returns 0 if the coupon is invalid, expired, or not applicable based on cart value or target category.\r\n * @param cartValue - The cart subtotal as a PriceModel.\r\n * @param shippingCost - The cart shipping cost.\r\n * @param country - The country code.\r\n * @param currency - The currency code.\r\n * @returns The calculated discount amount (rounded according to country rules).\r\n */\r\n public calculateApplicableCouponDiscount(cartValue: PriceModel, shippingCost: PriceModel, country: CountryCode, currency: CurrencyCode, checkExpiry: boolean = true): PriceModel {\r\n let zeroDiscount: PriceModel = new PriceModel({ amount: 0, currency });\r\n let potentialDiscount: PriceModel;\r\n\r\n // 1. Basic validation (active)\r\n if (checkExpiry && !this.isActive()) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 2. Check regional requirements (min cart value, max discount)\r\n const minCartValueReq = this.getMinCartValue(country);\r\n const maxCartDiscountCap = this.getMaxCartDiscount(country);\r\n\r\n // If minCartValueReq is not set or the cart value is less than the minimum required, return zero discount\r\n if (!minCartValueReq || minCartValueReq.compareTo(cartValue) > 0) {\r\n return zeroDiscount;\r\n }\r\n\r\n // If maxCartDiscountCap is not set, return zero discount\r\n if (!maxCartDiscountCap) {\r\n return zeroDiscount;\r\n }\r\n\r\n // 3. Calculate potential discount based on method and category\r\n const couponCategory = this.getCategory();\r\n const discountMethod = this.getDiscountMethod();\r\n // Determine the value the coupon applies to (shipping cost or subtotal)\r\n const targetValue = couponCategory === CouponCategory.SHIPPING ? shippingCost : cartValue;\r\n\r\n // No discount if the target value is zero or less\r\n if (targetValue.getAmount() <= 0) return zeroDiscount;\r\n\r\n switch (discountMethod) {\r\n case CouponDiscountMethod.FLAT:\r\n // Flat discount is capped by the target value itself and the max discount cap\r\n const flatAmount = maxCartDiscountCap; // Use cap as the flat amount source? Or coupon.value? Needs clarification. Assuming cap IS the flat amount here.\r\n potentialDiscount = targetValue.min(flatAmount);\r\n break;\r\n case CouponDiscountMethod.PERCENTAGE:\r\n // Calculate percentage discount based on the target value\r\n potentialDiscount = targetValue.multiply(this.getPercentageValue() / 100).round();\r\n break;\r\n default:\r\n // Unknown discount method\r\n return zeroDiscount;\r\n }\r\n\r\n // 4. Apply maximum discount cap to the calculated potential discount\r\n const finalDiscount = potentialDiscount.min(maxCartDiscountCap);\r\n\r\n return finalDiscount;\r\n }\r\n}\r\n"]}
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { P as PricingType, S as SelectionAttributes } from './TieredPrice-CuMNmrzq.mjs';
1
+ import { P as PricingType, S as SelectionAttributes } from './TieredPrice-BMG5DJMm.mjs';
2
2
  import { ProductType, GenderCategory, OperationalCountry, OperationalCountryCurrency, OperationalLocale, OperationalLanguage } from './Classes/Enum.mjs';
3
3
  import './Price-DhE6HC9v.mjs';
4
4
  import './Classes/Base.mjs';
@@ -257,96 +257,99 @@ declare const Schema: {
257
257
  };
258
258
  };
259
259
  };
260
- TieredPriceSchema: {
261
- pricingType: {
262
- enum: PricingType[];
263
- };
264
- tier: {
265
- type: string;
266
- properties: {
267
- enabled: {
268
- type: string;
269
- };
270
- minQuantity: {
271
- type: string;
272
- minimum: number;
273
- };
274
- unitPrice: {
275
- $ref: string;
276
- };
260
+ getTieredPriceSchemaDefinition(): {
261
+ $id: string;
262
+ definitions: {
263
+ pricingType: {
264
+ enum: PricingType[];
277
265
  };
278
- required: string[];
279
- };
280
- volumeTieredPrice: {
281
- type: string;
282
- properties: {
283
- type: {
284
- const: PricingType;
285
- };
286
- currency: {
287
- $ref: string;
288
- };
289
- baseUnitPrice: {
290
- $ref: string;
291
- };
292
- taxCategory: {
293
- $ref: string;
294
- };
295
- isTaxInclusive: {
296
- type: string;
297
- };
298
- tiers: {
299
- type: string;
300
- items: {
266
+ tier: {
267
+ type: string;
268
+ properties: {
269
+ enabled: {
270
+ type: string;
271
+ };
272
+ minQuantity: {
273
+ type: string;
274
+ minimum: number;
275
+ };
276
+ unitPrice: {
301
277
  $ref: string;
302
278
  };
303
279
  };
280
+ required: string[];
304
281
  };
305
- required: string[];
306
- };
307
- selectionTieredPrice: {
308
- type: string;
309
- properties: {
310
- type: {
311
- const: PricingType;
312
- };
313
- currency: {
314
- $ref: string;
315
- };
316
- taxCategory: {
317
- $ref: string;
318
- };
319
- isTaxInclusive: {
320
- type: string;
282
+ volumeTieredPrice: {
283
+ type: string;
284
+ properties: {
285
+ type: {
286
+ const: PricingType;
287
+ };
288
+ currency: {
289
+ $ref: string;
290
+ };
291
+ baseUnitPrice: {
292
+ $ref: string;
293
+ };
294
+ taxCategory: {
295
+ $ref: string;
296
+ };
297
+ isTaxInclusive: {
298
+ type: string;
299
+ };
300
+ tiers: {
301
+ type: string;
302
+ items: {
303
+ $ref: string;
304
+ };
305
+ };
321
306
  };
322
- selections: {
323
- type: string;
324
- items: {
307
+ required: string[];
308
+ };
309
+ selectionTieredPrice: {
310
+ type: string;
311
+ properties: {
312
+ type: {
313
+ const: PricingType;
314
+ };
315
+ currency: {
316
+ $ref: string;
317
+ };
318
+ taxCategory: {
319
+ $ref: string;
320
+ };
321
+ isTaxInclusive: {
325
322
  type: string;
326
- properties: {
327
- selectionAttributes: {
328
- $ref: string;
329
- };
330
- baseUnitPrice: {
331
- $ref: string;
332
- };
333
- tiers: {
334
- type: string;
335
- items: {
323
+ };
324
+ selections: {
325
+ type: string;
326
+ items: {
327
+ type: string;
328
+ properties: {
329
+ selectionAttributes: {
330
+ $ref: string;
331
+ };
332
+ baseUnitPrice: {
336
333
  $ref: string;
337
334
  };
335
+ tiers: {
336
+ type: string;
337
+ items: {
338
+ $ref: string;
339
+ };
340
+ };
338
341
  };
342
+ required: string[];
339
343
  };
340
- required: string[];
341
344
  };
342
345
  };
346
+ required: string[];
347
+ };
348
+ tieredPrice: {
349
+ anyOf: {
350
+ $ref: string;
351
+ }[];
343
352
  };
344
- required: string[];
345
- };
346
- tieredPrice: {
347
- anyOf: {
348
- $ref: string;
349
- }[];
350
353
  };
351
354
  };
352
355
  };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { P as PricingType, S as SelectionAttributes } from './TieredPrice-DhFaSgL8.js';
1
+ import { P as PricingType, S as SelectionAttributes } from './TieredPrice-CyJHtYB9.js';
2
2
  import { ProductType, GenderCategory, OperationalCountry, OperationalCountryCurrency, OperationalLocale, OperationalLanguage } from './Classes/Enum.js';
3
3
  import './Price-CM028BEC.js';
4
4
  import './Classes/Base.js';
@@ -257,96 +257,99 @@ declare const Schema: {
257
257
  };
258
258
  };
259
259
  };
260
- TieredPriceSchema: {
261
- pricingType: {
262
- enum: PricingType[];
263
- };
264
- tier: {
265
- type: string;
266
- properties: {
267
- enabled: {
268
- type: string;
269
- };
270
- minQuantity: {
271
- type: string;
272
- minimum: number;
273
- };
274
- unitPrice: {
275
- $ref: string;
276
- };
260
+ getTieredPriceSchemaDefinition(): {
261
+ $id: string;
262
+ definitions: {
263
+ pricingType: {
264
+ enum: PricingType[];
277
265
  };
278
- required: string[];
279
- };
280
- volumeTieredPrice: {
281
- type: string;
282
- properties: {
283
- type: {
284
- const: PricingType;
285
- };
286
- currency: {
287
- $ref: string;
288
- };
289
- baseUnitPrice: {
290
- $ref: string;
291
- };
292
- taxCategory: {
293
- $ref: string;
294
- };
295
- isTaxInclusive: {
296
- type: string;
297
- };
298
- tiers: {
299
- type: string;
300
- items: {
266
+ tier: {
267
+ type: string;
268
+ properties: {
269
+ enabled: {
270
+ type: string;
271
+ };
272
+ minQuantity: {
273
+ type: string;
274
+ minimum: number;
275
+ };
276
+ unitPrice: {
301
277
  $ref: string;
302
278
  };
303
279
  };
280
+ required: string[];
304
281
  };
305
- required: string[];
306
- };
307
- selectionTieredPrice: {
308
- type: string;
309
- properties: {
310
- type: {
311
- const: PricingType;
312
- };
313
- currency: {
314
- $ref: string;
315
- };
316
- taxCategory: {
317
- $ref: string;
318
- };
319
- isTaxInclusive: {
320
- type: string;
282
+ volumeTieredPrice: {
283
+ type: string;
284
+ properties: {
285
+ type: {
286
+ const: PricingType;
287
+ };
288
+ currency: {
289
+ $ref: string;
290
+ };
291
+ baseUnitPrice: {
292
+ $ref: string;
293
+ };
294
+ taxCategory: {
295
+ $ref: string;
296
+ };
297
+ isTaxInclusive: {
298
+ type: string;
299
+ };
300
+ tiers: {
301
+ type: string;
302
+ items: {
303
+ $ref: string;
304
+ };
305
+ };
321
306
  };
322
- selections: {
323
- type: string;
324
- items: {
307
+ required: string[];
308
+ };
309
+ selectionTieredPrice: {
310
+ type: string;
311
+ properties: {
312
+ type: {
313
+ const: PricingType;
314
+ };
315
+ currency: {
316
+ $ref: string;
317
+ };
318
+ taxCategory: {
319
+ $ref: string;
320
+ };
321
+ isTaxInclusive: {
325
322
  type: string;
326
- properties: {
327
- selectionAttributes: {
328
- $ref: string;
329
- };
330
- baseUnitPrice: {
331
- $ref: string;
332
- };
333
- tiers: {
334
- type: string;
335
- items: {
323
+ };
324
+ selections: {
325
+ type: string;
326
+ items: {
327
+ type: string;
328
+ properties: {
329
+ selectionAttributes: {
330
+ $ref: string;
331
+ };
332
+ baseUnitPrice: {
336
333
  $ref: string;
337
334
  };
335
+ tiers: {
336
+ type: string;
337
+ items: {
338
+ $ref: string;
339
+ };
340
+ };
338
341
  };
342
+ required: string[];
339
343
  };
340
- required: string[];
341
344
  };
342
345
  };
346
+ required: string[];
347
+ };
348
+ tieredPrice: {
349
+ anyOf: {
350
+ $ref: string;
351
+ }[];
343
352
  };
344
- required: string[];
345
- };
346
- tieredPrice: {
347
- anyOf: {
348
- $ref: string;
349
- }[];
350
353
  };
351
354
  };
352
355
  };
package/dist/index.js CHANGED
@@ -1,3 +1,3 @@
1
- 'use strict';var de=require('crypto'),Ee=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var de__default=/*#__PURE__*/_interopDefault(de);var Ee__default=/*#__PURE__*/_interopDefault(Ee);var k=(e=>(e.IN="IN",e))(k||{}),O=(e=>(e.INR="INR",e))(O||{}),U=(r=>(r["en-IN"]="en-IN",r["kn-IN"]="kn-IN",r))(U||{}),R=(t=>(t.en="en",t.kn="kn",t))(R||{}),x={"en-IN":"en","kn-IN":"kn"};var re={INR:"\u20B9"},ie={INR:"en-IN"},q=(o=>(o.MALE="Male",o.FEMALE="Female",o.UNISEX="Unisex",o.KIDS="Kids",o.BOY="Boy",o.GIRL="Girl",o.GENERAL="General",o))(q||{});var F=(t=>(t.GOODS="GOODS",t.SERVICE="SERVICE",t))(F||{});var K=new Uint8Array(256),V=K.length;function G(){return V>K.length-16&&(de__default.default.randomFillSync(K),V=0),K.slice(V,V+=16)}var ne=/^(?:[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 pe(r){return typeof r=="string"&&ne.test(r)}var se=pe;var d=[];for(let r=0;r<256;++r)d.push((r+256).toString(16).slice(1));function B(r,e=0){return d[r[e+0]]+d[r[e+1]]+d[r[e+2]]+d[r[e+3]]+"-"+d[r[e+4]]+d[r[e+5]]+"-"+d[r[e+6]]+d[r[e+7]]+"-"+d[r[e+8]]+d[r[e+9]]+"-"+d[r[e+10]]+d[r[e+11]]+d[r[e+12]]+d[r[e+13]]+d[r[e+14]]+d[r[e+15]]}function ge(r){if(!se(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var oe=ge;function me(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var ye="6ba7b810-9dad-11d1-80b4-00c04fd430c8",fe="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function j(r,e,t){function i(n,s,c,o){var a;if(typeof n=="string"&&(n=me(n)),typeof s=="string"&&(s=oe(s)),((a=s)===null||a===void 0?void 0:a.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+n.length);if(l.set(s),l.set(n,s.length),l=t(l),l[6]=l[6]&15|e,l[8]=l[8]&63|128,c){o=o||0;for(let g=0;g<16;++g)c[o+g]=l[g];return c}return B(l)}try{i.name=r;}catch{}return i.DNS=ye,i.URL=fe,i}var Y={randomUUID:de__default.default.randomUUID};function be(r,e,t){if(Y.randomUUID&&!e&&!r)return Y.randomUUID();r=r||{};let i=r.random||(r.rng||G)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=i[n];return e}return B(i)}var H=be;function Te(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),de__default.default.createHash("sha1").update(r).digest()}var ae=Te;var Ae=j("v5",80,ae),W=Ae;var xe={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,e)=>e&&r?W(r,e):H(),generateSearchId:(r,e)=>`${r}#${m.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:m.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},p=xe;var ce=r=>structuredClone(r),J=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:ce(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return ce(this.customFields)}},D=class extends J{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.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(e,t,i,n){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:n};}};var z=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var h=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var _=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},w=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},P=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},N=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},M=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var v=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},I=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},b=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},y=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},L=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var T=class extends Error{constructor(e="Invalid pricing type."){super(`InvalidPricingType: ${e}`),this.name="InvalidPricingTypeError";}};var S=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new L("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw new L("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var A=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new v("Amount cannot be negative.");if(!e.currency)throw new I("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(r.getPrecisionPlaces(this.currency)));}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(e){return parseFloat(e.toFixed(r.getPrecisionPlaces(this.currency)))}compareTo(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot add prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot subtract prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot multiply prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new y("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot divide prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new y("Must be a positive number.")}min(...e){if(e.length===0)throw new y("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new y("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i},this)}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(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=ie[t];if(!t||!n)throw new I("Invalid currency code for formatting.");let s=e,c=i.displayAsInteger?0:r.getDecimalPlaces(t),o={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:c,maximumFractionDigits:c};i.displayAsInteger&&(s=Math.ceil(s));try{return new Intl.NumberFormat(n,o).format(s)}catch(a){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,a),`${re[t]??t} ${r.addThousandSeparators(s.toFixed(c))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let t=e.split("."),i=t[0],n=t.length>1?"."+t[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,t){if(e<0)throw new v("Amount cannot be negative for rounding.");if(t===void 0)throw new I("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}static getSmallestUnit(e){let t=r.getDecimalPlaces(e);return 1/Math.pow(10,t)}};var ee=(t=>(t.VOLUME="volume",t.SELECTION="selection",t))(ee||{}),E=class{type;taxCategory;isTaxInclusive;static create(e){return e.type==="selection"?new X(e):new Z(e)}constructor(e){if(!e.taxCategory)throw new _;this.taxCategory=e.taxCategory,this.isTaxInclusive=e.isTaxInclusive??!1,this.type=e.type??"volume";}getType(){return this.type}getTaxCategory(){return this.taxCategory}getIsTaxInclusive(){return this.isTaxInclusive}},Z=class extends E{baseUnitPrice;tiers;currency;constructor(e){if(super(e),this.type="volume",!e.baseUnitPrice)throw new P("Base unit price is required for volume pricing.");this.baseUnitPrice=new A(e.baseUnitPrice),this.currency=e.currency??this.baseUnitPrice.getCurrency();let t=(e.tiers??[]).map(o=>({enabled:o.enabled??!0,minQuantity:o.minQuantity,unitPrice:new A(o.unitPrice)})).sort((o,a)=>o.minQuantity-a.minQuantity);if(t.some(o=>o.minQuantity<=0))throw new w;let n=this.baseUnitPrice.getCurrency()!==this.currency||t.some(o=>o.unitPrice.getCurrency()!==this.currency),s=t.some((o,a)=>a>0&&o.unitPrice.compareTo(t[a-1].unitPrice)>0),c=t[0]?.unitPrice.compareTo(this.baseUnitPrice)>0;if(n||s||c)throw new P("Tiers must share the same currency and must not increase in unit price.");this.tiers=t;}isPriceAvailable(){return this.tiers.filter(e=>e.enabled).length>0}getBaseUnitPrice(){return this.baseUnitPrice}getCurrency(){return this.baseUnitPrice.getCurrency()}getApplicableUnitPrice(e){if(e<=0)throw new N;let t=this.tiers.filter(i=>i.enabled);for(let i=t.length-1;i>=0;i--){let n=t[i];if(e>=n.minQuantity)return n.unitPrice}throw new M(e)}getMinQuantity(){return this.tiers.filter(t=>t.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(){let e=this.tiers.filter(s=>s.enabled);if(!e.length)return 0;let t=Math.min(...e.map(s=>s.unitPrice.getAmount())),i=this.baseUnitPrice.getAmount(),n=(i-t)/i*100;return n>0?n:0}getTiers(){return this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,baseUnitPrice:this.baseUnitPrice.getDetails(),tiers:this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}},X=class extends E{currency;selections;constructor(e){super(e),this.type="selection",this.currency=e.currency,this.selections=(e.selections??[]).map(t=>{if(!t.baseUnitPrice)throw new P("Base unit price is required for each selection.");let i=new A(t.baseUnitPrice),n=(t.tiers??[]).map(l=>({enabled:l.enabled??!0,minQuantity:l.minQuantity??1,unitPrice:new A(l.unitPrice)})).sort((l,g)=>l.minQuantity-g.minQuantity);if(n.some(l=>l.minQuantity<=0))throw new w;let c=i.getCurrency()!==this.currency||n.some(l=>l.unitPrice.getCurrency()!==this.currency),o=n.some((l,g)=>g>0&&l.unitPrice.compareTo(n[g-1].unitPrice)>0),a=n[0]?.unitPrice.compareTo(i)>0;if(c||o||a)throw new P("Tiers must share the same currency and must not increase in unit price within the same selection.");return {selectionAttributes:{...t.selectionAttributes},baseUnitPrice:i,tiers:n}});}findMatch(e){let t=m.generateSelectionAttributesKey(e),i=this.selections.find(n=>m.generateSelectionAttributesKey(n.selectionAttributes)===t);if(!i)throw new P("No pricing configuration found for selection variant.");return i}isPriceAvailable(e){try{return e?this.findMatch(e).tiers.filter(t=>t.enabled).length>0:(console.warn("Selection attributes are required to check price availability for selection pricing."),!1)}catch{return !1}}getBaseUnitPrice(e){if(!e)throw new T("Selection attributes are required to get base unit price for selection pricing.");return this.findMatch(e).baseUnitPrice}getCurrency(){return this.currency}getApplicableUnitPrice(e,t){if(e<=0)throw new N;if(!t)throw new T("Selection attributes are required to get applicable unit price for selection pricing.");let n=this.findMatch(t).tiers.filter(s=>s.enabled);for(let s=n.length-1;s>=0;s--){let c=n[s];if(e>=c.minQuantity)return c.unitPrice}throw new M(e)}getMinQuantity(e){if(!e)throw new T("Selection attributes are required to get min quantity for selection pricing.");return this.findMatch(e).tiers.filter(n=>n.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(e){if(!e)throw new T("Selection attributes are required to get max discount for selection pricing.");let t=this.findMatch(e),i=t.tiers.filter(o=>o.enabled);if(!i.length)return 0;let n=Math.min(...i.map(o=>o.unitPrice.getAmount())),s=t.baseUnitPrice.getAmount(),c=(s-n)/s*100;return c>0?c:0}getTiers(e){if(!e)throw new T("Selection attributes are required to get tiers for selection pricing.");return this.findMatch(e).tiers.map(i=>({enabled:i.enabled,minQuantity:i.minQuantity,unitPrice:i.unitPrice}))}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,selections:this.selections.map(e=>({selectionAttributes:e.selectionAttributes,baseUnitPrice:e.baseUnitPrice.getDetails(),...e.tiers.length>0?{tiers:e.tiers.map(t=>({enabled:t.enabled,minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}:{}}))}}};var m=class r extends D{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;productType;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new h("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let n of i){let[s,c]=n.split(":");c.startsWith("c+")?t[s]={name:c.slice(2)}:t[s]=c;}return t}catch(t){throw new h(t?.message)}}constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((n,s)=>(e.pricing[s]&&(n[s]=E.create(e.pricing[s])),n),{}),this.targetGender=e.targetGender,this.attributes=p.deepClone(e.attributes),this.specifications=p.deepClone(e.specifications),this.categories=p.deepClone(e.categories),this.productType=e.productType??"GOODS";let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new h("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let s=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(s))throw new z(s);return i.add(s),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new S(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new S(c))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?p.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[x[e]]??this.name.en:p.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[x[e]]??this.description.en:p.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[x[e]]??this.slug.en:p.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return p.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:p.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=r.generateSelectionAttributesKey(e),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return p.deepClone(this.categories)}getProductType(){return this.productType}getSpecifications(e){return e?p.deepClone(this.specifications[e]??this.specifications[x[e]]??this.specifications.en):p.deepClone(this.specifications)}getSearchTags(e){return e?p.deepClone(this.searchTags[e]??this.searchTags[x[e]]??this.searchTags.en):p.deepClone(this.searchTags)}getDetails(){let e=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((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:p.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),productType:this.getProductType(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new h("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],n=e[t];if(n===void 0)throw new h(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new h(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new h(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(s=>s.name===n.name)<0)throw new h(`Selection attribute '${t}' is invalid`)}});}getSku(e){let t=r.generateSelectionAttributesKey(e);return this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t)?.sku}validateSelectionAttribute(e){let t=r.generateSelectionAttributesKey(e);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var ue={$id:"standards",definitions:{lowercaseText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]*$"},lowercaseText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,10}$"},lowercaseText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,16}$"},lowercaseText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,30}$"},lowercaseText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,50}$"},lowercaseText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,256}$"},text:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).*$"},text10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,10}$"},text16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,16}$"},text30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,30}$"},text50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,50}$"},text256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,256}$"},requiredText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).+$"},requiredText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,10}$"},requiredText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,16}$"},requiredText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,30}$"},requiredText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,50}$"},requiredText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,256}$"},url:{type:"string",pattern:"^https://[^\\s/$.?#].[^\\s]*$",maxLength:2048},uuid:{type:"string",minLength:1,pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},productKey:{type:"string",pattern:m.productKeyRegex.source},productSku:{type:"string",pattern:m.productSKURegex.source},productType:{type:"string",enum:Object.values(F)},genderCategory:{type:"string",enum:Object.values(q)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},additionalProperties:!1,required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hex:{type:"string"}},additionalProperties:!1,required:["name"]},attributeValue:{oneOf:[{type:"string"},{$ref:"#/definitions/color"}]},selectionAttributes:{type:"object",properties:{color:{$ref:"#/definitions/color"}},required:["color"],additionalProperties:{$ref:"#/definitions/attributeValue"}},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},company:{$ref:"#/definitions/text50"},phone:{type:"string",pattern:"^[0-9]{10}$"},e164Phone:{type:"string",pattern:"^\\+[1-9]\\d{1,14}$"},email:{type:"string",pattern:"^[^\\s]+@[^\\s]+\\.[^\\s]+$"},addressLine1:{$ref:"#/definitions/requiredText50"},addressLine2:{$ref:"#/definitions/text50"},city:{$ref:"#/definitions/requiredText30"},postalCode:{$ref:"#/definitions/requiredText16"},state:{type:"string",enum:["AP","AR","AS","BR","CT","GA","GJ","HR","HP","JH","KA","KL","MP","MH","MN","ML","MZ","NL","OR","PB","RJ","SK","TN","TG","TR","UP","UT","WB","AN","CH","DH","LD","DL","PY","LA","JK"]},country:{type:"string",enum:Object.values(k)},currency:{type:"string",enum:Object.values(O)},locale:{type:"string",enum:Object.values(U)},language:{type:"string",enum:Object.values(R)},localeOrLanguage:{type:"string",enum:[...Object.values(U),...Object.values(R)]},addressType:{type:"string",enum:["shipping","billing","billing&shipping"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},company:{$ref:"standards#/definitions/company"},phone:{$ref:"standards#/definitions/phone"},email:{$ref:"standards#/definitions/email"},addressLine1:{$ref:"standards#/definitions/addressLine1"},addressLine2:{$ref:"standards#/definitions/addressLine2"},city:{$ref:"standards#/definitions/city"},postalCode:{$ref:"standards#/definitions/postalCode"},state:{$ref:"standards#/definitions/state"},country:{$ref:"standards#/definitions/country"}},required:["firstName","lastName","phone","email","addressLine1","postalCode","state","country"]}}};var le={pricingType:{enum:Object.values(ee)},tier:{type:"object",properties:{enabled:{type:"boolean"},minQuantity:{type:"integer",minimum:1},unitPrice:{$ref:"standards#/definitions/price"}},required:["minQuantity","unitPrice"]},volumeTieredPrice:{type:"object",properties:{type:{const:"volume"},currency:{$ref:"standards#/definitions/currency"},baseUnitPrice:{$ref:"standards#/definitions/price"},taxCategory:{$ref:"standards#/definitions/requiredText"},isTaxInclusive:{type:"boolean"},tiers:{type:"array",items:{$ref:"#/definitions/tier"}}},required:["taxCategory","baseUnitPrice"]},selectionTieredPrice:{type:"object",properties:{type:{const:"selection"},currency:{$ref:"standards#/definitions/currency"},taxCategory:{$ref:"standards#/definitions/requiredText"},isTaxInclusive:{type:"boolean"},selections:{type:"array",items:{type:"object",properties:{selectionAttributes:{$ref:"standards#/definitions/selectionAttributes"},baseUnitPrice:{$ref:"standards#/definitions/price"},tiers:{type:"array",items:{$ref:"#/definitions/tier"}}},required:["selectionAttributes","baseUnitPrice"]}}},required:["type","taxCategory","currency"]},tieredPrice:{anyOf:[{$ref:"#/definitions/volumeTieredPrice"},{$ref:"#/definitions/selectionTieredPrice"}]}};var Ie={getStandardSchemaDefinition(){return ue},TieredPriceSchema:le},Se=Ie;var $=Object.freeze({INVALID_UUID:"Invalid UUID",INVALID_EMAIL:"Invalid Email",INVALID_TOKEN:"Invalid Token",TOKEN_EXPIRED:"Token Expired",INVALID_VERIFIER:"Invalid Verifier",INVALID_PERMISSIONS:"Invalid Permissions",INVALID_AUTH_TYPE:"Invalid Authorization Type",USER_PRIVATE_KEY_NOT_FOUND:"User Private Key Not Found",USER_PUBLIC_KEY_NOT_FOUND:"User Public Key Not Found",ANONYMOUS_PRIVATE_KEY_NOT_FOUND:"Anonymous Private Key Not Found",ANONYMOUS_PUBLIC_KEY_NOT_FOUND:"Anonymous Public Key Not Found",SYSTEM_PRIVATE_KEY_NOT_FOUND:"System Private Key Not Found",SYSTEM_PUBLIC_KEY_NOT_FOUND:"System Public Key Not Found",ADMIN_PRIVATE_KEY_NOT_FOUND:"Admin Private Key Not Found",ADMIN_PUBLIC_KEY_NOT_FOUND:"Admin Public Key Not Found",SECRET_TOKEN_NOT_FOUND:"Secret Token Not Found",ANONYMOUS_SESSION_NOT_ALLOWED:"Anonymous Session Not Allowed",USER_SESSION_NOT_ALLOWED:"User Session Not Allowed",SYSTEM_SESSION_NOT_ALLOWED:"System Session Not Allowed",CDN_SESSION_NOT_ALLOWED:"CDN Session Not Allowed",INTERNAL_SERVER_ERROR:"Internal Server Error",SOMETHING_WENT_WRONG:"Something went wrong",AUTH_CONTEXT_NOT_INITIALIZED:"Auth Context not Initialized"});var C={logException:(r,e)=>{console.error(`Exception Occurred in Function: ${r}, Error: ${C.inspect(e)}`);},logError:(r,e)=>{console.error(`Error Occurred in Function: ${r}, Error: ${C.inspect(e)}`);},logWarning:(r,e)=>{console.warn(`Warning in Function: ${r} - ${C.inspect(e)}`);},logMessage:(r,e)=>{console.log(`Message in Function: ${r} - ${C.inspect(e)}`);},logInvalidPayload:(r,e)=>{console.error(`Invalid Payload received for Function: ${r}, Error: ${C.inspect(e)}`);},inspect:r=>typeof r=="string"?r:Ee__default.default.inspect(r)},f=C;var Ce={handleException:(r,e,t)=>{e.knownError?(e.logError&&f.logError(r,e),t.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(f.logException(r,e),t.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(f.logException(r,e),t.status(500).json({status:500,error:$.INTERNAL_SERVER_ERROR}));},generateResponse:(r,e,t)=>({status:r,data:e,error:t}),generateError:(r,e,t=!0,i=!1)=>({status:r,error:e,knownError:t,logError:i})},De=Ce;var we=async(r,e,t="GET",i={},n)=>{let s={method:t,headers:{"Content-Type":"application/json",...i}};t!=="GET"&&n&&(s.body=JSON.stringify(n));let c=`${r}${e?"/"+e:""}`,o=c.includes("api.xetile.com")||c.includes("localhost");try{let a=await fetch(c,s);if(!a.ok){let g,Q=await a.text();try{g=JSON.parse(Q);}catch{g={status:a.status,error:Q||a.statusText},f.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${c}. Raw text: ${Q}`);}throw {status:a.status,statusText:a.statusText,error:g}}let l=await a.json();return f.logMessage("Fetch",`API call successful: URL-${c}, Status- ${a.status}`),{status:a.status,statusText:a.statusText,data:o?l.data:l}}catch(a){throw f.logError("Fetch",`API call failed: URL-${c}, Status- ${a.status||500}, Error- ${f.inspect(a.error||a)}`),{status:a.status||500,statusText:a.statusText||$.INTERNAL_SERVER_ERROR,error:a.error||{status:a.status||500,error:a.statusText||$.SOMETHING_WENT_WRONG}}}},Ne=we;var te=class{cache=new Map;maxSize;ttl;cleanupInterval;constructor(e=1e3,t=5*60*1e3){if(!Number.isFinite(e)||e<1)throw new RangeError("maxSize must be a finite number greater than or equal to 1.");if(!Number.isFinite(t)||t<1)throw new RangeError("ttl must be a finite number greater than or equal to 1.");this.maxSize=e,this.ttl=t,this.cleanupInterval=setInterval(()=>this.cleanup(),60*1e3),this.cleanupInterval.unref&&this.cleanupInterval.unref();}cleanup(){let e=Date.now();for(let[t,i]of this.cache.entries())e>=i.expiry&&this.cache.delete(t);}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i);}this.cache.set(e,{value:t,expiry:Date.now()+this.ttl});}get(e){let t=this.cache.get(e);if(t){if(Date.now()>=t.expiry){this.cache.delete(e);return}return this.cache.delete(e),f.logMessage("MemoryCache.get",`Successfully read cache data for key: ${e}`),this.cache.set(e,t),t.value}}dispose(){clearInterval(this.cleanupInterval);}},Me=te;
2
- exports.Fetch=Ne;exports.Logger=f;exports.MemoryCache=Me;exports.ResponseUtility=De;exports.Schema=Se;exports.Utils=p;//# sourceMappingURL=index.js.map
1
+ 'use strict';var de=require('crypto'),Ee=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var de__default=/*#__PURE__*/_interopDefault(de);var Ee__default=/*#__PURE__*/_interopDefault(Ee);var Q=(e=>(e.IN="IN",e))(Q||{}),O=(e=>(e.INR="INR",e))(O||{}),U=(r=>(r["en-IN"]="en-IN",r["kn-IN"]="kn-IN",r))(U||{}),R=(t=>(t.en="en",t.kn="kn",t))(R||{}),x={"en-IN":"en","kn-IN":"kn"};var re={INR:"\u20B9"},ie={INR:"en-IN"},k=(o=>(o.MALE="Male",o.FEMALE="Female",o.UNISEX="Unisex",o.KIDS="Kids",o.BOY="Boy",o.GIRL="Girl",o.GENERAL="General",o))(k||{});var F=(t=>(t.GOODS="GOODS",t.SERVICE="SERVICE",t))(F||{});var K=new Uint8Array(256),V=K.length;function G(){return V>K.length-16&&(de__default.default.randomFillSync(K),V=0),K.slice(V,V+=16)}var ne=/^(?:[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 pe(r){return typeof r=="string"&&ne.test(r)}var se=pe;var d=[];for(let r=0;r<256;++r)d.push((r+256).toString(16).slice(1));function B(r,e=0){return d[r[e+0]]+d[r[e+1]]+d[r[e+2]]+d[r[e+3]]+"-"+d[r[e+4]]+d[r[e+5]]+"-"+d[r[e+6]]+d[r[e+7]]+"-"+d[r[e+8]]+d[r[e+9]]+"-"+d[r[e+10]]+d[r[e+11]]+d[r[e+12]]+d[r[e+13]]+d[r[e+14]]+d[r[e+15]]}function ge(r){if(!se(r))throw TypeError("Invalid UUID");let e,t=new Uint8Array(16);return t[0]=(e=parseInt(r.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(r.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(r.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(r.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(r.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var oe=ge;function me(r){r=unescape(encodeURIComponent(r));let e=[];for(let t=0;t<r.length;++t)e.push(r.charCodeAt(t));return e}var ye="6ba7b810-9dad-11d1-80b4-00c04fd430c8",fe="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function j(r,e,t){function i(n,s,c,o){var a;if(typeof n=="string"&&(n=me(n)),typeof s=="string"&&(s=oe(s)),((a=s)===null||a===void 0?void 0:a.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+n.length);if(l.set(s),l.set(n,s.length),l=t(l),l[6]=l[6]&15|e,l[8]=l[8]&63|128,c){o=o||0;for(let g=0;g<16;++g)c[o+g]=l[g];return c}return B(l)}try{i.name=r;}catch{}return i.DNS=ye,i.URL=fe,i}var Y={randomUUID:de__default.default.randomUUID};function be(r,e,t){if(Y.randomUUID&&!e&&!r)return Y.randomUUID();r=r||{};let i=r.random||(r.rng||G)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let n=0;n<16;++n)e[t+n]=i[n];return e}return B(i)}var H=be;function Te(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),de__default.default.createHash("sha1").update(r).digest()}var ae=Te;var Ae=j("v5",80,ae),W=Ae;var xe={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,e)=>e&&r?W(r,e):H(),generateSearchId:(r,e)=>`${r}#${m.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:r=>{let[e,t]=r.split("#");return {key:e,selectionAttributes:m.parseSelectionAttributesKey(t)}},deepClone(r){return structuredClone(r)}},p=xe;var ce=r=>structuredClone(r),J=class{customFields;constructor(e,t=new Date){this.customFields={...e.customFields};}getCustomField(e){let t=this.customFields[e];return t==null?t:ce(t)}setCustomField(e,t){this.customFields[e]=t;}getAllCustomFields(){return ce(this.customFields)}},D=class extends J{version;createdAt;modifiedAt;modifiedBy;constructor(e,t=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():t.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():t.toISOString(),this.modifiedBy={...e.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(e,t,i,n){this.modifiedBy={id:e,authType:t,requestId:i,lambdaName:n};}};var z=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var h=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var _=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},w=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},T=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},M=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},N=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var v=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},I=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},b=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},y=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},$=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var P=class extends Error{constructor(e="Invalid pricing type."){super(`InvalidPricingType: ${e}`),this.name="InvalidPricingTypeError";}};var S=class{sources;alt;order;label;constructor(e){if(this.sources={...e.sources},this.alt=e.alt,this.order=e.order,this.label=e.label,!this.sources.original)throw new $("ImageInfoModel cannot be created without an 'original' source URL.")}getSources(){return {...this.sources}}getSource(e){return this.sources[e]||this.sources.original}getAlt(){return this.alt}getOrder(){return this.order}getLabel(){return this.label}setAlt(e){this.alt=e;}setOrder(e){this.order=e;}setLabel(e){this.label=e;}setSource(e,t){if(t===void 0){if(e==="original")throw new $("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=t;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var A=class r{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new v("Amount cannot be negative.");if(!e.currency)throw new I("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(r.getPrecisionPlaces(this.currency)));}get kind(){return this.#e}static isPriceModel(e){return typeof e=="object"&&e!==null&&e.kind==="PriceModel"}getCurrency(){return this.currency}getAmount(){return this.amount}getDetails(){return {amount:this.amount,currency:this.currency}}getPreciseAmount(e){return parseFloat(e.toFixed(r.getPrecisionPlaces(this.currency)))}compareTo(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot add prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot subtract prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return new r({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot multiply prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new r({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new y("Must be a non-negative number.")}divide(e){if(r.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new b("Cannot divide prices in different currencies.");return new r({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new r({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new y("Must be a positive number.")}min(...e){if(e.length===0)throw new y("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return t.compareTo(i)<0?t:i},this)}max(...e){if(e.length===0)throw new y("Must provide at least one PriceModel.");return e.reduce((t,i)=>{if(r.isPriceModel(i)){if(t.getCurrency()!==i.getCurrency())throw new b("Cannot compare prices in different currencies.")}else throw new y("Must be a PriceModel instance.");return t.compareTo(i)>0?t:i},this)}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(e,t,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=ie[t];if(!t||!n)throw new I("Invalid currency code for formatting.");let s=e,c=i.displayAsInteger?0:r.getDecimalPlaces(t),o={style:i.style??"currency",currency:t,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:c,maximumFractionDigits:c};i.displayAsInteger&&(s=Math.ceil(s));try{return new Intl.NumberFormat(n,o).format(s)}catch(a){return console.error(`Error formatting price for currency "${t}" and locale "${n}":`,a),`${re[t]??t} ${r.addThousandSeparators(s.toFixed(c))}`}}static getDecimalPlaces(e){switch(e){case"INR":default:return 2}}static getPrecisionPlaces(e){switch(e){case"INR":default:return 6}}static addThousandSeparators(e){let t=e.split("."),i=t[0],n=t.length>1?"."+t[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,t){if(e<0)throw new v("Amount cannot be negative for rounding.");if(t===void 0)throw new I("Invalid currency code for rounding.");let i=r.getDecimalPlaces(t),n=Math.pow(10,i);return Math.round(e*n)/n}static getSmallestUnit(e){let t=r.getDecimalPlaces(e);return 1/Math.pow(10,t)}};var ee=(t=>(t.VOLUME="volume",t.SELECTION="selection",t))(ee||{}),E=class{type;taxCategory;isTaxInclusive;static create(e){return e.type==="selection"?new X(e):new Z(e)}constructor(e){if(!e.taxCategory)throw new _;this.taxCategory=e.taxCategory,this.isTaxInclusive=e.isTaxInclusive??!1,this.type=e.type??"volume";}getType(){return this.type}getTaxCategory(){return this.taxCategory}getIsTaxInclusive(){return this.isTaxInclusive}},Z=class extends E{baseUnitPrice;tiers;currency;constructor(e){if(super(e),this.type="volume",!e.baseUnitPrice)throw new T("Base unit price is required for volume pricing.");this.baseUnitPrice=new A(e.baseUnitPrice),this.currency=e.currency??this.baseUnitPrice.getCurrency();let t=(e.tiers??[]).map(o=>({enabled:o.enabled??!0,minQuantity:o.minQuantity,unitPrice:new A(o.unitPrice)})).sort((o,a)=>o.minQuantity-a.minQuantity);if(t.some(o=>o.minQuantity<=0))throw new w;let n=this.baseUnitPrice.getCurrency()!==this.currency||t.some(o=>o.unitPrice.getCurrency()!==this.currency),s=t.some((o,a)=>a>0&&o.unitPrice.compareTo(t[a-1].unitPrice)>0),c=t[0]?.unitPrice.compareTo(this.baseUnitPrice)>0;if(n||s||c)throw new T("Tiers must share the same currency and must not increase in unit price.");this.tiers=t;}isPriceAvailable(){return this.tiers.filter(e=>e.enabled).length>0}getBaseUnitPrice(){return this.baseUnitPrice}getCurrency(){return this.baseUnitPrice.getCurrency()}getApplicableUnitPrice(e){if(e<=0)throw new M;let t=this.tiers.filter(i=>i.enabled);for(let i=t.length-1;i>=0;i--){let n=t[i];if(e>=n.minQuantity)return n.unitPrice}throw new N(e)}getMinQuantity(){return this.tiers.filter(t=>t.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(){let e=this.tiers.filter(s=>s.enabled);if(!e.length)return 0;let t=Math.min(...e.map(s=>s.unitPrice.getAmount())),i=this.baseUnitPrice.getAmount(),n=(i-t)/i*100;return n>0?n:0}getMinPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[e.length-1].unitPrice:null}getMaxPrice(){let e=this.tiers.filter(t=>t.enabled);return e.length?e[0].unitPrice:null}getTiers(){return this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,baseUnitPrice:this.baseUnitPrice.getDetails(),tiers:this.tiers.map(e=>({enabled:e.enabled,minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}},X=class extends E{currency;selections;constructor(e){super(e),this.type="selection",this.currency=e.currency,this.selections=(e.selections??[]).map(t=>{if(!t.baseUnitPrice)throw new T("Base unit price is required for each selection.");let i=new A(t.baseUnitPrice),n=(t.tiers??[]).map(l=>({enabled:l.enabled??!0,minQuantity:l.minQuantity??1,unitPrice:new A(l.unitPrice)})).sort((l,g)=>l.minQuantity-g.minQuantity);if(n.some(l=>l.minQuantity<=0))throw new w;let c=i.getCurrency()!==this.currency||n.some(l=>l.unitPrice.getCurrency()!==this.currency),o=n.some((l,g)=>g>0&&l.unitPrice.compareTo(n[g-1].unitPrice)>0),a=n[0]?.unitPrice.compareTo(i)>0;if(c||o||a)throw new T("Tiers must share the same currency and must not increase in unit price within the same selection.");return {selectionAttributes:{...t.selectionAttributes},baseUnitPrice:i,tiers:n}});}findMatch(e,t=!1){let i=m.generateSelectionAttributesKey(e),n=this.selections.find(s=>m.generateSelectionAttributesKey(s.selectionAttributes)===i);if(!n&&t)throw new T("No pricing configuration found for selection variant.");return n??null}isPriceAvailable(e){if(!e)return console.warn("Selection attributes are required to check price availability for selection pricing."),!1;let t=this.findMatch(e);return t?t.tiers.filter(i=>i.enabled).length>0:!1}getBaseUnitPrice(e){if(!e)throw new P("Selection attributes are required to get base unit price for selection pricing.");return this.findMatch(e,!0).baseUnitPrice}getCurrency(){return this.currency}getApplicableUnitPrice(e,t){if(e<=0)throw new M;if(!t)throw new P("Selection attributes are required to get applicable unit price for selection pricing.");let n=this.findMatch(t,!0).tiers.filter(s=>s.enabled);for(let s=n.length-1;s>=0;s--){let c=n[s];if(e>=c.minQuantity)return c.unitPrice}throw new N(e)}getMinQuantity(e){if(!e)throw new P("Selection attributes are required to get min quantity for selection pricing.");return this.findMatch(e,!0).tiers.filter(n=>n.enabled)[0]?.minQuantity??1}getMaxDiscountPercent(e){if(!e)throw new P("Selection attributes are required to get max discount for selection pricing.");let t=this.findMatch(e,!0),i=t.tiers.filter(o=>o.enabled);if(!i.length)return 0;let n=Math.min(...i.map(o=>o.unitPrice.getAmount())),s=t.baseUnitPrice.getAmount(),c=(s-n)/s*100;return c>0?c:0}getTiers(e){if(!e)throw new P("Selection attributes are required to get tiers for selection pricing.");return this.findMatch(e,!0).tiers.map(i=>({enabled:i.enabled,minQuantity:i.minQuantity,unitPrice:i.unitPrice}))}getMinPrice(e){if(!e)throw new P("Selection attributes are required to get min price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let i=t.tiers.filter(n=>n.enabled);return i.length?i[i.length-1].unitPrice:null}getMaxPrice(e){if(!e)throw new P("Selection attributes are required to get max price for selection pricing.");let t=this.findMatch(e);if(!t)return null;let i=t.tiers.filter(n=>n.enabled);return i.length?i[0].unitPrice:null}getDetails(){return {type:this.type,taxCategory:this.taxCategory,isTaxInclusive:this.isTaxInclusive,currency:this.currency,selections:this.selections.map(e=>({selectionAttributes:e.selectionAttributes,baseUnitPrice:e.baseUnitPrice.getDetails(),...e.tiers.length>0?{tiers:e.tiers.map(t=>({enabled:t.enabled,minQuantity:t.minQuantity,unitPrice:t.unitPrice.getDetails()}))}:{}}))}}};var m=class r extends D{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;productType;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new h("Selection attributes must be an object");return Object.keys(e).filter(i=>e[i]!==void 0&&i.toLowerCase()!=="size").sort().map(i=>e[i].name?`${i}:c+${e[i].name}`:`${i}:${e[i]}`).join("|").toLowerCase()}static parseSelectionAttributesKey(e){try{let t={},i=e.split("|");for(let n of i){let[s,c]=n.split(":");c.startsWith("c+")?t[s]={name:c.slice(2)}:t[s]=c;}return t}catch(t){throw new h(t?.message)}}constructor(e,t=new Date){super(e,t),this.id=e.id,this.key=e.key,this.name={...e.name},this.description={...e.description},this.slug={...e.slug},this.brand=e.brand,this.pricing=Object.keys(e.pricing).reduce((n,s)=>(e.pricing[s]&&(n[s]=E.create(e.pricing[s])),n),{}),this.targetGender=e.targetGender,this.attributes=p.deepClone(e.attributes),this.specifications=p.deepClone(e.specifications),this.categories=p.deepClone(e.categories),this.productType=e.productType??"GOODS";let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new h("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let s=r.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(s))throw new z(s);return i.add(s),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new S(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new S(c))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?p.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[x[e]]??this.name.en:p.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[x[e]]??this.description.en:p.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[x[e]]??this.slug.en:p.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return p.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:p.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let t=r.generateSelectionAttributesKey(e),i=this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,t){switch(t){case"PRIMARY":return this.getImagesBySelectionAttributes(e)?.primary??this.variants[0]?.images?.primary;case"GALLERY":return this.getImagesBySelectionAttributes(e)?.gallery??[];default:return this.getImagesBySelectionAttributes(e)??{primary:this.variants[0]?.images?.primary,gallery:[]}}}getIsActive(){return this.isActive}getTargetGender(){return this.targetGender}getCategories(){return p.deepClone(this.categories)}getProductType(){return this.productType}getSpecifications(e){return e?p.deepClone(this.specifications[e]??this.specifications[x[e]]??this.specifications.en):p.deepClone(this.specifications)}getSearchTags(e){return e?p.deepClone(this.searchTags[e]??this.searchTags[x[e]]??this.searchTags.en):p.deepClone(this.searchTags)}getDetails(){let e=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((t,i)=>(this.pricing[i]&&(t[i]=this.pricing[i]?.getDetails()),t),{}),attributes:this.getAttributes(),variants:this.variants.map(t=>({sku:t.sku,selectionAttributes:p.deepClone(t.selectionAttributes),images:{primary:t.images.primary.getDetails(),gallery:t.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),productType:this.getProductType(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new h("Selection attributes are required");Object.keys(this.attributes).forEach(t=>{if(t.toLowerCase()==="size")return;let i=this.attributes[t],n=e[t];if(n===void 0)throw new h(`Selection attribute '${t}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new h(`Selection attribute '${t}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new h(`Selection attribute '${t}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(s=>s.name===n.name)<0)throw new h(`Selection attribute '${t}' is invalid`)}});}getSku(e){let t=r.generateSelectionAttributesKey(e);return this.variants.find(n=>r.generateSelectionAttributesKey(n.selectionAttributes)===t)?.sku}validateSelectionAttribute(e){let t=r.generateSelectionAttributesKey(e);return this.variants.some(i=>r.generateSelectionAttributesKey(i.selectionAttributes)===t)}validateSize(e){return this.attributes.size.includes(e)}};var ue={$id:"standards",definitions:{lowercaseText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]*$"},lowercaseText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,10}$"},lowercaseText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,16}$"},lowercaseText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,30}$"},lowercaseText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,50}$"},lowercaseText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[a-z]{0,256}$"},text:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).*$"},text10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,10}$"},text16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,16}$"},text30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,30}$"},text50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,50}$"},text256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{0,256}$"},requiredText:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).+$"},requiredText10:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,10}$"},requiredText16:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,16}$"},requiredText30:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,30}$"},requiredText50:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,50}$"},requiredText256:{type:"string",pattern:"^(?!\\s)(?!.*\\s$).{1,256}$"},url:{type:"string",pattern:"^https://[^\\s/$.?#].[^\\s]*$",maxLength:2048},uuid:{type:"string",minLength:1,pattern:"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$"},productKey:{type:"string",pattern:m.productKeyRegex.source},productSku:{type:"string",pattern:m.productSKURegex.source},productType:{type:"string",enum:Object.values(F)},genderCategory:{type:"string",enum:Object.values(k)},price:{type:"object",properties:{amount:{type:"number",minimum:0},currency:{$ref:"#/definitions/currency"}},additionalProperties:!1,required:["amount","currency"]},color:{type:"object",properties:{name:{type:"string"},hex:{type:"string"}},additionalProperties:!1,required:["name"]},attributeValue:{oneOf:[{type:"string"},{$ref:"#/definitions/color"}]},selectionAttributes:{type:"object",properties:{color:{$ref:"#/definitions/color"}},required:["color"],additionalProperties:{$ref:"#/definitions/attributeValue"}},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},company:{$ref:"#/definitions/text50"},phone:{type:"string",pattern:"^[0-9]{10}$"},e164Phone:{type:"string",pattern:"^\\+[1-9]\\d{1,14}$"},email:{type:"string",pattern:"^[^\\s]+@[^\\s]+\\.[^\\s]+$"},addressLine1:{$ref:"#/definitions/requiredText50"},addressLine2:{$ref:"#/definitions/text50"},city:{$ref:"#/definitions/requiredText30"},postalCode:{$ref:"#/definitions/requiredText16"},state:{type:"string",enum:["AP","AR","AS","BR","CT","GA","GJ","HR","HP","JH","KA","KL","MP","MH","MN","ML","MZ","NL","OR","PB","RJ","SK","TN","TG","TR","UP","UT","WB","AN","CH","DH","LD","DL","PY","LA","JK"]},country:{type:"string",enum:Object.values(Q)},currency:{type:"string",enum:Object.values(O)},locale:{type:"string",enum:Object.values(U)},language:{type:"string",enum:Object.values(R)},localeOrLanguage:{type:"string",enum:[...Object.values(U),...Object.values(R)]},addressType:{type:"string",enum:["shipping","billing","billing&shipping"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},company:{$ref:"standards#/definitions/company"},phone:{$ref:"standards#/definitions/phone"},email:{$ref:"standards#/definitions/email"},addressLine1:{$ref:"standards#/definitions/addressLine1"},addressLine2:{$ref:"standards#/definitions/addressLine2"},city:{$ref:"standards#/definitions/city"},postalCode:{$ref:"standards#/definitions/postalCode"},state:{$ref:"standards#/definitions/state"},country:{$ref:"standards#/definitions/country"}},required:["firstName","lastName","phone","email","addressLine1","postalCode","state","country"]}}};var le={$id:"TieredPrices",definitions:{pricingType:{enum:Object.values(ee)},tier:{type:"object",properties:{enabled:{type:"boolean"},minQuantity:{type:"integer",minimum:1},unitPrice:{$ref:"standards#/definitions/price"}},required:["minQuantity","unitPrice"]},volumeTieredPrice:{type:"object",properties:{type:{const:"volume"},currency:{$ref:"standards#/definitions/currency"},baseUnitPrice:{$ref:"standards#/definitions/price"},taxCategory:{$ref:"standards#/definitions/requiredText"},isTaxInclusive:{type:"boolean"},tiers:{type:"array",items:{$ref:"TieredPrices#/definitions/tier"}}},required:["taxCategory","baseUnitPrice"]},selectionTieredPrice:{type:"object",properties:{type:{const:"selection"},currency:{$ref:"standards#/definitions/currency"},taxCategory:{$ref:"standards#/definitions/requiredText"},isTaxInclusive:{type:"boolean"},selections:{type:"array",items:{type:"object",properties:{selectionAttributes:{$ref:"standards#/definitions/selectionAttributes"},baseUnitPrice:{$ref:"standards#/definitions/price"},tiers:{type:"array",items:{$ref:"TieredPrices#/definitions/tier"}}},required:["selectionAttributes","baseUnitPrice"]}}},required:["type","taxCategory","currency"]},tieredPrice:{anyOf:[{$ref:"TieredPrices#/definitions/volumeTieredPrice"},{$ref:"TieredPrices#/definitions/selectionTieredPrice"}]}}};var Ie={getStandardSchemaDefinition(){return ue},getTieredPriceSchemaDefinition(){return le}},Se=Ie;var L=Object.freeze({INVALID_UUID:"Invalid UUID",INVALID_EMAIL:"Invalid Email",INVALID_TOKEN:"Invalid Token",TOKEN_EXPIRED:"Token Expired",INVALID_VERIFIER:"Invalid Verifier",INVALID_PERMISSIONS:"Invalid Permissions",INVALID_AUTH_TYPE:"Invalid Authorization Type",USER_PRIVATE_KEY_NOT_FOUND:"User Private Key Not Found",USER_PUBLIC_KEY_NOT_FOUND:"User Public Key Not Found",ANONYMOUS_PRIVATE_KEY_NOT_FOUND:"Anonymous Private Key Not Found",ANONYMOUS_PUBLIC_KEY_NOT_FOUND:"Anonymous Public Key Not Found",SYSTEM_PRIVATE_KEY_NOT_FOUND:"System Private Key Not Found",SYSTEM_PUBLIC_KEY_NOT_FOUND:"System Public Key Not Found",ADMIN_PRIVATE_KEY_NOT_FOUND:"Admin Private Key Not Found",ADMIN_PUBLIC_KEY_NOT_FOUND:"Admin Public Key Not Found",SECRET_TOKEN_NOT_FOUND:"Secret Token Not Found",ANONYMOUS_SESSION_NOT_ALLOWED:"Anonymous Session Not Allowed",USER_SESSION_NOT_ALLOWED:"User Session Not Allowed",SYSTEM_SESSION_NOT_ALLOWED:"System Session Not Allowed",CDN_SESSION_NOT_ALLOWED:"CDN Session Not Allowed",INTERNAL_SERVER_ERROR:"Internal Server Error",SOMETHING_WENT_WRONG:"Something went wrong",AUTH_CONTEXT_NOT_INITIALIZED:"Auth Context not Initialized"});var C={logException:(r,e)=>{console.error(`Exception Occurred in Function: ${r}, Error: ${C.inspect(e)}`);},logError:(r,e)=>{console.error(`Error Occurred in Function: ${r}, Error: ${C.inspect(e)}`);},logWarning:(r,e)=>{console.warn(`Warning in Function: ${r} - ${C.inspect(e)}`);},logMessage:(r,e)=>{console.log(`Message in Function: ${r} - ${C.inspect(e)}`);},logInvalidPayload:(r,e)=>{console.error(`Invalid Payload received for Function: ${r}, Error: ${C.inspect(e)}`);},inspect:r=>typeof r=="string"?r:Ee__default.default.inspect(r)},f=C;var Ce={handleException:(r,e,t)=>{e.knownError?(e.logError&&f.logError(r,e),t.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(f.logException(r,e),t.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(f.logException(r,e),t.status(500).json({status:500,error:L.INTERNAL_SERVER_ERROR}));},generateResponse:(r,e,t)=>({status:r,data:e,error:t}),generateError:(r,e,t=!0,i=!1)=>({status:r,error:e,knownError:t,logError:i})},De=Ce;var we=async(r,e,t="GET",i={},n)=>{let s={method:t,headers:{"Content-Type":"application/json",...i}};t!=="GET"&&n&&(s.body=JSON.stringify(n));let c=`${r}${e?"/"+e:""}`,o=c.includes("api.xetile.com")||c.includes("localhost");try{let a=await fetch(c,s);if(!a.ok){let g,q=await a.text();try{g=JSON.parse(q);}catch{g={status:a.status,error:q||a.statusText},f.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${c}. Raw text: ${q}`);}throw {status:a.status,statusText:a.statusText,error:g}}let l=await a.json();return f.logMessage("Fetch",`API call successful: URL-${c}, Status- ${a.status}`),{status:a.status,statusText:a.statusText,data:o?l.data:l}}catch(a){throw f.logError("Fetch",`API call failed: URL-${c}, Status- ${a.status||500}, Error- ${f.inspect(a.error||a)}`),{status:a.status||500,statusText:a.statusText||L.INTERNAL_SERVER_ERROR,error:a.error||{status:a.status||500,error:a.statusText||L.SOMETHING_WENT_WRONG}}}},Me=we;var te=class{cache=new Map;maxSize;ttl;cleanupInterval;constructor(e=1e3,t=5*60*1e3){if(!Number.isFinite(e)||e<1)throw new RangeError("maxSize must be a finite number greater than or equal to 1.");if(!Number.isFinite(t)||t<1)throw new RangeError("ttl must be a finite number greater than or equal to 1.");this.maxSize=e,this.ttl=t,this.cleanupInterval=setInterval(()=>this.cleanup(),60*1e3),this.cleanupInterval.unref&&this.cleanupInterval.unref();}cleanup(){let e=Date.now();for(let[t,i]of this.cache.entries())e>=i.expiry&&this.cache.delete(t);}set(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i);}this.cache.set(e,{value:t,expiry:Date.now()+this.ttl});}get(e){let t=this.cache.get(e);if(t){if(Date.now()>=t.expiry){this.cache.delete(e);return}return this.cache.delete(e),f.logMessage("MemoryCache.get",`Successfully read cache data for key: ${e}`),this.cache.set(e,t),t.value}}dispose(){clearInterval(this.cleanupInterval);}},Ne=te;
2
+ exports.Fetch=Me;exports.Logger=f;exports.MemoryCache=Ne;exports.ResponseUtility=De;exports.Schema=Se;exports.Utils=p;//# sourceMappingURL=index.js.map
3
3
  //# sourceMappingURL=index.js.map