b23-lib 3.3.0 → 3.3.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Classes/Cart.d.mts +3 -1
- package/dist/Classes/Cart.d.ts +3 -1
- package/dist/Classes/Cart.js +1 -1
- package/dist/Classes/Cart.js.map +1 -1
- package/dist/Classes/Cart.mjs +1 -1
- package/dist/Classes/Cart.mjs.map +1 -1
- package/dist/index.js +2 -2
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1 -1
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/dist/Classes/Cart.mjs
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import {a}from'../chunk-3TUSUSXQ.mjs';import'../chunk-B2VFJRLS.mjs';import'../chunk-HX32EJ3F.mjs';import'../chunk-G6LH7V5B.mjs';import'../chunk-SOZHGHMY.mjs';import'../chunk-RQ2FFWUW.mjs';import {b}from'../chunk-MHLRJ4IJ.mjs';import'../chunk-FCRJAAPY.mjs';import'../chunk-2B2XI6FG.mjs';import'../chunk-LI5JQ6UC.mjs';import'../chunk-QK4XJ3GB.mjs';import {a as a$1}from'../chunk-R5DM7WCD.mjs';import'../chunk-UXZBULDS.mjs';var
|
|
1
|
+
import {a}from'../chunk-3TUSUSXQ.mjs';import'../chunk-B2VFJRLS.mjs';import'../chunk-HX32EJ3F.mjs';import'../chunk-G6LH7V5B.mjs';import'../chunk-SOZHGHMY.mjs';import'../chunk-RQ2FFWUW.mjs';import {b}from'../chunk-MHLRJ4IJ.mjs';import'../chunk-FCRJAAPY.mjs';import'../chunk-2B2XI6FG.mjs';import'../chunk-LI5JQ6UC.mjs';import'../chunk-QK4XJ3GB.mjs';import {a as a$1}from'../chunk-R5DM7WCD.mjs';import'../chunk-UXZBULDS.mjs';var p=(i=>(i.ACTIVE="ACTIVE",i.FROZEN="FROZEN",i.MERGED="MERGED",i.ORDERED="ORDERED",i))(p||{}),h={expiresAtInSeconds:120*24*60*60},c=class extends a{state;expireAt;config;constructor(t,e=new Date,r=h){super(t,e),this.state=t.state,this.expireAt=t.expireAt&&typeof t.expireAt=="number"?t.expireAt:Math.floor(e.getTime()/1e3)+r.expiresAtInSeconds,this.config=r;}getState(){return this.state}getExpireAt(){return this.expireAt}isActive(){let t=Math.ceil(Date.now()/1e3);return this.state==="ACTIVE"&&this.expireAt>t}clearCartItems(){this.lineItems=[],this.charges=[],this.coupons=[],this.shippingDetails=null,this.calculateTotals();}validateLineItems(t){this.lineItems=this.lineItems.map(e=>{try{e.updateProductData(t[e.getProductKey()],this.country,this.currency);}catch(r){console.error(`Error recalculating line item ${e.getId()}:`,r),e.clearLineItem();}return e}).filter(e=>e.getId()),this.calculateTotals();}addLineItem(t,e){let r=t.getProductKey(),i=t.getSelectionAttributes(),n=b.generateSelectionAttributesKey(i),s=this.lineItems.findIndex(l=>l.getProductKey()===r&&b.generateSelectionAttributesKey(l.getSelectionAttributes())===n);return s>=0?this.lineItems[s].addSubItems(t.getSubItems(),e):this.lineItems.push(t),this.calculateTotals(),s>=0?s:this.lineItems.length-1}updateLineItem(t,e,r){let i=this.lineItems,n=i.findIndex(s=>s.getId()===t);if(n<0)throw new a$1(t);return i[n].addSubItems([{size:e,quantity:r}],!1),this.calculateTotals(),n}removeLineItem(t){let r=this.lineItems.findIndex(i=>i.getId()===t);if(r<0)throw new a$1(t);return this.lineItems.splice(r,1),this.charges=this.charges.filter(i=>i.getLineItemId()!==t),this.calculateTotals(),r}getDetails(){return {...super.getDetails(),state:this.getState(),expireAt:this.getExpireAt()}}};export{p as CartState,h as DEFAULT_CART_CONFIG,c as default};//# sourceMappingURL=Cart.mjs.map
|
|
2
2
|
//# sourceMappingURL=Cart.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/Classes/Cart.ts"],"names":["CartState","DEFAULT_CART_CONFIG","CartModel","BaseShoppingContainerModel","data","date","config","nowSeconds","products","lineItem","error","newLineItem","productKey","selectionAttributes","selectionAttributeKey","ProductModel","index","item","lineItemId","size","quantity","lineItems","LineItemNotFoundError","charge"],"mappings":"qaAKO,IAAKA,OACVA,CAAA,CAAA,MAAA,CAAS,QACTA,CAAAA,CAAAA,CAAA,OAAS,QACTA,CAAAA,CAAAA,CAAA,MAAS,CAAA,QAAA,CACTA,EAAA,OAAU,CAAA,SAAA,CAJAA,OAAA,EAwBCC,CAAAA,CAAAA,CAAAA,CAAkC,CAC7C,kBAAoB,CAAA,GAAA,CAAM,EAAK,CAAA,EAAA,CAAK,EACtC,CAEqBC,CAAAA,CAAAA,CAArB,cAAuCC,CAA2B,CACtD,MACA,QACA,CAAA,MAAA,CAEV,WAAYC,CAAAA,CAAAA,CAAsBC,EAAa,IAAI,IAAA,CAAQC,EAAqBL,CAAqB,CAAA,CACnG,MAAMG,CAAMC,CAAAA,CAAI,CAChB,CAAA,IAAA,CAAK,MAAQD,CAAK,CAAA,KAAA,CAClB,KAAK,QAAWA,CAAAA,CAAAA,CAAK,UAAY,OAAOA,CAAAA,CAAK,QAAa,EAAA,QAAA,CAAWA,EAAK,QAAW,CAAA,IAAA,CAAK,MAAMC,CAAK,CAAA,OAAA,GAAY,GAAI,CAAA,CAAIC,CAAO,CAAA,kBAAA,CAChI,KAAK,MAASA,CAAAA,EAChB,CAMO,QAAsB,EAAA,CAC3B,OAAO,IAAK,CAAA,KACd,CAMO,WAAA,EAAsB,CAC3B,OAAO,IAAA,CAAK,QACd,CAMO,QAAA,EAAoB,CACzB,IAAMC,CAAAA,CAAa,IAAK,CAAA,IAAA,CAAK,KAAK,GAAI,EAAA,CAAI,GAAI,CAAA,
|
|
1
|
+
{"version":3,"sources":["../../src/Classes/Cart.ts"],"names":["CartState","DEFAULT_CART_CONFIG","CartModel","BaseShoppingContainerModel","data","date","config","nowSeconds","products","lineItem","error","newLineItem","addQuantity","productKey","selectionAttributes","selectionAttributeKey","ProductModel","index","item","lineItemId","size","quantity","lineItems","LineItemNotFoundError","charge"],"mappings":"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","file":"Cart.mjs","sourcesContent":["import { LineItemNotFoundError } from \"./Error\";\r\nimport LineItemModel from \"./LineItem\";\r\nimport ProductModel from \"./Product\";\r\nimport BaseShoppingContainerModel, { BaseShoppingContainerAttributes, BaseShoppingContainerData } from \"./ShoppingContainer\";\r\n\r\nexport enum CartState {\r\n ACTIVE = \"ACTIVE\",\r\n FROZEN = \"FROZEN\",\r\n MERGED = \"MERGED\",\r\n ORDERED = \"ORDERED\"\r\n}\r\n\r\n/**\r\n * Input attributes for creating or updating a CartModel.\r\n */\r\nexport type CartAttributes = BaseShoppingContainerAttributes & {\r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartData = BaseShoppingContainerData & {\r\n state: CartState;\r\n expireAt: number;\r\n};\r\n\r\nexport type CartConfig = {\r\n expiresAtInSeconds: number;\r\n}\r\n\r\nexport const DEFAULT_CART_CONFIG: CartConfig = {\r\n expiresAtInSeconds: 120 * 24 * 60 * 60\r\n}\r\n\r\nexport default class CartModel extends BaseShoppingContainerModel {\r\n protected state: CartState;\r\n protected expireAt: number;\r\n protected config: CartConfig;\r\n\r\n constructor(data: CartAttributes, date: Date = new Date(), config: CartConfig = DEFAULT_CART_CONFIG) {\r\n super(data, date);\r\n this.state = data.state;\r\n this.expireAt = data.expireAt && typeof data.expireAt === 'number' ? data.expireAt : Math.floor(date.getTime() / 1000) + config.expiresAtInSeconds;\r\n this.config = config;\r\n }\r\n\r\n /**\r\n * Gets the current state of the cart (e.g., ACTIVE, ORDERED).\r\n * @returns The CartState enum value.\r\n */\r\n public getState(): CartState {\r\n return this.state;\r\n }\r\n\r\n /**\r\n * Gets the timestamp when the cart expires.\r\n * @returns The expiration timestamp in seconds (Unix epoch).\r\n */\r\n public getExpireAt(): number {\r\n return this.expireAt;\r\n }\r\n\r\n /**\r\n * Checks if the cart is currently active and not expired.\r\n * @returns True if active and not expired, false otherwise.\r\n */\r\n public isActive(): boolean {\r\n const nowSeconds = Math.ceil(Date.now() / 1000);\r\n return this.state === CartState.ACTIVE && (this.expireAt > nowSeconds);\r\n }\r\n\r\n /**\r\n * Clears all line items, coupons, and shipping details from the cart and resets totals.\r\n */\r\n public clearCartItems() {\r\n this.lineItems = [];\r\n this.charges = [];\r\n this.coupons = [];\r\n this.shippingDetails = null;\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Validates line items against the current product catalog.\r\n * Updates product data for each item and removes invalid items.\r\n * @param products - A record map of ProductModels keyed by product ID/key.\r\n */\r\n public validateLineItems(products: Record<string, ProductModel>): void {\r\n this.lineItems = this.lineItems.map(lineItem => {\r\n try {\r\n lineItem.updateProductData(products[lineItem.getProductKey()], this.country, this.currency);\r\n } catch (error) {\r\n console.error(`Error recalculating line item ${lineItem.getId()}:`, error);\r\n lineItem.clearLineItem();\r\n }\r\n return lineItem;\r\n }).filter(lineItem => lineItem.getId());\r\n\r\n this.calculateTotals();\r\n }\r\n\r\n /**\r\n * Adds a new line item or updates the quantity of an existing one.\r\n * @param newLineItem The LineItemModel to add.\r\n * @param addQuantity If true, adds the quantity from `subItem` to the existing quantity.\r\n * If false, replaces the existing quantity with the one from `subItem`.\r\n * @returns The index of the added/updated line item in the internal array.\r\n */\r\n public addLineItem(newLineItem: LineItemModel, addQuantity: boolean) {\r\n const productKey = newLineItem.getProductKey();\r\n const selectionAttributes = newLineItem.getSelectionAttributes();\r\n const selectionAttributeKey = ProductModel.generateSelectionAttributesKey(selectionAttributes);\r\n let index = this.lineItems.findIndex(\r\n (item) => item.getProductKey() === productKey && ProductModel.generateSelectionAttributesKey(item.getSelectionAttributes()) === selectionAttributeKey\r\n );\r\n\r\n if (index >= 0) {\r\n this.lineItems[index].addSubItems(newLineItem.getSubItems(), addQuantity);\r\n } else {\r\n this.lineItems.push(newLineItem);\r\n }\r\n\r\n this.calculateTotals();\r\n return index >= 0 ? index : this.lineItems.length - 1;\r\n }\r\n\r\n /**\r\n * Updates the quantity for a specific size within a line item.\r\n * @param lineItemId The ID of the LineItemModel to update.\r\n * @param size The size identifier within the line item.\r\n * @param quantity The new quantity for the size (0 to remove).\r\n * @returns The index of the updated line item.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public updateLineItem(lineItemId: string, size: string, quantity: number) {\r\n const lineItems = this.lineItems;\r\n let index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n\r\n if (index < 0) {\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n lineItems[index].addSubItems([{ size, quantity }], false);\r\n this.calculateTotals();\r\n\r\n return index;\r\n }\r\n\r\n /**\r\n * Removes a line item completely from the cart.\r\n * @param lineItemId The ID of the LineItemModel to remove.\r\n * @returns The index the item previously occupied.\r\n * @throws {Error} If the line item is not found.\r\n */\r\n public removeLineItem(lineItemId: string) {\r\n const lineItems = this.lineItems;\r\n const index = lineItems.findIndex((item) => item.getId() === lineItemId);\r\n\r\n if (index < 0) {\r\n throw new LineItemNotFoundError(lineItemId);\r\n }\r\n\r\n this.lineItems.splice(index, 1);\r\n this.charges = this.charges.filter(charge => charge.getLineItemId() !== lineItemId);\r\n this.calculateTotals();\r\n\r\n return index;\r\n }\r\n\r\n getDetails(): CartData {\r\n return {\r\n ...super.getDetails(),\r\n state: this.getState(),\r\n expireAt: this.getExpireAt(),\r\n }\r\n }\r\n}\r\n"]}
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
'use strict';var se=require('crypto'),Ae=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var se__default=/*#__PURE__*/_interopDefault(se);var Ae__default=/*#__PURE__*/_interopDefault(Ae);var V=(e=>(e.IN="IN",e))(V||{}),D=(e=>(e.INR="INR",e))(D||{}),w=(t=>(t["en-IN"]="en-IN",t["kn-IN"]="kn-IN",t))(w||{}),v=(r=>(r.en="en",r.kn="kn",r))(v||{}),A={"en-IN":"en","kn-IN":"kn"};var J={INR:"\u20B9"},Z={INR:"en-IN"},k=(l=>(l.MALE="Male",l.FEMALE="Female",l.UNISEX="Unisex",l.KIDS="Kids",l.BOY="Boy",l.GIRL="Girl",l.GENERAL="General",l))(k||{});var M=new Uint8Array(256),$=M.length;function G(){return $>M.length-16&&(se__default.default.randomFillSync(M),$=0),M.slice($,$+=16)}var X=/^(?:[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 oe(t){return typeof t=="string"&&X.test(t)}var ee=oe;var d=[];for(let t=0;t<256;++t)d.push((t+256).toString(16).slice(1));function L(t,e=0){return d[t[e+0]]+d[t[e+1]]+d[t[e+2]]+d[t[e+3]]+"-"+d[t[e+4]]+d[t[e+5]]+"-"+d[t[e+6]]+d[t[e+7]]+"-"+d[t[e+8]]+d[t[e+9]]+"-"+d[t[e+10]]+d[t[e+11]]+d[t[e+12]]+d[t[e+13]]+d[t[e+14]]+d[t[e+15]]}function ae(t){if(!ee(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var te=ae;function ce(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var ue="6ba7b810-9dad-11d1-80b4-00c04fd430c8",le="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function j(t,e,r){function i(n,o,c,l){var s;if(typeof n=="string"&&(n=ce(n)),typeof o=="string"&&(o=te(o)),((s=o)===null||s===void 0?void 0:s.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+n.length);if(u.set(o),u.set(n,o.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,c){l=l||0;for(let b=0;b<16;++b)c[l+b]=u[b];return c}return L(u)}try{i.name=t;}catch{}return i.DNS=ue,i.URL=le,i}var Q={randomUUID:se__default.default.randomUUID};function pe(t,e,r){if(Q.randomUUID&&!e&&!t)return Q.randomUUID();t=t||{};let i=t.random||(t.rng||G)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){r=r||0;for(let n=0;n<16;++n)e[r+n]=i[n];return e}return L(i)}var q=pe;function me(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),se__default.default.createHash("sha1").update(t).digest()}var re=me;var fe=j("v5",80,re),Y=fe;var ye={isUUID:t=>/^[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(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?Y(t,e):q(),generateSearchId:(t,e)=>`${t}#${h.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttributes:h.parseSelectionAttributesKey(r)}},deepClone(t){return structuredClone(t)}},p=ye;var ie=t=>structuredClone(t),H=class{customFields;constructor(e,r=new Date){this.customFields={...e.customFields};}getCustomField(e){let r=this.customFields[e];return r==null?r:ie(r)}setCustomField(e,r){this.customFields[e]=r;}getAllCustomFields(){return ie(this.customFields)}},P=class extends H{version;createdAt;modifiedAt;modifiedBy;constructor(e,r=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():r.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():r.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,r,i,n){this.modifiedBy={id:e,authType:r,requestId:i,lambdaName:n};}};var R=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var m=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var O=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},U=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},F=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},z=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},_=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var C=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},x=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},f=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},g=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},E=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var I=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 E("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,r){if(r===void 0){if(e==="original")throw new E("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=r;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var T=class t{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new C("Amount cannot be negative.");if(!e.currency)throw new x("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(t.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(t.getPrecisionPlaces(this.currency)))}compareTo(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot add prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return new t({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot subtract prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return new t({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot multiply prices in different currencies.");return new t({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new t({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new g("Must be a non-negative number.")}divide(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new f("Cannot divide prices in different currencies.");return new t({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new t({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new g("Must be a positive number.")}min(...e){if(e.length===0)throw new g("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(t.isPriceModel(i)){if(r.getCurrency()!==i.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return r.compareTo(i)<0?r:i},this)}max(...e){if(e.length===0)throw new g("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(t.isPriceModel(i)){if(r.getCurrency()!==i.getCurrency())throw new f("Cannot compare prices in different currencies.")}else throw new g("Must be a PriceModel instance.");return r.compareTo(i)>0?r:i},this)}zero(){return new t({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new t({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return t.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return t.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,r,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=Z[r];if(!r||!n)throw new x("Invalid currency code for formatting.");let o=e,c=i.displayAsInteger?0:t.getDecimalPlaces(r),l={style:i.style??"currency",currency:r,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:c,maximumFractionDigits:c};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,l).format(o)}catch(s){return console.error(`Error formatting price for currency "${r}" and locale "${n}":`,s),`${J[r]??r} ${t.addThousandSeparators(o.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 r=e.split("."),i=r[0],n=r.length>1?"."+r[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,r){if(e<0)throw new C("Amount cannot be negative for rounding.");if(r===void 0)throw new x("Invalid currency code for rounding.");let i=t.getDecimalPlaces(r),n=Math.pow(10,i);return Math.round(e*n)/n}};var B=class{baseUnitPrice;taxCategory;tiers;constructor(e){let r=new T(e.baseUnitPrice);if(!e.taxCategory)throw new O;let i=(e.tiers??[]).map(s=>({minQuantity:s.minQuantity,unitPrice:new T(s.unitPrice)})).sort((s,u)=>s.minQuantity-u.minQuantity);if(i.some(s=>s.minQuantity<=0))throw new U;let o=i.some(s=>s.unitPrice.getCurrency()!==r.getCurrency()),c=i.some((s,u)=>u>0&&s.unitPrice.compareTo(i[u-1].unitPrice)>0),l=i[0]?.unitPrice.compareTo(r)>0;if(o||c||l)throw new F("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=r,this.taxCategory=e.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}getApplicableTier(e){if(e<=0)throw new z;for(let r=this.tiers.length-1;r>=0;r--)if(e>=this.tiers[r].minQuantity){let i=this.tiers[r];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new _(e)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let e=this.tiers[this.tiers.length-1].unitPrice.getAmount(),r=this.baseUnitPrice.getAmount();return (r-e)/r*100}};var h=class t extends P{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new m("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 r={},i=e.split("|");for(let n of i){let[o,c]=n.split(":");c.startsWith("c+")?r[o]={name:c.slice(2)}:r[o]=c;}return r}catch(r){throw new m(r?.message)}}constructor(e,r=new Date){super(e,r),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,o)=>(e.pricing[o]&&(n[o]=new B(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=p.deepClone(e.attributes),this.specifications=p.deepClone(e.specifications),this.categories=p.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new m("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=t.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new R(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new I(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new I(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[A[e]]??this.name.en:p.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[A[e]]??this.description.en:p.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[A[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 r=t.generateSelectionAttributesKey(e),i=this.variants.find(n=>t.generateSelectionAttributesKey(n.selectionAttributes)===r);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,r){switch(r){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)}getSpecifications(e){return e?p.deepClone(this.specifications[e]??this.specifications[A[e]]??this.specifications.en):p.deepClone(this.specifications)}getSearchTags(e){return e?p.deepClone(this.searchTags[e]??this.searchTags[A[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((r,i)=>(this.pricing[i]&&(r[i]=this.pricing[i]?.getDetails()),r),{}),attributes:this.getAttributes(),variants:this.variants.map(r=>({sku:r.sku,selectionAttributes:p.deepClone(r.selectionAttributes),images:{primary:r.images.primary.getDetails(),gallery:r.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new m("Selection attributes are required");Object.keys(this.attributes).forEach(r=>{if(r.toLowerCase()==="size")return;let i=this.attributes[r],n=e[r];if(n===void 0)throw new m(`Selection attribute '${r}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new m(`Selection attribute '${r}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new m(`Selection attribute '${r}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new m(`Selection attribute '${r}' is invalid`)}});}validateSelectionAttribute(e){let r=t.generateSelectionAttributesKey(e);return this.variants.some(i=>t.generateSelectionAttributesKey(i.selectionAttributes)===r)}validateSize(e){return this.attributes.size.includes(e)}};var ne={$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:h.productKeyRegex.source},productSku:{type:"string",pattern:h.productSKURegex.source},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}$"},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(V)},currency:{type:"string",enum:Object.values(D)},locale:{type:"string",enum:Object.values(w)},language:{type:"string",enum:Object.values(v)},localeOrLanguage:{type:"string",enum:[...Object.values(w),...Object.values(v)]},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 he={getStandardSchemaDefinition(){return ne}},be=he;var N=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 S={logException:(t,e)=>{console.error(`Exception Occurred in Function: ${t}, Error: ${S.inspect(e)}`);},logError:(t,e)=>{console.error(`Error Occurred in Function: ${t}, Error: ${S.inspect(e)}`);},logWarning:(t,e)=>{console.warn(`Warning in Function: ${t} - ${S.inspect(e)}`);},logMessage:(t,e)=>{console.log(`Message in Function: ${t} - ${S.inspect(e)}`);},logInvalidPayload:(t,e)=>{console.error(`Invalid Payload received for Function: ${t}, Error: ${S.inspect(e)}`);},inspect:t=>typeof t=="string"?t:Ae__default.default.inspect(t)},y=S;var xe={handleException:(t,e,r)=>{e.knownError?(e.logError&&y.logError(t,e),r.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(y.logException(t,e),r.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(y.logException(t,e),r.status(500).json({status:500,error:N.INTERNAL_SERVER_ERROR}));},generateResponse:(t,e,r)=>({status:t,data:e,error:r}),generateError:(t,e,r=!0,i=!1)=>({status:t,error:e,knownError:r,logError:i})},Ie=xe;var Te=async(t,e,r="GET",i={},n)=>{let o={method:r,headers:{"Content-Type":"application/json",...i}};r!=="GET"&&n&&(o.body=JSON.stringify(n));let c=`${t}${e?"/"+e:""}`,l=c.includes("api.xetile.com")||c.includes("localhost");try{let s=await fetch(c,o);if(!s.ok){let b,K=await s.text();try{b=JSON.parse(K);}catch{b={status:s.status,error:K||s.statusText},y.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${c}. Raw text: ${K}`);}throw {status:s.status,statusText:s.statusText,error:b}}let u=await s.json();return y.logMessage("Fetch",`API call successful: URL-${c}, Status- ${s.status}`),{status:s.status,statusText:s.statusText,data:l?u.data:u}}catch(s){throw y.logError("Fetch",`API call failed: URL-${c}, Status- ${s.status||500}, Error- ${y.inspect(s.error||s)}`),{status:s.status||500,statusText:s.statusText||N.INTERNAL_SERVER_ERROR,error:s.error||{status:s.status||500,error:s.statusText||N.SOMETHING_WENT_WRONG}}}},Se=Te;var W=class{cache=new Map;maxSize;ttl;cleanupInterval;constructor(e=1e3,r=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(r)||r<1)throw new RangeError("ttl must be a finite number greater than or equal to 1.");this.maxSize=e,this.ttl=r,this.cleanupInterval=setInterval(()=>this.cleanup(),60*1e3),this.cleanupInterval.unref&&this.cleanupInterval.unref();}cleanup(){let e=Date.now();for(let[r,i]of this.cache.entries())e>=i.expiry&&this.cache.delete(r);}set(e,r){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:r,expiry:Date.now()+this.ttl});}get(e){let r=this.cache.get(e);if(r){if(Date.now()>=r.expiry){this.cache.delete(e);return}return this.cache.delete(e),this.cache.set(e,r),r.value}}dispose(){clearInterval(this.cleanupInterval);}},Pe=W;
|
|
2
|
-
exports.Fetch=Se;exports.Logger=
|
|
1
|
+
'use strict';var se=require('crypto'),Ae=require('util');function _interopDefault(e){return e&&e.__esModule?e:{default:e}}var se__default=/*#__PURE__*/_interopDefault(se);var Ae__default=/*#__PURE__*/_interopDefault(Ae);var V=(e=>(e.IN="IN",e))(V||{}),D=(e=>(e.INR="INR",e))(D||{}),w=(t=>(t["en-IN"]="en-IN",t["kn-IN"]="kn-IN",t))(w||{}),$=(r=>(r.en="en",r.kn="kn",r))($||{}),A={"en-IN":"en","kn-IN":"kn"};var J={INR:"\u20B9"},Z={INR:"en-IN"},k=(l=>(l.MALE="Male",l.FEMALE="Female",l.UNISEX="Unisex",l.KIDS="Kids",l.BOY="Boy",l.GIRL="Girl",l.GENERAL="General",l))(k||{});var M=new Uint8Array(256),v=M.length;function G(){return v>M.length-16&&(se__default.default.randomFillSync(M),v=0),M.slice(v,v+=16)}var X=/^(?:[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 oe(t){return typeof t=="string"&&X.test(t)}var ee=oe;var d=[];for(let t=0;t<256;++t)d.push((t+256).toString(16).slice(1));function L(t,e=0){return d[t[e+0]]+d[t[e+1]]+d[t[e+2]]+d[t[e+3]]+"-"+d[t[e+4]]+d[t[e+5]]+"-"+d[t[e+6]]+d[t[e+7]]+"-"+d[t[e+8]]+d[t[e+9]]+"-"+d[t[e+10]]+d[t[e+11]]+d[t[e+12]]+d[t[e+13]]+d[t[e+14]]+d[t[e+15]]}function ae(t){if(!ee(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}var te=ae;function ce(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}var ue="6ba7b810-9dad-11d1-80b4-00c04fd430c8",le="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function j(t,e,r){function i(n,o,c,l){var s;if(typeof n=="string"&&(n=ce(n)),typeof o=="string"&&(o=te(o)),((s=o)===null||s===void 0?void 0:s.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+n.length);if(u.set(o),u.set(n,o.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,c){l=l||0;for(let b=0;b<16;++b)c[l+b]=u[b];return c}return L(u)}try{i.name=t;}catch{}return i.DNS=ue,i.URL=le,i}var Q={randomUUID:se__default.default.randomUUID};function ge(t,e,r){if(Q.randomUUID&&!e&&!t)return Q.randomUUID();t=t||{};let i=t.random||(t.rng||G)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){r=r||0;for(let n=0;n<16;++n)e[r+n]=i[n];return e}return L(i)}var q=ge;function me(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),se__default.default.createHash("sha1").update(t).digest()}var re=me;var fe=j("v5",80,re),Y=fe;var ye={isUUID:t=>/^[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(t),isEmail:t=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(t),isURL:t=>/^(http|https):\/\/[^ "]+$/.test(t),generateUUID:(t,e)=>e&&t?Y(t,e):q(),generateSearchId:(t,e)=>`${t}#${h.generateSelectionAttributesKey(e)}`,getKeyfromSearchId:t=>{let[e,r]=t.split("#");return {key:e,selectionAttributes:h.parseSelectionAttributesKey(r)}},deepClone(t){return structuredClone(t)}},g=ye;var ie=t=>structuredClone(t),H=class{customFields;constructor(e,r=new Date){this.customFields={...e.customFields};}getCustomField(e){let r=this.customFields[e];return r==null?r:ie(r)}setCustomField(e,r){this.customFields[e]=r;}getAllCustomFields(){return ie(this.customFields)}},P=class extends H{version;createdAt;modifiedAt;modifiedBy;constructor(e,r=new Date){super(e),this.version=e.version??1,this.createdAt=e.createdAt&&!isNaN(Date.parse(e.createdAt))?new Date(e.createdAt).toISOString():r.toISOString(),this.modifiedAt=e.modifiedAt&&!isNaN(Date.parse(e.modifiedAt))?new Date(e.modifiedAt).toISOString():r.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,r,i,n){this.modifiedBy={id:e,authType:r,requestId:i,lambdaName:n};}};var R=class extends Error{constructor(e){super(`Duplicate selection attribute found: ${e}`),this.name="DuplicateSelectionAttributeError";}};var f=class extends Error{constructor(e="Failed to parse selection attributes key."){super(`SelectionAttributeParseError: ${e}`),this.name="SelectionAttributeParseError";}};var O=class extends Error{constructor(e="Tax category is not valid."){super(`InvalidTaxCategory: ${e}`),this.name="InvalidTaxCategoryError";}},U=class extends Error{constructor(e="Minimum quantity must be greater than zero."){super(`InvalidMinQuantity: ${e}`),this.name="InvalidMinQuantityError";}},F=class extends Error{constructor(e){super(`InvalidTieredPrice: ${e}`),this.name="InvalidTieredPriceError";}},z=class extends Error{constructor(e="Quantity must be greater than zero."){super(`InvalidQuantity: ${e}`),this.name="InvalidQuantityError";}},_=class extends Error{constructor(e){super(`NoApplicableTier: Quantity ${e} does not meet the minimum purchase requirement.`),this.name="NoApplicableTierError";}};var C=class extends Error{constructor(e="Amount cannot be negative."){super(`InvalidAmount: ${e}`),this.name="InvalidPriceAmountError";}},x=class extends Error{constructor(e="Currency code is required."){super(`InvalidCurrency: ${e}`),this.name="InvalidCurrencyCodeError";}},y=class extends Error{constructor(e="Cannot perform operation on prices with different currencies."){super(`CurrencyMismatch: ${e}`),this.name="CurrencyMismatchError";}},p=class extends Error{constructor(e){super(`InvalidArgument: ${e}`),this.name="InvalidArgumentError";}},E=class extends Error{constructor(e="Invalid image source configuration."){super(`InvalidImageSource: ${e}`),this.name="InvalidImageSourceError";}};var I=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 E("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,r){if(r===void 0){if(e==="original")throw new E("Cannot remove the 'original' image source.");delete this.sources[e];}else this.sources[e]=r;}getDetails(){return {sources:this.getSources(),alt:this.getAlt(),order:this.getOrder(),label:this.getLabel()}}};var T=class t{#e;amount;currency;constructor(e){if(this.#e="PriceModel",e.amount<0)throw new C("Amount cannot be negative.");if(!e.currency)throw new x("Currency code is required.");this.currency=e.currency,this.amount=parseFloat(e.amount.toFixed(t.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(t.getPrecisionPlaces(this.currency)))}compareTo(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new y("Cannot compare prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return this.getPreciseAmount(this.amount-e.getAmount())}add(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new y("Cannot add prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return new t({amount:this.getPreciseAmount(this.amount+e.getAmount()),currency:this.currency})}subtract(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new y("Cannot subtract prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return new t({amount:this.getPreciseAmount(this.amount-e.getAmount()),currency:this.currency})}multiply(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new y("Cannot multiply prices in different currencies.");return new t({amount:this.getPreciseAmount(this.amount*e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>=0)return new t({amount:this.getPreciseAmount(this.amount*e),currency:this.currency});throw new p("Must be a non-negative number.")}divide(e){if(t.isPriceModel(e)){if(this.currency!==e.getCurrency())throw new y("Cannot divide prices in different currencies.");return new t({amount:this.getPreciseAmount(this.amount/e.getAmount()),currency:this.currency})}else if(typeof e=="number"&&e>0)return new t({amount:this.getPreciseAmount(this.amount/e),currency:this.currency});throw new p("Must be a positive number.")}min(...e){if(e.length===0)throw new p("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(t.isPriceModel(i)){if(r.getCurrency()!==i.getCurrency())throw new y("Cannot compare prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return r.compareTo(i)<0?r:i},this)}max(...e){if(e.length===0)throw new p("Must provide at least one PriceModel.");return e.reduce((r,i)=>{if(t.isPriceModel(i)){if(r.getCurrency()!==i.getCurrency())throw new y("Cannot compare prices in different currencies.")}else throw new p("Must be a PriceModel instance.");return r.compareTo(i)>0?r:i},this)}zero(){return new t({currency:this.currency,amount:0})}isZero(){return this.amount===0}round(){return new t({currency:this.currency,amount:this.getRoundedAmount()})}getRoundedAmount(){return t.getRoundedAmount(this.amount,this.currency)}getFormattedString(){return t.getFormattedString(this.amount,this.currency)}toString(){return this.getFormattedString()}static getFormattedString(e,r,i={displayAsInteger:!1,style:"currency",currencyDisplay:"symbol"}){let n=Z[r];if(!r||!n)throw new x("Invalid currency code for formatting.");let o=e,c=i.displayAsInteger?0:t.getDecimalPlaces(r),l={style:i.style??"currency",currency:r,signDisplay:"never",currencyDisplay:i.currencyDisplay,minimumFractionDigits:c,maximumFractionDigits:c};i.displayAsInteger&&(o=Math.ceil(o));try{return new Intl.NumberFormat(n,l).format(o)}catch(s){return console.error(`Error formatting price for currency "${r}" and locale "${n}":`,s),`${J[r]??r} ${t.addThousandSeparators(o.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 r=e.split("."),i=r[0],n=r.length>1?"."+r[1]:"";return i.replace(/\B(?=(\d{3})+(?!\d))/g,",")+n}static getRoundedAmount(e,r){if(e<0)throw new C("Amount cannot be negative for rounding.");if(r===void 0)throw new x("Invalid currency code for rounding.");let i=t.getDecimalPlaces(r),n=Math.pow(10,i);return Math.round(e*n)/n}};var B=class{baseUnitPrice;taxCategory;tiers;constructor(e){let r=new T(e.baseUnitPrice);if(!e.taxCategory)throw new O;let i=(e.tiers??[]).map(s=>({minQuantity:s.minQuantity,unitPrice:new T(s.unitPrice)})).sort((s,u)=>s.minQuantity-u.minQuantity);if(i.some(s=>s.minQuantity<=0))throw new U;let o=i.some(s=>s.unitPrice.getCurrency()!==r.getCurrency()),c=i.some((s,u)=>u>0&&s.unitPrice.compareTo(i[u-1].unitPrice)>0),l=i[0]?.unitPrice.compareTo(r)>0;if(o||c||l)throw new F("Tiers must share the same currency and must not increase in unit price.");this.baseUnitPrice=r,this.taxCategory=e.taxCategory,this.tiers=i;}getBaseUnitPrice(){return this.baseUnitPrice}getTaxCategory(){return this.taxCategory}getTiers(){return this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice}))}getDetails(){return {baseUnitPrice:this.baseUnitPrice.getDetails(),taxCategory:this.taxCategory,tiers:this.tiers.map(e=>({minQuantity:e.minQuantity,unitPrice:e.unitPrice.getDetails()}))}}getApplicableTier(e){if(e<=0)throw new z;for(let r=this.tiers.length-1;r>=0;r--)if(e>=this.tiers[r].minQuantity){let i=this.tiers[r];return {minQuantity:i.minQuantity,unitPrice:i.unitPrice}}throw new _(e)}getMinQuantity(){return this.tiers[0]?.minQuantity??1}getMaxDiscountPercent(){if(!this.tiers.length)return 0;let e=this.tiers[this.tiers.length-1].unitPrice.getAmount(),r=this.baseUnitPrice.getAmount();return (r-e)/r*100}};var h=class t extends P{id;key;name;description;slug;brand;pricing;variants;targetGender;attributes;specifications;categories;isActive;searchTags;static productKeyRegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static productSKURegex=/^(?!\s)(?!.*\s$)[A-Z0-9-]{4,16}$/;static generateSelectionAttributesKey(e){if(typeof e!="object")throw new f("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 r={},i=e.split("|");for(let n of i){let[o,c]=n.split(":");c.startsWith("c+")?r[o]={name:c.slice(2)}:r[o]=c;}return r}catch(r){throw new f(r?.message)}}constructor(e,r=new Date){super(e,r),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,o)=>(e.pricing[o]&&(n[o]=new B(e.pricing[o])),n),{}),this.targetGender=e.targetGender,this.attributes=g.deepClone(e.attributes),this.specifications=g.deepClone(e.specifications),this.categories=g.deepClone(e.categories);let i=new Set;this.variants=(e.variants||[]).map(n=>{if(!n.selectionAttributes||typeof n.selectionAttributes!="object")throw new f("Selection attributes are required");this.checkSelectionAttributes(n.selectionAttributes);let o=t.generateSelectionAttributesKey(n.selectionAttributes);if(i.has(o))throw new R(o);return i.add(o),{sku:n.sku,selectionAttributes:n.selectionAttributes,images:{primary:new I(n.images.primary),gallery:(n.images.gallery||[]).map(c=>new I(c))}}}),this.isActive=e.isActive,this.searchTags=e.searchTags?g.deepClone(e.searchTags):{en:[]};}getId(){return this.id}getKey(){return this.key}getName(e){return e?this.name[e]??this.name[A[e]]??this.name.en:g.deepClone(this.name)}getDescription(e){return e?this.description[e]??this.description[A[e]]??this.description.en:g.deepClone(this.description)}getSlug(e){return e?this.slug[e]??this.slug[A[e]]??this.slug.en:g.deepClone(this.slug)}getBrand(){return this.brand}getPriceDetails(e){return e?this.pricing[e]??null:{...this.pricing}}getAttributes(){return g.deepClone(this.attributes)}getVariants(){return this.variants.map(e=>({sku:e.sku,selectionAttributes:g.deepClone(e.selectionAttributes),images:{primary:e.images.primary,gallery:[...e.images.gallery]}}))}getImagesBySelectionAttributes(e){let r=t.generateSelectionAttributesKey(e),i=this.variants.find(n=>t.generateSelectionAttributesKey(n.selectionAttributes)===r);return i?{primary:i.images.primary,gallery:[...i.images.gallery]}:null}getImages(e,r){switch(r){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 g.deepClone(this.categories)}getSpecifications(e){return e?g.deepClone(this.specifications[e]??this.specifications[A[e]]??this.specifications.en):g.deepClone(this.specifications)}getSearchTags(e){return e?g.deepClone(this.searchTags[e]??this.searchTags[A[e]]??this.searchTags.en):g.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((r,i)=>(this.pricing[i]&&(r[i]=this.pricing[i]?.getDetails()),r),{}),attributes:this.getAttributes(),variants:this.variants.map(r=>({sku:r.sku,selectionAttributes:g.deepClone(r.selectionAttributes),images:{primary:r.images.primary.getDetails(),gallery:r.images.gallery.map(i=>i.getDetails())}})),isActive:this.getIsActive(),targetGender:this.getTargetGender(),categories:this.getCategories(),specifications:this.getSpecifications(),searchTags:this.getSearchTags(),...e}}checkSelectionAttributes(e){if(!e||typeof e!="object")throw new f("Selection attributes are required");Object.keys(this.attributes).forEach(r=>{if(r.toLowerCase()==="size")return;let i=this.attributes[r],n=e[r];if(n===void 0)throw new f(`Selection attribute '${r}' is missing`);if(typeof i=="string"){if(typeof n!="string"||i!==n)throw new f(`Selection attribute '${r}' is invalid`)}else if(Array.isArray(i)){if(i.length>0&&typeof i[0]=="string"){if(typeof n!="string"||!i.includes(n))throw new f(`Selection attribute '${r}' is invalid`)}else if(typeof n!="object"||!("name"in n)||i.findIndex(o=>o.name===n.name)<0)throw new f(`Selection attribute '${r}' is invalid`)}});}validateSelectionAttribute(e){let r=t.generateSelectionAttributesKey(e);return this.variants.some(i=>t.generateSelectionAttributesKey(i.selectionAttributes)===r)}validateSize(e){return this.attributes.size.includes(e)}};var ne={$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:h.productKeyRegex.source},productSku:{type:"string",pattern:h.productSKURegex.source},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}$"},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(V)},currency:{type:"string",enum:Object.values(D)},locale:{type:"string",enum:Object.values(w)},language:{type:"string",enum:Object.values($)},localeOrLanguage:{type:"string",enum:[...Object.values(w),...Object.values($)]},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 he={getStandardSchemaDefinition(){return ne}},be=he;var N=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 S={logException:(t,e)=>{console.error(`Exception Occurred in Function: ${t}, Error: ${S.inspect(e)}`);},logError:(t,e)=>{console.error(`Error Occurred in Function: ${t}, Error: ${S.inspect(e)}`);},logWarning:(t,e)=>{console.warn(`Warning in Function: ${t} - ${S.inspect(e)}`);},logMessage:(t,e)=>{console.log(`Message in Function: ${t} - ${S.inspect(e)}`);},logInvalidPayload:(t,e)=>{console.error(`Invalid Payload received for Function: ${t}, Error: ${S.inspect(e)}`);},inspect:t=>typeof t=="string"?t:Ae__default.default.inspect(t)},m=S;var xe={handleException:(t,e,r)=>{e.knownError?(e.logError&&m.logError(t,e),r.status(e.status).json({status:e.status,error:e.error})):e.status&&e.error?(m.logException(t,e),r.status(e.status).json({error:e.errorMessage||JSON.stringify(e.error),status:e.status})):(m.logException(t,e),r.status(500).json({status:500,error:N.INTERNAL_SERVER_ERROR}));},generateResponse:(t,e,r)=>({status:t,data:e,error:r}),generateError:(t,e,r=!0,i=!1)=>({status:t,error:e,knownError:r,logError:i})},Ie=xe;var Te=async(t,e,r="GET",i={},n)=>{let o={method:r,headers:{"Content-Type":"application/json",...i}};r!=="GET"&&n&&(o.body=JSON.stringify(n));let c=`${t}${e?"/"+e:""}`,l=c.includes("api.xetile.com")||c.includes("localhost");try{let s=await fetch(c,o);if(!s.ok){let b,K=await s.text();try{b=JSON.parse(K);}catch{b={status:s.status,error:K||s.statusText},m.logWarning("Fetch",`Failed to parse error response body as JSON for URL-${c}. Raw text: ${K}`);}throw {status:s.status,statusText:s.statusText,error:b}}let u=await s.json();return m.logMessage("Fetch",`API call successful: URL-${c}, Status- ${s.status}`),{status:s.status,statusText:s.statusText,data:l?u.data:u}}catch(s){throw m.logError("Fetch",`API call failed: URL-${c}, Status- ${s.status||500}, Error- ${m.inspect(s.error||s)}`),{status:s.status||500,statusText:s.statusText||N.INTERNAL_SERVER_ERROR,error:s.error||{status:s.status||500,error:s.statusText||N.SOMETHING_WENT_WRONG}}}},Se=Te;var W=class{cache=new Map;maxSize;ttl;cleanupInterval;constructor(e=1e3,r=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(r)||r<1)throw new RangeError("ttl must be a finite number greater than or equal to 1.");this.maxSize=e,this.ttl=r,this.cleanupInterval=setInterval(()=>this.cleanup(),60*1e3),this.cleanupInterval.unref&&this.cleanupInterval.unref();}cleanup(){let e=Date.now();for(let[r,i]of this.cache.entries())e>=i.expiry&&this.cache.delete(r);}set(e,r){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:r,expiry:Date.now()+this.ttl});}get(e){let r=this.cache.get(e);if(r){if(Date.now()>=r.expiry){this.cache.delete(e);return}return this.cache.delete(e),m.logMessage("MemoryCache.get",`Successfully read cache data for key: ${e}`),this.cache.set(e,r),r.value}}dispose(){clearInterval(this.cleanupInterval);}},Pe=W;
|
|
2
|
+
exports.Fetch=Se;exports.Logger=m;exports.MemoryCache=Pe;exports.ResponseUtility=Ie;exports.Schema=be;exports.Utils=g;//# sourceMappingURL=index.js.map
|
|
3
3
|
//# sourceMappingURL=index.js.map
|