b23-lib 1.6.2 → 1.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -422,4 +422,442 @@ declare const Logger: {
422
422
  inspect: (context: any) => string;
423
423
  };
424
424
 
425
- export { type AuthMiddlewareConfig, type AuthTokenType, AuthUtility, type AuthUtilityConfig, DefaultAuthMiddlewareConfig, DefaultAuthUtilityConfig, DynamoDBUtility as DynamoDB, type ErrorType, Fetch, Logger, ResponseUtility, Schema, type SuccessType, Utils };
425
+ /**
426
+ * Represents the countries where the application operates or products are available.
427
+ */
428
+ declare enum OperationalCountry {
429
+ /** India */ IN = "IN"
430
+ }
431
+ declare enum OperationalCountryCurrency {
432
+ /** India */ INR = "INR"
433
+ }
434
+ declare enum OperationalLocale {
435
+ /** India */ 'en-IN' = "en-IN"
436
+ }
437
+ /**
438
+ * Defines the supported ISO 4217 currency codes as an enumeration.
439
+ */
440
+ declare const CountryCurrencyMap: {
441
+ /** India */ IN: OperationalCountryCurrency;
442
+ };
443
+ declare const CurrencySymbolMap: {
444
+ INR: string;
445
+ };
446
+ /**
447
+ * Defines standard gender categories for product targeting.
448
+ */
449
+ declare enum GenderCategory {
450
+ MALE = "Male",
451
+ FEMALE = "Female",
452
+ UNISEX = "Unisex",
453
+ KIDS = "Kids",
454
+ BOY = "Boy",
455
+ GIRL = "Girl"
456
+ }
457
+
458
+ /**
459
+ * Represents a ISO 3166-1 alpha-2 country code (e.g., 'US', 'IN').
460
+ */
461
+ type CountryCode = keyof typeof OperationalCountry;
462
+ /**
463
+ * Represents a ISO 4217 currency code (e.g., 'INR', 'USD').
464
+ */
465
+ type CurrencyCode = keyof typeof OperationalCountryCurrency;
466
+ /**
467
+ * /**
468
+ * Represents a string that can be localized into multiple languages.
469
+ * The 'en' property is mandatory and serves as the default English translation.
470
+ * Additional properties can be added for other locales using their respective locale codes.
471
+ */
472
+ type LocalizedString = {
473
+ en: string;
474
+ } & {
475
+ [locale in LocaleCode]?: string;
476
+ };
477
+ /**
478
+ * Represents a BCP 47 language tag (e.g., 'en-US', 'fr-FR').
479
+ * Used to identify languages and regional variations.
480
+ */
481
+ type LocaleCode = keyof typeof OperationalLocale;
482
+ /**
483
+ * Represents a pricing tier based on a minimum purchase quantity.
484
+ */
485
+ type PriceTier = {
486
+ /** The minimum quantity required to achieve this unit price. */
487
+ minQuantity: number;
488
+ /** The price per unit at this quantity tier. */
489
+ unitPrice: number;
490
+ currency: CurrencyCode;
491
+ country: CountryCode;
492
+ };
493
+ /**
494
+ * Represents the base price information for a single unit in a specific country.
495
+ */
496
+ type BasePrice = {
497
+ /** Enforces that this price is for a single unit. */
498
+ minQuantity: 1;
499
+ /** The price per unit. */
500
+ unitPrice: number;
501
+ currency: CurrencyCode;
502
+ country: CountryCode;
503
+ };
504
+ type BasePriceList = BasePrice[];
505
+ type PriceTierList = PriceTier[];
506
+ type Color = {
507
+ name: string;
508
+ hex?: string;
509
+ };
510
+ /**
511
+ * Represents a date and time string formatted according to the ISO 8601 standard.
512
+ * Example: "2023-10-27T10:30:00Z"
513
+ */
514
+ type ISODateTime = string;
515
+ type RegionalPrice = {
516
+ country: CountryCode;
517
+ currency: CurrencyCode;
518
+ price: number;
519
+ };
520
+ type RegionalPriceList = RegionalPrice[];
521
+ interface ShippingDetails {
522
+ shippingMethodId?: string;
523
+ shippingMethodName?: string | LocalizedString;
524
+ carrier?: string;
525
+ estimatedCost?: number;
526
+ estimatedDeliveryBy?: ISODateTime | null;
527
+ deliveryInstructions?: string | null;
528
+ }
529
+
530
+ interface CustomFields {
531
+ [key: string]: any;
532
+ }
533
+ type BaseAttributes = {
534
+ customFields?: CustomFields;
535
+ version?: number;
536
+ createdAt?: ISODateTime;
537
+ modifiedAt?: ISODateTime;
538
+ modifiedBy?: string;
539
+ };
540
+ type BaseData = {
541
+ customFields: CustomFields;
542
+ version: number;
543
+ createdAt: ISODateTime;
544
+ modifiedAt: ISODateTime;
545
+ modifiedBy: string;
546
+ };
547
+
548
+ declare enum AddressType {
549
+ BILLING = "billing",
550
+ SHIPPING = "shipping",
551
+ BILLING_AND_SHIPPING = "billing&shipping",
552
+ NONE = "none"
553
+ }
554
+ type AddressAttributes = BaseAttributes & {
555
+ id: string;
556
+ firstName: string;
557
+ lastName: string;
558
+ phone: string;
559
+ email: string;
560
+ addressLine1: string;
561
+ addressLine2?: string;
562
+ city: string;
563
+ postalCode: string;
564
+ state: string;
565
+ country: string;
566
+ isBillingAddress: boolean;
567
+ isShippingAddress: boolean;
568
+ };
569
+ type AddressData = Required<AddressAttributes>;
570
+
571
+ declare enum ImageResolution {
572
+ THUMBNAIL = "thumbnail",
573
+ SMALL = "small",
574
+ MEDIUM = "medium",
575
+ LARGE = "large",
576
+ ORIGINAL = "original"
577
+ }
578
+ type ImageInfoAttribute = {
579
+ sources: {
580
+ [key in ImageResolution]?: string;
581
+ } & {
582
+ original: string;
583
+ };
584
+ alt?: string;
585
+ order?: number;
586
+ label?: string;
587
+ };
588
+ type ImageInfoData = ImageInfoAttribute;
589
+
590
+ type SubItem = {
591
+ size: string;
592
+ quantity: number;
593
+ };
594
+ type LineItemAttributes = {
595
+ id: string;
596
+ productKey: string;
597
+ variantId: string;
598
+ name: LocalizedString;
599
+ attributes: {
600
+ color: Color;
601
+ };
602
+ primaryImage: ImageInfoData;
603
+ subItems: SubItem[];
604
+ basePrice: BasePrice;
605
+ priceTiers: PriceTier[];
606
+ };
607
+ type LineItemData = LineItemAttributes & {
608
+ totalQuantity: number;
609
+ priceTotals: {
610
+ subtotal: number;
611
+ mrpTotal: number;
612
+ };
613
+ };
614
+
615
+ declare enum CouponType {
616
+ COUPON = "coupon",
617
+ AUTOMATIC = "automatic"
618
+ }
619
+ declare enum CouponDiscountMethod {
620
+ FLAT = "flat",
621
+ PERCENTAGE = "percentage"
622
+ }
623
+ declare enum CouponCategory {
624
+ SHIPPING = "SHIPPING",
625
+ CUSTOMER = "CUSTOMER"
626
+ }
627
+ declare enum ApplicableTo {
628
+ ALL = "all",
629
+ FTB = "ftb"
630
+ }
631
+ type CouponAttribute = BaseAttributes & {
632
+ couponCode: string;
633
+ name: LocalizedString;
634
+ description: LocalizedString;
635
+ type: CouponType;
636
+ customerId?: string;
637
+ validFrom: ISODateTime;
638
+ validTo: ISODateTime;
639
+ minCartValue: RegionalPriceList;
640
+ maxCartDiscount: RegionalPriceList;
641
+ discountMethod: CouponDiscountMethod;
642
+ percentageValue?: number;
643
+ applicableTo: ApplicableTo;
644
+ category: CouponCategory;
645
+ };
646
+ type CouponData = Required<CouponAttribute>;
647
+
648
+ type BaseShoppingContainerAttributes = BaseAttributes & {
649
+ id: string;
650
+ customerId?: string;
651
+ customerEmail?: string;
652
+ anonymousId?: string;
653
+ lineItems: LineItemData[];
654
+ shippingDetails: ShippingDetails | null;
655
+ shippingAddress?: AddressData | null;
656
+ billingAddress?: AddressData | null;
657
+ coupons?: CouponData[];
658
+ total?: {
659
+ shipping?: number;
660
+ effectiveShipping?: number;
661
+ subtotal?: number;
662
+ mrpTotal?: number;
663
+ couponTotal?: {
664
+ [key: string]: number;
665
+ };
666
+ grandTotal?: number;
667
+ };
668
+ country: CountryCode;
669
+ currency: CurrencyCode;
670
+ locale: LocaleCode;
671
+ };
672
+ type BaseShoppingContainerData = Omit<BaseShoppingContainerAttributes, 'coupons' | 'total'> & BaseData & {
673
+ coupons: CouponData[];
674
+ total: {
675
+ shipping: number;
676
+ effectiveShipping: number;
677
+ subtotal: number;
678
+ mrpTotal: number;
679
+ couponTotal: {
680
+ [key: string]: number;
681
+ };
682
+ grandTotal: number;
683
+ };
684
+ };
685
+
686
+ declare enum CartState {
687
+ ACTIVE = "ACTIVE",
688
+ FROZEN = "FROZEN",
689
+ MERGED = "MERGED",
690
+ ORDERED = "ORDERED"
691
+ }
692
+ declare class LineItemNotFoundError extends Error {
693
+ constructor(lineItemId: string);
694
+ }
695
+ /**
696
+ * Input attributes for creating or updating a CartModel.
697
+ */
698
+ type CartAttributes = BaseShoppingContainerAttributes & {
699
+ state: CartState;
700
+ expireAt: number;
701
+ };
702
+ type CartData = BaseShoppingContainerData & {
703
+ state: CartState;
704
+ expireAt: number;
705
+ };
706
+ type CartConfig = {
707
+ expiresAtInSeconds: number;
708
+ };
709
+ declare const DEFAULT_CART_CONFIG: CartConfig;
710
+
711
+ declare enum CustomerStatus {
712
+ CREATED = "CREATED",
713
+ REGISTERED_USER = "REGISTERED_USER",
714
+ ACTIVATED_USER = "ACTIVATED_USER",
715
+ EMAIL_OTP = "EMAIL_OTP",
716
+ EMAIL_PASSWORD = "EMAIL_PASSWORD",
717
+ PHONE_OTP = "PHONE_OTP"
718
+ }
719
+ type CustomerAttributes = BaseAttributes & {
720
+ id: string;
721
+ email: string;
722
+ phone: string;
723
+ firstName: string;
724
+ lastName: string;
725
+ isEmailVerified?: boolean;
726
+ customerStatus?: Set<CustomerStatus>;
727
+ };
728
+ type CustomerDataWithArrayStatus = Omit<CustomerAttributes, 'customerStatus'> & BaseData & {
729
+ customerStatus: CustomerStatus[];
730
+ };
731
+ type CustomerData = Required<CustomerDataWithArrayStatus>;
732
+ type CustomerDataWithOutId = Omit<CustomerData, 'id'>;
733
+
734
+ type CustomerAddressAttributes = BaseAttributes & {
735
+ id: string;
736
+ addresses: AddressData[];
737
+ defaultBillingAddressId: string;
738
+ defaultShippingAddressId: string;
739
+ };
740
+ type CustomerAddressWithoutDefaultAddress = Omit<CustomerAddressAttributes, 'addresses' | 'defaultBillingAddressId' | 'defaultShippingAddressId'> & {
741
+ addresses: AddressData[];
742
+ defaultBillingAddressId: string | null;
743
+ defaultShippingAddressId: string | null;
744
+ };
745
+ type CustomerAddressDataWithOutId = Required<Omit<CustomerAddressWithoutDefaultAddress, 'id'>>;
746
+ type CustomerAddressData = Required<CustomerAddressWithoutDefaultAddress>;
747
+
748
+ declare enum PaymentStatus {
749
+ PENDING = "PENDING",
750
+ AUTHORIZED = "AUTHORIZED",
751
+ CAPTURED = "CAPTURED",
752
+ FAILED = "FAILED",
753
+ REFUNDED = "REFUNDED",
754
+ PARTIALLY_REFUNDED = "PARTIALLY_REFUNDED"
755
+ }
756
+ declare enum PaymentMode {
757
+ PAY_LATER = "PAY_LATER",
758
+ CARD = "CARD",
759
+ CASH = "CASH",
760
+ NET_BANKING = "NET_BANKING",
761
+ WALLET = "WALLET",
762
+ COD = "COD",
763
+ UNKNOWN = "UNKNOWN"
764
+ }
765
+ /**
766
+ * Input attributes for creating or updating a PaymentModel.
767
+ */
768
+ type PaymentAttributes = BaseAttributes & {
769
+ txnId: string;
770
+ externalId?: string;
771
+ orderNumber: string;
772
+ customerId: string;
773
+ status: PaymentStatus;
774
+ subStatus?: string;
775
+ amount: number;
776
+ currency: CurrencyCode;
777
+ paymentMode: PaymentMode;
778
+ gatewayResponse?: string;
779
+ gatewayErrorCode?: string;
780
+ gatewayErrorMessage?: string;
781
+ amountRefunded?: number;
782
+ cardLast4?: string;
783
+ cardBrand?: string;
784
+ transactionAt: ISODateTime;
785
+ };
786
+ /**
787
+ * Output data structure for a PaymentModel.
788
+ * Excludes potentially large or sensitive fields by default.
789
+ */
790
+ type PaymentData = Omit<PaymentAttributes, 'gatewayResponse' | 'gatewayErrorMessage'> & BaseData;
791
+
792
+ declare enum OrderState {
793
+ PENDING_PAYMENT = "PENDING_PAYMENT",
794
+ PROCESSING = "PROCESSING",
795
+ SHIPPED = "SHIPPED",
796
+ PARTIALLY_SHIPPED = "PARTIALLY_SHIPPED",
797
+ DELIVERED = "DELIVERED",
798
+ CANCELLED = "CANCELLED",
799
+ RETURNED = "RETURNED",
800
+ REFUNDED = "REFUNDED"
801
+ }
802
+ /**
803
+ * Input attributes for creating an OrderModel.
804
+ * Extends CartAttributes but requires/adds order-specific fields.
805
+ */
806
+ type OrderAttributes = Required<Omit<BaseShoppingContainerAttributes, 'anonymousId'>> & {
807
+ anonymousId?: string;
808
+ orderNumber: string;
809
+ cartId: string;
810
+ paymentStatus: PaymentStatus;
811
+ holdReason?: string;
812
+ state: OrderState;
813
+ };
814
+ /**
815
+ * Output data structure for an OrderModel.
816
+ */
817
+ type OrderData = BaseShoppingContainerData & OrderAttributes;
818
+
819
+ type ProductVariantIdentifier = {
820
+ key: string;
821
+ variantId: string;
822
+ };
823
+ type ProductHashKey = {
824
+ id: string;
825
+ variantId: string;
826
+ };
827
+ type ProductAttributes = BaseAttributes & {
828
+ id: string;
829
+ key: string;
830
+ variantId: string;
831
+ name: LocalizedString;
832
+ description: LocalizedString;
833
+ slug: LocalizedString;
834
+ brand: string;
835
+ basePrices: BasePriceList;
836
+ priceTiers: PriceTierList;
837
+ attributes: {
838
+ color: Color;
839
+ sizes: string[];
840
+ };
841
+ primaryImage: ImageInfoData;
842
+ additionalImages?: ImageInfoData[];
843
+ isActive: boolean;
844
+ targetGender: GenderCategory;
845
+ categories: string[];
846
+ specifications: {
847
+ [locale: string]: {
848
+ [key: string]: string | string[];
849
+ };
850
+ };
851
+ searchTags?: string[];
852
+ };
853
+ type ProductData = Required<ProductAttributes>;
854
+ type ProductSpecification = {
855
+ [key: string]: string | string[];
856
+ };
857
+ type LocalizedProductSpecification = {
858
+ en: ProductSpecification;
859
+ } & {
860
+ [locale in LocaleCode]?: ProductSpecification;
861
+ };
862
+
863
+ export { type AddressAttributes, type AddressData, AddressType, ApplicableTo, type AuthMiddlewareConfig, type AuthTokenType, AuthUtility, type AuthUtilityConfig, type BaseAttributes, type BaseData, type BasePrice, type BasePriceList, type BaseShoppingContainerAttributes, type BaseShoppingContainerData, type CartAttributes, type CartConfig, type CartData, CartState, type Color, type CountryCode, CountryCurrencyMap, type CouponAttribute, CouponCategory, type CouponData, CouponDiscountMethod, CouponType, type CurrencyCode, CurrencySymbolMap, type CustomFields, type CustomerAddressAttributes, type CustomerAddressData, type CustomerAddressDataWithOutId, type CustomerAttributes, type CustomerData, type CustomerDataWithOutId, CustomerStatus, DEFAULT_CART_CONFIG, DefaultAuthMiddlewareConfig, DefaultAuthUtilityConfig, DynamoDBUtility as DynamoDB, type ErrorType, Fetch, GenderCategory, type ISODateTime, type ImageInfoAttribute, type ImageInfoData, ImageResolution, type LineItemAttributes, type LineItemData, LineItemNotFoundError, type LocaleCode, type LocalizedProductSpecification, type LocalizedString, Logger, OperationalCountry, OperationalCountryCurrency, OperationalLocale, type OrderAttributes, type OrderData, OrderState, type PaymentAttributes, type PaymentData, PaymentMode, PaymentStatus, type PriceTier, type PriceTierList, type ProductAttributes, type ProductData, type ProductHashKey, type ProductSpecification, type ProductVariantIdentifier, type RegionalPrice, type RegionalPriceList, ResponseUtility, Schema, type ShippingDetails, type SubItem, type SuccessType, Utils };
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- "use strict";var Q=Object.create;var x=Object.defineProperty;var Z=Object.getOwnPropertyDescriptor;var tt=Object.getOwnPropertyNames;var et=Object.getPrototypeOf,nt=Object.prototype.hasOwnProperty;var rt=(e,t)=>{for(var n in t)x(e,n,{get:t[n],enumerable:!0})},V=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of tt(t))!nt.call(e,s)&&s!==n&&x(e,s,{get:()=>t[s],enumerable:!(r=Z(t,s))||r.enumerable});return e};var S=(e,t,n)=>(n=e!=null?Q(et(e)):{},V(t||!e||!e.__esModule?x(n,"default",{value:e,enumerable:!0}):n,e)),st=e=>V(x({},"__esModule",{value:!0}),e);var ht={};rt(ht,{AuthUtility:()=>X,DefaultAuthMiddlewareConfig:()=>v,DefaultAuthUtilityConfig:()=>O,DynamoDB:()=>k,Fetch:()=>K,Logger:()=>h,ResponseUtility:()=>E,Schema:()=>W,Utils:()=>N});module.exports=st(ht);var o=require("@aws-sdk/client-dynamodb"),y=require("@aws-sdk/util-dynamodb"),U=class{client;returnItemCollectionMetrics;logCapacity;region;marshall=y.marshall;unmarshall=y.unmarshall;ReturnValue=o.ReturnValue;ReturnItemCollectionMetrics=o.ReturnItemCollectionMetrics;ReturnValuesOnConditionCheckFailure=o.ReturnValuesOnConditionCheckFailure;constructor({region:t,returnItemCollectionMetrics:n=o.ReturnItemCollectionMetrics.NONE,logCapacity:r=!1}){this.region=t,this.returnItemCollectionMetrics=n,this.logCapacity=r,this.client=new o.DynamoDBClient({region:this.region})}log(t,n,r){this.logCapacity&&console.log(t,"Capacity:",n,"Size:",r)}async putItem(t,n,r,s,a,u=o.ReturnValue.NONE,i=o.ReturnValuesOnConditionCheckFailure.ALL_OLD){let d={TableName:t,Item:(0,y.marshall)(n,{removeUndefinedValues:!0,convertClassInstanceToMap:!0}),ConditionExpression:r,ExpressionAttributeNames:s,ExpressionAttributeValues:a,ReturnValues:u,ReturnConsumedCapacity:o.ReturnConsumedCapacity.INDEXES,ReturnValuesOnConditionCheckFailure:i,ReturnItemCollectionMetrics:this.returnItemCollectionMetrics},l=new o.PutItemCommand(d),c=await this.client.send(l);return this.log("Put",c.ConsumedCapacity,c.ItemCollectionMetrics),(0,y.unmarshall)(c.Attributes||{})}async transactWriteItems(t){let n={TransactItems:t.map(a=>(a.Put&&(a.Put.Item=(0,y.marshall)(a.Put.Item,{removeUndefinedValues:!0,convertClassInstanceToMap:!0})),a.Update&&(a.Update.Key=(0,y.marshall)(a.Update.Key)),a.Delete&&(a.Delete.Key=(0,y.marshall)(a.Delete.Key)),a)),ReturnConsumedCapacity:o.ReturnConsumedCapacity.INDEXES,ReturnItemCollectionMetrics:this.returnItemCollectionMetrics},r=new o.TransactWriteItemsCommand(n),s=await this.client.send(r);this.log("Transaction",s.ConsumedCapacity,s.ItemCollectionMetrics)}async getItem(t,n,r=!1,s,a){let u={TableName:t,Key:(0,y.marshall)(n),ConsistentRead:r,ProjectionExpression:s,ExpressionAttributeNames:a,ReturnConsumedCapacity:o.ReturnConsumedCapacity.TOTAL},i=new o.GetItemCommand(u),d=await this.client.send(i);return this.log("Read",d.ConsumedCapacity),(0,y.unmarshall)(d.Item||{})}async batchGetItem(t,n,r=!1,s,a){let u={RequestItems:{[t]:{Keys:n.map(l=>(0,y.marshall)(l)),ConsistentRead:r,ProjectionExpression:s,ExpressionAttributeNames:a}},ReturnConsumedCapacity:o.ReturnConsumedCapacity.TOTAL},i=new o.BatchGetItemCommand(u),d=await this.client.send(i);return this.log("BatchRead",d.ConsumedCapacity),d.Responses?.[t]?.map(l=>(0,y.unmarshall)(l))||[]}async queryItems(t,n,r=!1,s,a,u,i){let d={TableName:t,KeyConditionExpression:n,ExpressionAttributeValues:u,ConsistentRead:r,ProjectionExpression:s,ExpressionAttributeNames:a,ExclusiveStartKey:i,ReturnConsumedCapacity:o.ReturnConsumedCapacity.TOTAL},l=new o.QueryCommand(d),c=await this.client.send(l);return this.log("Query",c.ConsumedCapacity),{items:c.Items?.map(p=>(0,y.unmarshall)(p))||[],lastEvaluatedKey:c.LastEvaluatedKey}}async scanItems(t,n,r=!1,s,a,u,i){let d={TableName:t,FilterExpression:n,ExpressionAttributeValues:u,ConsistentRead:r,ProjectionExpression:s,ExpressionAttributeNames:a,ExclusiveStartKey:i,ReturnConsumedCapacity:o.ReturnConsumedCapacity.TOTAL},l=new o.ScanCommand(d),c=await this.client.send(l);return this.log("Scan",c.ConsumedCapacity),{items:c.Items?.map(p=>(0,y.unmarshall)(p))||[],lastEvaluatedKey:c.LastEvaluatedKey}}async partiQL(t,n=[],r,s=!1){let a={Statement:t,Parameters:n,ConsistentRead:s,NextToken:r,ReturnConsumedCapacity:o.ReturnConsumedCapacity.INDEXES},u=new o.ExecuteStatementCommand(a),i=await this.client.send(u);return this.log("PartiQL",i.ConsumedCapacity),{Items:i.Items?.map(d=>(0,y.unmarshall)(d))||[],nextToken:i.NextToken,lastEvaluatedKey:i.LastEvaluatedKey}}async updateItem(t,n,r,s,a,u,i=o.ReturnValue.UPDATED_NEW,d=o.ReturnValuesOnConditionCheckFailure.ALL_OLD){let l={TableName:t,Key:(0,y.marshall)(n),ConditionExpression:r,UpdateExpression:s,ExpressionAttributeNames:a,ExpressionAttributeValues:u,ReturnValues:i,ReturnConsumedCapacity:o.ReturnConsumedCapacity.INDEXES,ReturnValuesOnConditionCheckFailure:d,ReturnItemCollectionMetrics:this.returnItemCollectionMetrics},c=new o.UpdateItemCommand(l),p=await this.client.send(c);return this.log("Update",p.ConsumedCapacity,p.ItemCollectionMetrics),(0,y.unmarshall)(p.Attributes||{})}async deleteItem(t,n,r,s,a,u=o.ReturnValue.ALL_OLD,i=o.ReturnValuesOnConditionCheckFailure.ALL_OLD){let d={TableName:t,Key:(0,y.marshall)(n),ConditionExpression:r,ExpressionAttributeNames:s,ExpressionAttributeValues:a,ReturnValues:u,ReturnConsumedCapacity:o.ReturnConsumedCapacity.INDEXES,ReturnValuesOnConditionCheckFailure:i,ReturnItemCollectionMetrics:this.returnItemCollectionMetrics},l=new o.DeleteItemCommand(d),c=await this.client.send(l);return this.log("Delete",c.ConsumedCapacity,c.ItemCollectionMetrics),(0,y.unmarshall)(c.Attributes||{})}async getItemByIndex(t,n,r,s=!1,a,u,i,d){let l={TableName:t,IndexName:n,KeyConditionExpression:r,ExpressionAttributeValues:i,ExclusiveStartKey:d,ConsistentRead:s,ProjectionExpression:a,ExpressionAttributeNames:u,ReturnConsumedCapacity:o.ReturnConsumedCapacity.INDEXES},c=new o.QueryCommand(l),p=await this.client.send(c);return this.log("GetItemByIndex",p.ConsumedCapacity),{Items:p.Items?.map(A=>(0,y.unmarshall)(A))||[],lastEvaluatedKey:p.LastEvaluatedKey}}},k=U;var F={$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:"^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$"},variantId:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$"},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},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:["IN"]},currency:{type:"string",enum:["INR"]},locale:{type:"string",enum:["en-IN"]},addressType:{type:"string",enum:["shipping","billing","shipping&billing"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},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 at={getStandardSchemaDefinition(){return F}},W=at;var T=require("jose");var m=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"});var Y=S(require("util")),C={logException:(e,t)=>{console.error(`Exception Occurred in Function: ${e}, Error: ${C.inspect(t)}`)},logError:(e,t)=>{console.error(`Error Occurred in Function: ${e}, Error: ${C.inspect(t)}`)},logWarning:(e,t)=>{console.warn(`Warning in Function: ${e} - ${C.inspect(t)}`)},logMessage:(e,t)=>{console.log(`Message in Function: ${e} - ${C.inspect(t)}`)},logInvalidPayload:(e,t)=>{console.error(`Invalid Payload received for Function: ${e}, Error: ${C.inspect(t)}`)},inspect:e=>typeof e=="string"?e:Y.default.inspect(e)},h=C;var J=S(require("crypto")),R=new Uint8Array(256),P=R.length;function b(){return P>R.length-16&&(J.default.randomFillSync(R),P=0),R.slice(P,P+=16)}var j=/^(?:[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 ot(e){return typeof e=="string"&&j.test(e)}var B=ot;var I=[];for(let e=0;e<256;++e)I.push((e+256).toString(16).slice(1));function _(e,t=0){return I[e[t+0]]+I[e[t+1]]+I[e[t+2]]+I[e[t+3]]+"-"+I[e[t+4]]+I[e[t+5]]+"-"+I[e[t+6]]+I[e[t+7]]+"-"+I[e[t+8]]+I[e[t+9]]+"-"+I[e[t+10]]+I[e[t+11]]+I[e[t+12]]+I[e[t+13]]+I[e[t+14]]+I[e[t+15]]}function ut(e){if(!B(e))throw TypeError("Invalid UUID");let t,n=new Uint8Array(16);return n[0]=(t=parseInt(e.slice(0,8),16))>>>24,n[1]=t>>>16&255,n[2]=t>>>8&255,n[3]=t&255,n[4]=(t=parseInt(e.slice(9,13),16))>>>8,n[5]=t&255,n[6]=(t=parseInt(e.slice(14,18),16))>>>8,n[7]=t&255,n[8]=(t=parseInt(e.slice(19,23),16))>>>8,n[9]=t&255,n[10]=(t=parseInt(e.slice(24,36),16))/1099511627776&255,n[11]=t/4294967296&255,n[12]=t>>>24&255,n[13]=t>>>16&255,n[14]=t>>>8&255,n[15]=t&255,n}var G=ut;function lt(e){e=unescape(encodeURIComponent(e));let t=[];for(let n=0;n<e.length;++n)t.push(e.charCodeAt(n));return t}var ct="6ba7b810-9dad-11d1-80b4-00c04fd430c8",mt="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function D(e,t,n){function r(s,a,u,i){var d;if(typeof s=="string"&&(s=lt(s)),typeof a=="string"&&(a=G(a)),((d=a)===null||d===void 0?void 0:d.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+s.length);if(l.set(a),l.set(s,a.length),l=n(l),l[6]=l[6]&15|t,l[8]=l[8]&63|128,u){i=i||0;for(let c=0;c<16;++c)u[i+c]=l[c];return u}return _(l)}try{r.name=e}catch{}return r.DNS=ct,r.URL=mt,r}var H=S(require("crypto")),w={randomUUID:H.default.randomUUID};function dt(e,t,n){if(w.randomUUID&&!t&&!e)return w.randomUUID();e=e||{};let r=e.random||(e.rng||b)();if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,t){n=n||0;for(let s=0;s<16;++s)t[n+s]=r[s];return t}return _(r)}var L=dt;var q=S(require("crypto"));function yt(e){return Array.isArray(e)?e=Buffer.from(e):typeof e=="string"&&(e=Buffer.from(e,"utf8")),q.default.createHash("sha1").update(e).digest()}var z=yt;var pt=D("v5",80,z),$=pt;var gt={isUUID:e=>/^[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(e),isEmail:e=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(e),isURL:e=>/^(http|https):\/\/[^ "]+$/.test(e),generateUUID:(e,t)=>t&&e?$(e,t):L(),generateSearchId:(e,t)=>`${e}#${t}`,getKeyfromSearchId:e=>{let[t,n]=e.split("#");return{key:t,variantId:n}}},N=gt;var ft={handleException:(e,t,n)=>{t.knownError?(t.logError&&h.logError(e,t),n.status(t.status).json({status:t.status,error:t.error})):t.status&&t.error?(h.logException(e,t),n.status(t.status).json({...t.error,status:t.status})):(h.logException(e,t),n.status(500).json({status:500,error:m.INTERNAL_SERVER_ERROR}))},generateResponse:(e,t,n)=>({status:e,data:t,error:n}),generateError:(e,t,n=!0,r=!1)=>({status:e,error:t,knownError:n,logError:r})},E=ft;var f=S(require("assert"));var It=async(e,t,n="GET",r={},s)=>{let a={method:n,headers:{"Content-Type":"application/json",...r}};n!=="GET"&&s&&(a.body=JSON.stringify(s));let u=`${e}${t?"/"+t:""}`;try{let i=await fetch(u,a);if(!i.ok){let l=await i.json().catch(()=>i.text());throw{status:i.status,statusText:i.statusText,error:l||{status:i.status,error:i.statusText}}}let d=await i.json();return h.logMessage("Fetch",`API call successful: URL-${u}, Status- ${i.status}`),{status:i.status,statusText:i.statusText,data:d.data}}catch(i){throw h.logError("Fetch",`API call failed: URL-${u}, Status- ${i.status||500}, Error- ${h.inspect(i.error||i)}`),{status:i.status||500,statusText:i.statusText||m.INTERNAL_SERVER_ERROR,error:i.error||{status:i.status||500,error:i.statusText||m.SOMETHING_WENT_WRONG}}}},K=It;var O={maxTokenAge:"30 days",userPrivateKeys:"[]",userPublicKeys:"[]",anonymousPrivateKeys:"[]",anonymousPublicKeys:"[]",systemPrivateKeys:"[]",systemPublicKeys:"[]",adminPrivateKeys:"[]",adminPublicKeys:"[]"},v={allowAnonymous:!1,allowSystem:!0,allowUser:!0,allowCDN:!1},M=class{maxTokenAge;userPrivateKeys;userPublicKeys;anonymousPrivateKeys;anonymousPublicKeys;systemPrivateKeys;systemPublicKeys;adminPrivateKeys;adminPublicKeys;constructor(t=O){let{maxTokenAge:n,userPrivateKeys:r,userPublicKeys:s,anonymousPrivateKeys:a,anonymousPublicKeys:u,systemPrivateKeys:i,systemPublicKeys:d,adminPrivateKeys:l,adminPublicKeys:c}={...O,...t};this.maxTokenAge=n,this.userPrivateKeys=JSON.parse(r),this.userPublicKeys=JSON.parse(s),this.anonymousPrivateKeys=JSON.parse(a),this.anonymousPublicKeys=JSON.parse(u),this.systemPrivateKeys=JSON.parse(i),this.systemPublicKeys=JSON.parse(d),this.adminPrivateKeys=JSON.parse(l),this.adminPublicKeys=JSON.parse(c),this.logWarnings()}logWarnings(){let t=(n,r,s)=>r.length>s&&h.logWarning("AuthUtility",`More than ${s} ${n} keys provided. This is not recommended.`);t("user private",this.userPrivateKeys,3),t("user public",this.userPublicKeys,3),t("anonymous private",this.anonymousPrivateKeys,1),t("anonymous public",this.anonymousPublicKeys,3),t("system private",this.systemPrivateKeys,1),t("system public",this.systemPublicKeys,3),t("admin private",this.adminPrivateKeys,1),t("admin public",this.adminPublicKeys,3)}async createSignedJWT(t,n,r){let s=await(0,T.importPKCS8)(n,"RS256");return await new T.SignJWT(t).setProtectedHeader({alg:"RS256"}).setExpirationTime(r).setIssuedAt().sign(s)}async verifySignedJWT(t,n,r){for(let u=n.length-1;u>0;u--)try{let i=await(0,T.importSPKI)(n[u],"RS256");return(await(0,T.jwtVerify)(t,i,{clockTolerance:30,maxTokenAge:r})).payload}catch{continue}let s=await(0,T.importSPKI)(n[0],"RS256");return(await(0,T.jwtVerify)(t,s,{clockTolerance:30,maxTokenAge:r})).payload}async createAnonymousToken(t,n){(0,f.default)(this.anonymousPrivateKeys.length,m.ANONYMOUS_PRIVATE_KEY_NOT_FOUND),(0,f.default)(N.isUUID(t),m.INVALID_UUID);let r={id:t,type:"Anon",...n};return await this.createSignedJWT(r,this.anonymousPrivateKeys[this.anonymousPrivateKeys.length-1],this.maxTokenAge)}async verifyAnonymousToken(t){(0,f.default)(this.anonymousPublicKeys.length,m.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);let n=await this.verifySignedJWT(t,this.anonymousPublicKeys,this.maxTokenAge);return(0,f.default)(n.type==="Anon",m.INVALID_AUTH_TYPE),n}async createUserToken(t,n){(0,f.default)(this.userPrivateKeys.length,m.USER_PRIVATE_KEY_NOT_FOUND),(0,f.default)(N.isUUID(t),m.INVALID_UUID);let r={id:t,type:"User",...n};return await this.createSignedJWT(r,this.userPrivateKeys[this.userPrivateKeys.length-1],this.maxTokenAge)}async verifyUserToken(t){(0,f.default)(this.userPublicKeys.length,m.USER_PUBLIC_KEY_NOT_FOUND);let n=await this.verifySignedJWT(t,this.userPublicKeys,this.maxTokenAge);return(0,f.default)(n.type==="User",m.INVALID_AUTH_TYPE),n}async createSystemToken(t,n){(0,f.default)(this.systemPrivateKeys.length,m.SYSTEM_PRIVATE_KEY_NOT_FOUND);let r={id:t,type:"System",...n};return await this.createSignedJWT(r,this.systemPrivateKeys[this.systemPrivateKeys.length-1],"5 min")}async verifySystemToken(t){(0,f.default)(this.systemPublicKeys.length,m.USER_PUBLIC_KEY_NOT_FOUND);let n=await this.verifySignedJWT(t,this.systemPublicKeys,"5 min");return(0,f.default)(n.type==="System",m.INVALID_AUTH_TYPE),n}async createAdminToken(t,n,r){(0,f.default)(this.adminPrivateKeys.length,m.ADMIN_PRIVATE_KEY_NOT_FOUND),(0,f.default)(N.isEmail(t),m.INVALID_EMAIL),(0,f.default)(N.isURL(n),m.INVALID_VERIFIER);let s={email:t,type:"Admin",verifier:n,...r};return await this.createSignedJWT(s,this.adminPrivateKeys[this.adminPrivateKeys.length-1],this.maxTokenAge)}async verifyAdminToken(t,n,r){(0,f.default)(this.adminPublicKeys.length,m.ADMIN_PUBLIC_KEY_NOT_FOUND);let s=await this.verifySignedJWT(t,this.adminPublicKeys,this.maxTokenAge);if((0,f.default)(s.type==="Admin",m.INVALID_AUTH_TYPE),r){let a=await K(s.verifier,"","POST",{},{token:t,permissions:n});if((0,f.default)(a.data.isTokenValid===!0,m.INVALID_TOKEN),a.data.hasPermissions!==!0)throw E.generateError(403,m.INVALID_PERMISSIONS)}return s}AuthMiddleware(t=v,n=[]){let{allowAnonymous:r,allowSystem:s,allowUser:a,allowCDN:u}={...v,...t};return async(i,d,l)=>{try{let[c,p]=i.get("Authorization")?.split(" ")||[];if(!p)throw new Error(m.INVALID_TOKEN);let A;switch(c){case"Anon":if(!r)throw E.generateError(403,m.ANONYMOUS_SESSION_NOT_ALLOWED);A=await this.verifyAnonymousToken(p);break;case"User":if(!a)throw E.generateError(403,m.USER_SESSION_NOT_ALLOWED);A=await this.verifyUserToken(p);break;case"System":if(!s)throw E.generateError(403,m.SYSTEM_SESSION_NOT_ALLOWED);A=await this.verifySystemToken(p),h.logMessage("AuthMiddleware",`System Name - ${A.id}`);break;case"Admin":A=await this.verifyAdminToken(p,n,!0),h.logMessage("AuthMiddleware",`Admin - ${A.email}`);break;case"CDN":if(!u)throw E.generateError(403,m.CDN_SESSION_NOT_ALLOWED);(0,f.default)(["E3CQMOP5FX6KD1","E3TNCKKZ3FOX9W"].includes(p),m.INVALID_TOKEN),h.logMessage("AuthMiddleware",`CDN DistributionId - ${p}`);break;default:throw E.generateError(403,m.INVALID_AUTH_TYPE)}d.locals.auth={authType:c,token:p,...A},l()}catch(c){h.logError("AuthMiddleware",c),E.handleException("AuthMiddleware",E.generateError(401,c.error||m.TOKEN_EXPIRED,!0),d)}}}},X=M;0&&(module.exports={AuthUtility,DefaultAuthMiddlewareConfig,DefaultAuthUtilityConfig,DynamoDB,Fetch,Logger,ResponseUtility,Schema,Utils});
1
+ "use strict";var ft=Object.create;var x=Object.defineProperty;var At=Object.getOwnPropertyDescriptor;var Ct=Object.getOwnPropertyNames;var bt=Object.getPrototypeOf,Tt=Object.prototype.hasOwnProperty;var St=(r,t)=>{for(var e in t)x(r,e,{get:t[e],enumerable:!0})},H=(r,t,e,s)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Ct(t))!Tt.call(r,i)&&i!==e&&x(r,i,{get:()=>t[i],enumerable:!(s=At(t,i))||s.enumerable});return r};var E=(r,t,e)=>(e=r!=null?ft(bt(r)):{},H(t||!r||!r.__esModule?x(e,"default",{value:r,enumerable:!0}):e,r)),Dt=r=>H(x({},"__esModule",{value:!0}),r);var kt={};St(kt,{AddressType:()=>nt,ApplicableTo:()=>pt,AuthUtility:()=>st,CartState:()=>gt,CountryCurrencyMap:()=>P,CouponCategory:()=>z,CouponDiscountMethod:()=>G,CouponType:()=>lt,CurrencySymbolMap:()=>k,CustomerStatus:()=>mt,DEFAULT_CART_CONFIG:()=>$t,DefaultAuthMiddlewareConfig:()=>M,DefaultAuthUtilityConfig:()=>w,DynamoDB:()=>Y,Fetch:()=>v,GenderCategory:()=>ct,ImageResolution:()=>ot,LineItemNotFoundError:()=>W,Logger:()=>f,OperationalCountry:()=>at,OperationalCountryCurrency:()=>ut,OperationalLocale:()=>dt,OrderState:()=>ht,PaymentMode:()=>It,PaymentStatus:()=>yt,ResponseUtility:()=>A,Schema:()=>q,Utils:()=>T});module.exports=Dt(kt);var u=require("@aws-sdk/client-dynamodb"),m=require("@aws-sdk/util-dynamodb"),_=class{client;returnItemCollectionMetrics;logCapacity;region;marshall=m.marshall;unmarshall=m.unmarshall;ReturnValue=u.ReturnValue;ReturnItemCollectionMetrics=u.ReturnItemCollectionMetrics;ReturnValuesOnConditionCheckFailure=u.ReturnValuesOnConditionCheckFailure;constructor({region:t,returnItemCollectionMetrics:e=u.ReturnItemCollectionMetrics.NONE,logCapacity:s=!1}){this.region=t,this.returnItemCollectionMetrics=e,this.logCapacity=s,this.client=new u.DynamoDBClient({region:this.region})}log(t,e,s){this.logCapacity&&console.log(t,"Capacity:",e,"Size:",s)}async putItem(t,e,s,i,n,a=u.ReturnValue.NONE,o=u.ReturnValuesOnConditionCheckFailure.ALL_OLD){let d={TableName:t,Item:(0,m.marshall)(e,{removeUndefinedValues:!0,convertClassInstanceToMap:!0}),ConditionExpression:s,ExpressionAttributeNames:i,ExpressionAttributeValues:n,ReturnValues:a,ReturnConsumedCapacity:u.ReturnConsumedCapacity.INDEXES,ReturnValuesOnConditionCheckFailure:o,ReturnItemCollectionMetrics:this.returnItemCollectionMetrics},l=new u.PutItemCommand(d),p=await this.client.send(l);return this.log("Put",p.ConsumedCapacity,p.ItemCollectionMetrics),(0,m.unmarshall)(p.Attributes||{})}async transactWriteItems(t){let e={TransactItems:t.map(n=>(n.Put&&(n.Put.Item=(0,m.marshall)(n.Put.Item,{removeUndefinedValues:!0,convertClassInstanceToMap:!0})),n.Update&&(n.Update.Key=(0,m.marshall)(n.Update.Key)),n.Delete&&(n.Delete.Key=(0,m.marshall)(n.Delete.Key)),n)),ReturnConsumedCapacity:u.ReturnConsumedCapacity.INDEXES,ReturnItemCollectionMetrics:this.returnItemCollectionMetrics},s=new u.TransactWriteItemsCommand(e),i=await this.client.send(s);this.log("Transaction",i.ConsumedCapacity,i.ItemCollectionMetrics)}async getItem(t,e,s=!1,i,n){let a={TableName:t,Key:(0,m.marshall)(e),ConsistentRead:s,ProjectionExpression:i,ExpressionAttributeNames:n,ReturnConsumedCapacity:u.ReturnConsumedCapacity.TOTAL},o=new u.GetItemCommand(a),d=await this.client.send(o);return this.log("Read",d.ConsumedCapacity),(0,m.unmarshall)(d.Item||{})}async batchGetItem(t,e,s=!1,i,n){let a={RequestItems:{[t]:{Keys:e.map(l=>(0,m.marshall)(l)),ConsistentRead:s,ProjectionExpression:i,ExpressionAttributeNames:n}},ReturnConsumedCapacity:u.ReturnConsumedCapacity.TOTAL},o=new u.BatchGetItemCommand(a),d=await this.client.send(o);return this.log("BatchRead",d.ConsumedCapacity),d.Responses?.[t]?.map(l=>(0,m.unmarshall)(l))||[]}async queryItems(t,e,s=!1,i,n,a,o){let d={TableName:t,KeyConditionExpression:e,ExpressionAttributeValues:a,ConsistentRead:s,ProjectionExpression:i,ExpressionAttributeNames:n,ExclusiveStartKey:o,ReturnConsumedCapacity:u.ReturnConsumedCapacity.TOTAL},l=new u.QueryCommand(d),p=await this.client.send(l);return this.log("Query",p.ConsumedCapacity),{items:p.Items?.map(h=>(0,m.unmarshall)(h))||[],lastEvaluatedKey:p.LastEvaluatedKey}}async scanItems(t,e,s=!1,i,n,a,o){let d={TableName:t,FilterExpression:e,ExpressionAttributeValues:a,ConsistentRead:s,ProjectionExpression:i,ExpressionAttributeNames:n,ExclusiveStartKey:o,ReturnConsumedCapacity:u.ReturnConsumedCapacity.TOTAL},l=new u.ScanCommand(d),p=await this.client.send(l);return this.log("Scan",p.ConsumedCapacity),{items:p.Items?.map(h=>(0,m.unmarshall)(h))||[],lastEvaluatedKey:p.LastEvaluatedKey}}async partiQL(t,e=[],s,i=!1){let n={Statement:t,Parameters:e,ConsistentRead:i,NextToken:s,ReturnConsumedCapacity:u.ReturnConsumedCapacity.INDEXES},a=new u.ExecuteStatementCommand(n),o=await this.client.send(a);return this.log("PartiQL",o.ConsumedCapacity),{Items:o.Items?.map(d=>(0,m.unmarshall)(d))||[],nextToken:o.NextToken,lastEvaluatedKey:o.LastEvaluatedKey}}async updateItem(t,e,s,i,n,a,o=u.ReturnValue.UPDATED_NEW,d=u.ReturnValuesOnConditionCheckFailure.ALL_OLD){let l={TableName:t,Key:(0,m.marshall)(e),ConditionExpression:s,UpdateExpression:i,ExpressionAttributeNames:n,ExpressionAttributeValues:a,ReturnValues:o,ReturnConsumedCapacity:u.ReturnConsumedCapacity.INDEXES,ReturnValuesOnConditionCheckFailure:d,ReturnItemCollectionMetrics:this.returnItemCollectionMetrics},p=new u.UpdateItemCommand(l),h=await this.client.send(p);return this.log("Update",h.ConsumedCapacity,h.ItemCollectionMetrics),(0,m.unmarshall)(h.Attributes||{})}async deleteItem(t,e,s,i,n,a=u.ReturnValue.ALL_OLD,o=u.ReturnValuesOnConditionCheckFailure.ALL_OLD){let d={TableName:t,Key:(0,m.marshall)(e),ConditionExpression:s,ExpressionAttributeNames:i,ExpressionAttributeValues:n,ReturnValues:a,ReturnConsumedCapacity:u.ReturnConsumedCapacity.INDEXES,ReturnValuesOnConditionCheckFailure:o,ReturnItemCollectionMetrics:this.returnItemCollectionMetrics},l=new u.DeleteItemCommand(d),p=await this.client.send(l);return this.log("Delete",p.ConsumedCapacity,p.ItemCollectionMetrics),(0,m.unmarshall)(p.Attributes||{})}async getItemByIndex(t,e,s,i=!1,n,a,o,d){let l={TableName:t,IndexName:e,KeyConditionExpression:s,ExpressionAttributeValues:o,ExclusiveStartKey:d,ConsistentRead:i,ProjectionExpression:n,ExpressionAttributeNames:a,ReturnConsumedCapacity:u.ReturnConsumedCapacity.INDEXES},p=new u.QueryCommand(l),h=await this.client.send(p);return this.log("GetItemByIndex",h.ConsumedCapacity),{Items:h.Items?.map(b=>(0,m.unmarshall)(b))||[],lastEvaluatedKey:h.LastEvaluatedKey}}},Y=_;var J={$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:"^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$"},variantId:{type:"string",pattern:"^(?!\\s)(?!.*\\s$)[A-Z0-9-]{4,16}$"},firstName:{$ref:"#/definitions/requiredText30"},lastName:{$ref:"#/definitions/text30"},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:["IN"]},currency:{type:"string",enum:["INR"]},locale:{type:"string",enum:["en-IN"]},addressType:{type:"string",enum:["shipping","billing","shipping&billing"]},address:{type:"object",properties:{firstName:{$ref:"standards#/definitions/firstName"},lastName:{$ref:"standards#/definitions/lastName"},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 Pt={getStandardSchemaDefinition(){return J}},q=Pt;var C=require("jose");var g=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"});var j=E(require("util")),S={logException:(r,t)=>{console.error(`Exception Occurred in Function: ${r}, Error: ${S.inspect(t)}`)},logError:(r,t)=>{console.error(`Error Occurred in Function: ${r}, Error: ${S.inspect(t)}`)},logWarning:(r,t)=>{console.warn(`Warning in Function: ${r} - ${S.inspect(t)}`)},logMessage:(r,t)=>{console.log(`Message in Function: ${r} - ${S.inspect(t)}`)},logInvalidPayload:(r,t)=>{console.error(`Invalid Payload received for Function: ${r}, Error: ${S.inspect(t)}`)},inspect:r=>typeof r=="string"?r:j.default.inspect(r)},f=S;var Q=E(require("crypto")),R=new Uint8Array(256),L=R.length;function K(){return L>R.length-16&&(Q.default.randomFillSync(R),L=0),R.slice(L,L+=16)}var Z=/^(?:[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 Nt(r){return typeof r=="string"&&Z.test(r)}var X=Nt;var I=[];for(let r=0;r<256;++r)I.push((r+256).toString(16).slice(1));function O(r,t=0){return I[r[t+0]]+I[r[t+1]]+I[r[t+2]]+I[r[t+3]]+"-"+I[r[t+4]]+I[r[t+5]]+"-"+I[r[t+6]]+I[r[t+7]]+"-"+I[r[t+8]]+I[r[t+9]]+"-"+I[r[t+10]]+I[r[t+11]]+I[r[t+12]]+I[r[t+13]]+I[r[t+14]]+I[r[t+15]]}function xt(r){if(!X(r))throw TypeError("Invalid UUID");let t,e=new Uint8Array(16);return e[0]=(t=parseInt(r.slice(0,8),16))>>>24,e[1]=t>>>16&255,e[2]=t>>>8&255,e[3]=t&255,e[4]=(t=parseInt(r.slice(9,13),16))>>>8,e[5]=t&255,e[6]=(t=parseInt(r.slice(14,18),16))>>>8,e[7]=t&255,e[8]=(t=parseInt(r.slice(19,23),16))>>>8,e[9]=t&255,e[10]=(t=parseInt(r.slice(24,36),16))/1099511627776&255,e[11]=t/4294967296&255,e[12]=t>>>24&255,e[13]=t>>>16&255,e[14]=t>>>8&255,e[15]=t&255,e}var tt=xt;function Lt(r){r=unescape(encodeURIComponent(r));let t=[];for(let e=0;e<r.length;++e)t.push(r.charCodeAt(e));return t}var Rt="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Ot="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function U(r,t,e){function s(i,n,a,o){var d;if(typeof i=="string"&&(i=Lt(i)),typeof n=="string"&&(n=tt(n)),((d=n)===null||d===void 0?void 0:d.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+i.length);if(l.set(n),l.set(i,n.length),l=e(l),l[6]=l[6]&15|t,l[8]=l[8]&63|128,a){o=o||0;for(let p=0;p<16;++p)a[o+p]=l[p];return a}return O(l)}try{s.name=r}catch{}return s.DNS=Rt,s.URL=Ot,s}var et=E(require("crypto")),B={randomUUID:et.default.randomUUID};function vt(r,t,e){if(B.randomUUID&&!t&&!r)return B.randomUUID();r=r||{};let s=r.random||(r.rng||K)();if(s[6]=s[6]&15|64,s[8]=s[8]&63|128,t){e=e||0;for(let i=0;i<16;++i)t[e+i]=s[i];return t}return O(s)}var V=vt;var rt=E(require("crypto"));function wt(r){return Array.isArray(r)?r=Buffer.from(r):typeof r=="string"&&(r=Buffer.from(r,"utf8")),rt.default.createHash("sha1").update(r).digest()}var it=wt;var Mt=U("v5",80,it),F=Mt;var _t={isUUID:r=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(r),isEmail:r=>/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/.test(r),isURL:r=>/^(http|https):\/\/[^ "]+$/.test(r),generateUUID:(r,t)=>t&&r?F(r,t):V(),generateSearchId:(r,t)=>`${r}#${t}`,getKeyfromSearchId:r=>{let[t,e]=r.split("#");return{key:t,variantId:e}}},T=_t;var Kt={handleException:(r,t,e)=>{t.knownError?(t.logError&&f.logError(r,t),e.status(t.status).json({status:t.status,error:t.error})):t.status&&t.error?(f.logException(r,t),e.status(t.status).json({...t.error,status:t.status})):(f.logException(r,t),e.status(500).json({status:500,error:g.INTERNAL_SERVER_ERROR}))},generateResponse:(r,t,e)=>({status:r,data:t,error:e}),generateError:(r,t,e=!0,s=!1)=>({status:r,error:t,knownError:e,logError:s})},A=Kt;var y=E(require("assert"));var Ut=async(r,t,e="GET",s={},i)=>{let n={method:e,headers:{"Content-Type":"application/json",...s}};e!=="GET"&&i&&(n.body=JSON.stringify(i));let a=`${r}${t?"/"+t:""}`;try{let o=await fetch(a,n);if(!o.ok){let l=await o.json().catch(()=>o.text());throw{status:o.status,statusText:o.statusText,error:l||{status:o.status,error:o.statusText}}}let d=await o.json();return f.logMessage("Fetch",`API call successful: URL-${a}, Status- ${o.status}`),{status:o.status,statusText:o.statusText,data:d.data}}catch(o){throw f.logError("Fetch",`API call failed: URL-${a}, Status- ${o.status||500}, Error- ${f.inspect(o.error||o)}`),{status:o.status||500,statusText:o.statusText||g.INTERNAL_SERVER_ERROR,error:o.error||{status:o.status||500,error:o.statusText||g.SOMETHING_WENT_WRONG}}}},v=Ut;var w={maxTokenAge:"30 days",userPrivateKeys:"[]",userPublicKeys:"[]",anonymousPrivateKeys:"[]",anonymousPublicKeys:"[]",systemPrivateKeys:"[]",systemPublicKeys:"[]",adminPrivateKeys:"[]",adminPublicKeys:"[]"},M={allowAnonymous:!1,allowSystem:!0,allowUser:!0,allowCDN:!1},$=class{maxTokenAge;userPrivateKeys;userPublicKeys;anonymousPrivateKeys;anonymousPublicKeys;systemPrivateKeys;systemPublicKeys;adminPrivateKeys;adminPublicKeys;constructor(t=w){let{maxTokenAge:e,userPrivateKeys:s,userPublicKeys:i,anonymousPrivateKeys:n,anonymousPublicKeys:a,systemPrivateKeys:o,systemPublicKeys:d,adminPrivateKeys:l,adminPublicKeys:p}={...w,...t};this.maxTokenAge=e,this.userPrivateKeys=JSON.parse(s),this.userPublicKeys=JSON.parse(i),this.anonymousPrivateKeys=JSON.parse(n),this.anonymousPublicKeys=JSON.parse(a),this.systemPrivateKeys=JSON.parse(o),this.systemPublicKeys=JSON.parse(d),this.adminPrivateKeys=JSON.parse(l),this.adminPublicKeys=JSON.parse(p),this.logWarnings()}logWarnings(){let t=(e,s,i)=>s.length>i&&f.logWarning("AuthUtility",`More than ${i} ${e} keys provided. This is not recommended.`);t("user private",this.userPrivateKeys,3),t("user public",this.userPublicKeys,3),t("anonymous private",this.anonymousPrivateKeys,1),t("anonymous public",this.anonymousPublicKeys,3),t("system private",this.systemPrivateKeys,1),t("system public",this.systemPublicKeys,3),t("admin private",this.adminPrivateKeys,1),t("admin public",this.adminPublicKeys,3)}async createSignedJWT(t,e,s){let i=await(0,C.importPKCS8)(e,"RS256");return await new C.SignJWT(t).setProtectedHeader({alg:"RS256"}).setExpirationTime(s).setIssuedAt().sign(i)}async verifySignedJWT(t,e,s){for(let a=e.length-1;a>0;a--)try{let o=await(0,C.importSPKI)(e[a],"RS256");return(await(0,C.jwtVerify)(t,o,{clockTolerance:30,maxTokenAge:s})).payload}catch{continue}let i=await(0,C.importSPKI)(e[0],"RS256");return(await(0,C.jwtVerify)(t,i,{clockTolerance:30,maxTokenAge:s})).payload}async createAnonymousToken(t,e){(0,y.default)(this.anonymousPrivateKeys.length,g.ANONYMOUS_PRIVATE_KEY_NOT_FOUND),(0,y.default)(T.isUUID(t),g.INVALID_UUID);let s={id:t,type:"Anon",...e};return await this.createSignedJWT(s,this.anonymousPrivateKeys[this.anonymousPrivateKeys.length-1],this.maxTokenAge)}async verifyAnonymousToken(t){(0,y.default)(this.anonymousPublicKeys.length,g.ANONYMOUS_PUBLIC_KEY_NOT_FOUND);let e=await this.verifySignedJWT(t,this.anonymousPublicKeys,this.maxTokenAge);return(0,y.default)(e.type==="Anon",g.INVALID_AUTH_TYPE),e}async createUserToken(t,e){(0,y.default)(this.userPrivateKeys.length,g.USER_PRIVATE_KEY_NOT_FOUND),(0,y.default)(T.isUUID(t),g.INVALID_UUID);let s={id:t,type:"User",...e};return await this.createSignedJWT(s,this.userPrivateKeys[this.userPrivateKeys.length-1],this.maxTokenAge)}async verifyUserToken(t){(0,y.default)(this.userPublicKeys.length,g.USER_PUBLIC_KEY_NOT_FOUND);let e=await this.verifySignedJWT(t,this.userPublicKeys,this.maxTokenAge);return(0,y.default)(e.type==="User",g.INVALID_AUTH_TYPE),e}async createSystemToken(t,e){(0,y.default)(this.systemPrivateKeys.length,g.SYSTEM_PRIVATE_KEY_NOT_FOUND);let s={id:t,type:"System",...e};return await this.createSignedJWT(s,this.systemPrivateKeys[this.systemPrivateKeys.length-1],"5 min")}async verifySystemToken(t){(0,y.default)(this.systemPublicKeys.length,g.USER_PUBLIC_KEY_NOT_FOUND);let e=await this.verifySignedJWT(t,this.systemPublicKeys,"5 min");return(0,y.default)(e.type==="System",g.INVALID_AUTH_TYPE),e}async createAdminToken(t,e,s){(0,y.default)(this.adminPrivateKeys.length,g.ADMIN_PRIVATE_KEY_NOT_FOUND),(0,y.default)(T.isEmail(t),g.INVALID_EMAIL),(0,y.default)(T.isURL(e),g.INVALID_VERIFIER);let i={email:t,type:"Admin",verifier:e,...s};return await this.createSignedJWT(i,this.adminPrivateKeys[this.adminPrivateKeys.length-1],this.maxTokenAge)}async verifyAdminToken(t,e,s){(0,y.default)(this.adminPublicKeys.length,g.ADMIN_PUBLIC_KEY_NOT_FOUND);let i=await this.verifySignedJWT(t,this.adminPublicKeys,this.maxTokenAge);if((0,y.default)(i.type==="Admin",g.INVALID_AUTH_TYPE),s){let n=await v(i.verifier,"","POST",{},{token:t,permissions:e});if((0,y.default)(n.data.isTokenValid===!0,g.INVALID_TOKEN),n.data.hasPermissions!==!0)throw A.generateError(403,g.INVALID_PERMISSIONS)}return i}AuthMiddleware(t=M,e=[]){let{allowAnonymous:s,allowSystem:i,allowUser:n,allowCDN:a}={...M,...t};return async(o,d,l)=>{try{let[p,h]=o.get("Authorization")?.split(" ")||[];if(!h)throw new Error(g.INVALID_TOKEN);let b;switch(p){case"Anon":if(!s)throw A.generateError(403,g.ANONYMOUS_SESSION_NOT_ALLOWED);b=await this.verifyAnonymousToken(h);break;case"User":if(!n)throw A.generateError(403,g.USER_SESSION_NOT_ALLOWED);b=await this.verifyUserToken(h);break;case"System":if(!i)throw A.generateError(403,g.SYSTEM_SESSION_NOT_ALLOWED);b=await this.verifySystemToken(h),f.logMessage("AuthMiddleware",`System Name - ${b.id}`);break;case"Admin":b=await this.verifyAdminToken(h,e,!0),f.logMessage("AuthMiddleware",`Admin - ${b.email}`);break;case"CDN":if(!a)throw A.generateError(403,g.CDN_SESSION_NOT_ALLOWED);(0,y.default)(["E3CQMOP5FX6KD1","E3TNCKKZ3FOX9W"].includes(h),g.INVALID_TOKEN),f.logMessage("AuthMiddleware",`CDN DistributionId - ${h}`);break;default:throw A.generateError(403,g.INVALID_AUTH_TYPE)}d.locals.auth={authType:p,token:h,...b},l()}catch(p){f.logError("AuthMiddleware",p),A.handleException("AuthMiddleware",A.generateError(401,p.error||g.TOKEN_EXPIRED,!0),d)}}}},st=$;var nt=(i=>(i.BILLING="billing",i.SHIPPING="shipping",i.BILLING_AND_SHIPPING="billing&shipping",i.NONE="none",i))(nt||{});var ot=(n=>(n.THUMBNAIL="thumbnail",n.SMALL="small",n.MEDIUM="medium",n.LARGE="large",n.ORIGINAL="original",n))(ot||{});var at=(t=>(t.IN="IN",t))(at||{}),ut=(t=>(t.INR="INR",t))(ut||{}),dt=(r=>(r["en-IN"]="en-IN",r))(dt||{}),P={IN:"INR"},k={INR:"\u20B9"},ct=(a=>(a.MALE="Male",a.FEMALE="Female",a.UNISEX="Unisex",a.KIDS="Kids",a.BOY="Boy",a.GIRL="Girl",a))(ct||{});var N=class r{price;country;constructor(t,e){if(this.country=e,t<0)throw new Error("InvalidPrice: Price cannot be negative.");this.price=t}getCountry(){return this.country}getRoundedPrice(){return r.getRoundedPrice(this.price,this.country)}getFormattedString(t,e={}){let s=e.displayAsInteger??!1,i=P[this.country];if(i===void 0)throw new Error("Currency mapping not found for CountryCode");let n=this.price,a=s?0:r.getDecimalPlaces(i),o={style:"currency",currency:i,signDisplay:"never",currencyDisplay:e.currencyDisplay,minimumFractionDigits:a,maximumFractionDigits:a};s&&(n=Math.round(n));try{return new Intl.NumberFormat(t,o).format(n)}catch(d){return console.error(`Error formatting price for locale "${t}" and currency "${i}":`,d),`${k[i]??i} ${r.addThousandSeparators(n.toFixed(a))}`}}static getDecimalPlaces(t){switch(t){case"INR":default:return 2}}static addThousandSeparators(t){let e=t.split("."),s=e[0],i=e.length>1?"."+e[1]:"";return s.replace(/\B(?=(\d{3})+(?!\d))/g,",")+i}static getRoundedPrice(t,e){if(t<0)throw new Error("Price cannot be negative for rounding.");let s=P[e];if(s===void 0)throw new Error(`Currency mapping not found for CountryCode: ${e}`);let i=r.getDecimalPlaces(s),n=Math.pow(10,i);return Math.round(t*n)/n}static getCurrency(t){return P[t]}};N.getRoundedPrice(-1,"IN");var lt=(e=>(e.COUPON="coupon",e.AUTOMATIC="automatic",e))(lt||{}),G=(e=>(e.FLAT="flat",e.PERCENTAGE="percentage",e))(G||{}),z=(e=>(e.SHIPPING="SHIPPING",e.CUSTOMER="CUSTOMER",e))(z||{}),pt=(e=>(e.ALL="all",e.FTB="ftb",e))(pt||{});var gt=(i=>(i.ACTIVE="ACTIVE",i.FROZEN="FROZEN",i.MERGED="MERGED",i.ORDERED="ORDERED",i))(gt||{}),W=class extends Error{constructor(t){super(`Line item with ID '${t}' not found in the cart.`),this.name="LineItemNotFoundError"}},$t={expiresAtInSeconds:120*24*60*60};var mt=(a=>(a.CREATED="CREATED",a.REGISTERED_USER="REGISTERED_USER",a.ACTIVATED_USER="ACTIVATED_USER",a.EMAIL_OTP="EMAIL_OTP",a.EMAIL_PASSWORD="EMAIL_PASSWORD",a.PHONE_OTP="PHONE_OTP",a))(mt||{});var ht=(d=>(d.PENDING_PAYMENT="PENDING_PAYMENT",d.PROCESSING="PROCESSING",d.SHIPPED="SHIPPED",d.PARTIALLY_SHIPPED="PARTIALLY_SHIPPED",d.DELIVERED="DELIVERED",d.CANCELLED="CANCELLED",d.RETURNED="RETURNED",d.REFUNDED="REFUNDED",d))(ht||{});var yt=(a=>(a.PENDING="PENDING",a.AUTHORIZED="AUTHORIZED",a.CAPTURED="CAPTURED",a.FAILED="FAILED",a.REFUNDED="REFUNDED",a.PARTIALLY_REFUNDED="PARTIALLY_REFUNDED",a))(yt||{}),It=(o=>(o.PAY_LATER="PAY_LATER",o.CARD="CARD",o.CASH="CASH",o.NET_BANKING="NET_BANKING",o.WALLET="WALLET",o.COD="COD",o.UNKNOWN="UNKNOWN",o))(It||{});0&&(module.exports={AddressType,ApplicableTo,AuthUtility,CartState,CountryCurrencyMap,CouponCategory,CouponDiscountMethod,CouponType,CurrencySymbolMap,CustomerStatus,DEFAULT_CART_CONFIG,DefaultAuthMiddlewareConfig,DefaultAuthUtilityConfig,DynamoDB,Fetch,GenderCategory,ImageResolution,LineItemNotFoundError,Logger,OperationalCountry,OperationalCountryCurrency,OperationalLocale,OrderState,PaymentMode,PaymentStatus,ResponseUtility,Schema,Utils});
2
2
  //# sourceMappingURL=index.js.map