@cimplify/sdk 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.mts CHANGED
@@ -1972,6 +1972,11 @@ interface CheckoutResult {
1972
1972
  public_key?: string;
1973
1973
  }
1974
1974
 
1975
+ /**
1976
+ * Generate a cryptographically secure idempotency key.
1977
+ * Uses crypto.randomUUID if available, falls back to timestamp + random.
1978
+ */
1979
+ declare function generateIdempotencyKey(): string;
1975
1980
  /**
1976
1981
  * Checkout service with explicit error handling via Result type.
1977
1982
  *
@@ -1999,6 +2004,10 @@ declare class CheckoutService {
1999
2004
  /**
2000
2005
  * Process checkout with cart data.
2001
2006
  *
2007
+ * Automatically generates an idempotency key if not provided to ensure
2008
+ * payment safety. The same key is used across retries, preventing
2009
+ * duplicate charges if a network error occurs after payment processing.
2010
+ *
2002
2011
  * @example
2003
2012
  * ```typescript
2004
2013
  * const result = await client.checkout.process({
@@ -2824,6 +2833,12 @@ declare class LiteService {
2824
2833
  interface CimplifyConfig {
2825
2834
  publicKey?: string;
2826
2835
  credentials?: RequestCredentials;
2836
+ /** Request timeout in milliseconds (default: 30000) */
2837
+ timeout?: number;
2838
+ /** Maximum retry attempts for retryable errors (default: 3) */
2839
+ maxRetries?: number;
2840
+ /** Base delay between retries in milliseconds (default: 1000) */
2841
+ retryDelay?: number;
2827
2842
  }
2828
2843
  declare class CimplifyClient {
2829
2844
  private baseUrl;
@@ -2831,6 +2846,9 @@ declare class CimplifyClient {
2831
2846
  private publicKey;
2832
2847
  private credentials;
2833
2848
  private sessionToken;
2849
+ private timeout;
2850
+ private maxRetries;
2851
+ private retryDelay;
2834
2852
  private _catalogue?;
2835
2853
  private _cart?;
2836
2854
  private _checkout?;
@@ -2849,6 +2867,11 @@ declare class CimplifyClient {
2849
2867
  private saveSessionToken;
2850
2868
  private getHeaders;
2851
2869
  private updateSessionFromResponse;
2870
+ /**
2871
+ * Resilient fetch with timeout and automatic retries for network errors.
2872
+ * Uses exponential backoff: 1s, 2s, 4s between retries.
2873
+ */
2874
+ private resilientFetch;
2852
2875
  query<T = unknown>(query: string, variables?: Record<string, unknown>): Promise<T>;
2853
2876
  call<T = unknown>(method: string, args?: unknown): Promise<T>;
2854
2877
  get<T = unknown>(path: string): Promise<T>;
@@ -3392,4 +3415,4 @@ interface ApiResponse<T> {
3392
3415
  metadata?: ResponseMetadata;
3393
3416
  }
3394
3417
 
3395
- export { AUTHORIZATION_TYPE, AUTH_MUTATION, type AddOn, type AddOnDetails, type AddOnGroupDetails, type AddOnOption, type AddOnOptionDetails, type AddOnOptionPrice, type AddOnWithOptions, type AddToCartInput, type AddressData, type AdjustmentType, type AmountToPay, type ApiError, type ApiResponse, type AppliedDiscount, type AuthResponse, AuthService, type AuthStatus, type AuthorizationType, type AvailabilityCheck, type AvailabilityResult, type AvailableSlot, type BenefitType, type Booking, type BookingRequirementOverride, type BookingStatus, type BookingWithDetails, type BufferTimes, type Bundle, type BundleComponentData, type BundleComponentInfo, type BundlePriceType, type BundleProduct, type BundleSelectionData, type BundleSelectionInput, type BundleStoredSelection, type BundleSummary, type BundleWithDetails, type Business, type BusinessHours, type BusinessPreferences, BusinessService, type BusinessSettings, type BusinessType, type BusinessWithLocations, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CURRENCY_SYMBOLS, type CancelBookingInput, type CancelOrderInput, type CancellationPolicy, type Cart, type CartAddOn, type CartChannel, type CartItem, type CartItemDetails, CartOperations, type CartStatus, type CartSummary, type CartTotals, CatalogueQueries, type Category, type CategoryInfo, type CategorySummary, type ChangePasswordInput, type CheckSlotAvailabilityInput, type CheckoutAddressInfo, type CheckoutCustomerInfo, type CheckoutFormData, type CheckoutInput, type CheckoutMode, CheckoutService as CheckoutOperations, type CheckoutOrderType, type CheckoutPaymentMethod, type CheckoutResult, CheckoutService, type CheckoutStep, type ChosenPrice, CimplifyClient, type CimplifyConfig, CimplifyError, type Collection, type CollectionProduct, type CollectionSummary, type ComponentGroup, type ComponentGroupWithComponents, type ComponentPriceBreakdown, type ComponentSelectionInput, type ComponentSourceType, type Composite, type CompositeComponent, type CompositePriceBreakdown, type CompositePriceResult, type CompositePricingMode, type CompositeSelectionData, type ComponentSelectionInput as CompositeSelectionInput, type CompositeStoredSelection, type CompositeWithDetails, type ContactType, type CreateAddressInput, type CreateMobileMoneyInput, type Currency, type Customer, type CustomerAddress, type CustomerLinkPreferences, type CustomerMobileMoney, type CustomerServicePreferences, DEFAULT_COUNTRY, DEFAULT_CURRENCY, type DayAvailability, type DepositResult, type DepositType, type DeviceType, type DigitalProductType, type DiscountBreakdown, type DiscountDetails, type DisplayAddOn, type DisplayAddOnOption, type DisplayCart, type DisplayCartItem, type EnrollAndLinkOrderInput, type EnrollAndLinkOrderResult, type EnrollmentData, type Err, ErrorCode, type ErrorCodeType, type FeeBearerType, type FormatCompactOptions, type FormatPriceOptions, type FulfillmentLink, type FulfillmentStatus, type FulfillmentType, type GetAvailableSlotsInput, type GetOrdersOptions, type GetProductsOptions, type GroupPricingBehavior, type InitializePaymentResult, InventoryService, type InventorySummary, type InventoryType, type KitchenOrderItem, type KitchenOrderResult, LINK_MUTATION, LINK_QUERY, type LineConfiguration, type LineItem, type LineType, type LinkData, type LinkEnrollResult, LinkService, type LinkSession, type LinkStatusResult, type LiteBootstrap, LiteService, type Location, type LocationAppointment, type LocationProductPrice, type LocationStock, type LocationTaxBehavior, type LocationTaxOverrides, type LocationTimeProfile, type LocationWithDetails, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, type MobileMoneyData, type MobileMoneyDetails, type MobileMoneyProvider, type Money, type MutationRequest, ORDER_MUTATION, ORDER_TYPE, type Ok, type Order, type OrderChannel, type OrderFilter, type OrderFulfillmentSummary, type OrderGroup, type OrderGroupDetails, type OrderGroupPayment, type OrderGroupPaymentState, type OrderGroupPaymentSummary, type OrderHistory, type OrderLineState, type OrderLineStatus, type OrderPaymentEvent, OrderQueries, type OrderSplitDetail, type OrderStatus, type OtpResult, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, type Pagination, type PaginationParams, type ParsedPrice, type Payment, type PaymentErrorDetails, type PaymentMethod, type PaymentMethodType, type PaymentProcessingState, type PaymentProvider, type PaymentResponse, type PaymentState, type PaymentStatus, type PaymentStatusResponse, type PickupTime, type PickupTimeType, type Price, type PriceAdjustment, type PriceDecisionPath, type PriceEntryType, type PriceInfo, type PricePathTaxInfo, type PriceSource, type PricingOverrides, type Product, type ProductAddOn, type ProductAvailability, type ProductStock, type ProductTimeProfile, type ProductType, type ProductVariant, type ProductVariantValue, type ProductWithDetails, type ProductWithPrice, QueryBuilder, type QueryRequest, type RefundOrderInput, type ReminderMethod, type ReminderSettings, type RequestOtpInput, type RescheduleBookingInput, type ResourceAssignment, type ResourceAvailabilityException, type ResourceAvailabilityRule, type ResourceType, type ResponseMetadata, type Result, type RevokeAllSessionsResult, type RevokeSessionResult, type Room, type SalesChannel, type SchedulingMetadata, type SchedulingResult, SchedulingService, type SearchOptions, type SelectedAddOnOption, type Service, type ServiceAvailabilityException, type ServiceAvailabilityParams, type ServiceAvailabilityResult, type ServiceAvailabilityRule, type ServiceCharge, type ServiceNotes, type ServiceScheduleRequest, type ServiceStaffRequirement, type ServiceStatus, type ServiceWithStaff, type Staff, type StaffAssignment, type StaffAvailabilityException, type StaffAvailabilityRule, type StaffBookingProfile, type StaffRole, type StaffScheduleItem, type Stock, type StockLevel, type StockOwnershipType, type StockStatus, type StorefrontBootstrap, type SubmitAuthorizationInput, type Table, type TableInfo, type TaxComponent, type TaxInfo, type TaxPathComponent, type TimeRange, type TimeRanges, type TimeSlot, type UICart, type UICartBusiness, type UICartCustomer, type UICartLocation, type UICartPricing, type UpdateAddressInput, type UpdateCartItemInput, type UpdateOrderStatusInput, type UpdateProfileInput, type VariantAxis, type VariantAxisSelection, type VariantAxisValue, type VariantAxisWithValues, type VariantDetails, type VariantDetailsDTO, type VariantDisplayAttribute, type VariantLocationAvailability, type VariantStock, type VariantStrategy, type VerifyOtpInput, categorizePaymentError, combine, combineObject, createCimplifyClient, detectMobileMoneyProvider, err, extractPriceInfo, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatProductPrice, fromPromise, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getMarkupPercentage, getOrElse, getProductCurrency, isCimplifyError, isErr, isOk, isOnSale, isRetryableError, mapError, mapResult, normalizePaymentResponse, normalizeStatusResponse, ok, parsePrice, parsePricePath, parsedPriceToPriceInfo, query, toNullable, tryCatch, unwrap };
3418
+ export { AUTHORIZATION_TYPE, AUTH_MUTATION, type AddOn, type AddOnDetails, type AddOnGroupDetails, type AddOnOption, type AddOnOptionDetails, type AddOnOptionPrice, type AddOnWithOptions, type AddToCartInput, type AddressData, type AdjustmentType, type AmountToPay, type ApiError, type ApiResponse, type AppliedDiscount, type AuthResponse, AuthService, type AuthStatus, type AuthorizationType, type AvailabilityCheck, type AvailabilityResult, type AvailableSlot, type BenefitType, type Booking, type BookingRequirementOverride, type BookingStatus, type BookingWithDetails, type BufferTimes, type Bundle, type BundleComponentData, type BundleComponentInfo, type BundlePriceType, type BundleProduct, type BundleSelectionData, type BundleSelectionInput, type BundleStoredSelection, type BundleSummary, type BundleWithDetails, type Business, type BusinessHours, type BusinessPreferences, BusinessService, type BusinessSettings, type BusinessType, type BusinessWithLocations, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CURRENCY_SYMBOLS, type CancelBookingInput, type CancelOrderInput, type CancellationPolicy, type Cart, type CartAddOn, type CartChannel, type CartItem, type CartItemDetails, CartOperations, type CartStatus, type CartSummary, type CartTotals, CatalogueQueries, type Category, type CategoryInfo, type CategorySummary, type ChangePasswordInput, type CheckSlotAvailabilityInput, type CheckoutAddressInfo, type CheckoutCustomerInfo, type CheckoutFormData, type CheckoutInput, type CheckoutMode, CheckoutService as CheckoutOperations, type CheckoutOrderType, type CheckoutPaymentMethod, type CheckoutResult, CheckoutService, type CheckoutStep, type ChosenPrice, CimplifyClient, type CimplifyConfig, CimplifyError, type Collection, type CollectionProduct, type CollectionSummary, type ComponentGroup, type ComponentGroupWithComponents, type ComponentPriceBreakdown, type ComponentSelectionInput, type ComponentSourceType, type Composite, type CompositeComponent, type CompositePriceBreakdown, type CompositePriceResult, type CompositePricingMode, type CompositeSelectionData, type ComponentSelectionInput as CompositeSelectionInput, type CompositeStoredSelection, type CompositeWithDetails, type ContactType, type CreateAddressInput, type CreateMobileMoneyInput, type Currency, type Customer, type CustomerAddress, type CustomerLinkPreferences, type CustomerMobileMoney, type CustomerServicePreferences, DEFAULT_COUNTRY, DEFAULT_CURRENCY, type DayAvailability, type DepositResult, type DepositType, type DeviceType, type DigitalProductType, type DiscountBreakdown, type DiscountDetails, type DisplayAddOn, type DisplayAddOnOption, type DisplayCart, type DisplayCartItem, type EnrollAndLinkOrderInput, type EnrollAndLinkOrderResult, type EnrollmentData, type Err, ErrorCode, type ErrorCodeType, type FeeBearerType, type FormatCompactOptions, type FormatPriceOptions, type FulfillmentLink, type FulfillmentStatus, type FulfillmentType, type GetAvailableSlotsInput, type GetOrdersOptions, type GetProductsOptions, type GroupPricingBehavior, type InitializePaymentResult, InventoryService, type InventorySummary, type InventoryType, type KitchenOrderItem, type KitchenOrderResult, LINK_MUTATION, LINK_QUERY, type LineConfiguration, type LineItem, type LineType, type LinkData, type LinkEnrollResult, LinkService, type LinkSession, type LinkStatusResult, type LiteBootstrap, LiteService, type Location, type LocationAppointment, type LocationProductPrice, type LocationStock, type LocationTaxBehavior, type LocationTaxOverrides, type LocationTimeProfile, type LocationWithDetails, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, type MobileMoneyData, type MobileMoneyDetails, type MobileMoneyProvider, type Money, type MutationRequest, ORDER_MUTATION, ORDER_TYPE, type Ok, type Order, type OrderChannel, type OrderFilter, type OrderFulfillmentSummary, type OrderGroup, type OrderGroupDetails, type OrderGroupPayment, type OrderGroupPaymentState, type OrderGroupPaymentSummary, type OrderHistory, type OrderLineState, type OrderLineStatus, type OrderPaymentEvent, OrderQueries, type OrderSplitDetail, type OrderStatus, type OtpResult, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, type Pagination, type PaginationParams, type ParsedPrice, type Payment, type PaymentErrorDetails, type PaymentMethod, type PaymentMethodType, type PaymentProcessingState, type PaymentProvider, type PaymentResponse, type PaymentState, type PaymentStatus, type PaymentStatusResponse, type PickupTime, type PickupTimeType, type Price, type PriceAdjustment, type PriceDecisionPath, type PriceEntryType, type PriceInfo, type PricePathTaxInfo, type PriceSource, type PricingOverrides, type Product, type ProductAddOn, type ProductAvailability, type ProductStock, type ProductTimeProfile, type ProductType, type ProductVariant, type ProductVariantValue, type ProductWithDetails, type ProductWithPrice, QueryBuilder, type QueryRequest, type RefundOrderInput, type ReminderMethod, type ReminderSettings, type RequestOtpInput, type RescheduleBookingInput, type ResourceAssignment, type ResourceAvailabilityException, type ResourceAvailabilityRule, type ResourceType, type ResponseMetadata, type Result, type RevokeAllSessionsResult, type RevokeSessionResult, type Room, type SalesChannel, type SchedulingMetadata, type SchedulingResult, SchedulingService, type SearchOptions, type SelectedAddOnOption, type Service, type ServiceAvailabilityException, type ServiceAvailabilityParams, type ServiceAvailabilityResult, type ServiceAvailabilityRule, type ServiceCharge, type ServiceNotes, type ServiceScheduleRequest, type ServiceStaffRequirement, type ServiceStatus, type ServiceWithStaff, type Staff, type StaffAssignment, type StaffAvailabilityException, type StaffAvailabilityRule, type StaffBookingProfile, type StaffRole, type StaffScheduleItem, type Stock, type StockLevel, type StockOwnershipType, type StockStatus, type StorefrontBootstrap, type SubmitAuthorizationInput, type Table, type TableInfo, type TaxComponent, type TaxInfo, type TaxPathComponent, type TimeRange, type TimeRanges, type TimeSlot, type UICart, type UICartBusiness, type UICartCustomer, type UICartLocation, type UICartPricing, type UpdateAddressInput, type UpdateCartItemInput, type UpdateOrderStatusInput, type UpdateProfileInput, type VariantAxis, type VariantAxisSelection, type VariantAxisValue, type VariantAxisWithValues, type VariantDetails, type VariantDetailsDTO, type VariantDisplayAttribute, type VariantLocationAvailability, type VariantStock, type VariantStrategy, type VerifyOtpInput, categorizePaymentError, combine, combineObject, createCimplifyClient, detectMobileMoneyProvider, err, extractPriceInfo, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatProductPrice, fromPromise, generateIdempotencyKey, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getMarkupPercentage, getOrElse, getProductCurrency, isCimplifyError, isErr, isOk, isOnSale, isRetryableError, mapError, mapResult, normalizePaymentResponse, normalizeStatusResponse, ok, parsePrice, parsePricePath, parsedPriceToPriceInfo, query, toNullable, tryCatch, unwrap };
package/dist/index.d.ts CHANGED
@@ -1972,6 +1972,11 @@ interface CheckoutResult {
1972
1972
  public_key?: string;
1973
1973
  }
1974
1974
 
1975
+ /**
1976
+ * Generate a cryptographically secure idempotency key.
1977
+ * Uses crypto.randomUUID if available, falls back to timestamp + random.
1978
+ */
1979
+ declare function generateIdempotencyKey(): string;
1975
1980
  /**
1976
1981
  * Checkout service with explicit error handling via Result type.
1977
1982
  *
@@ -1999,6 +2004,10 @@ declare class CheckoutService {
1999
2004
  /**
2000
2005
  * Process checkout with cart data.
2001
2006
  *
2007
+ * Automatically generates an idempotency key if not provided to ensure
2008
+ * payment safety. The same key is used across retries, preventing
2009
+ * duplicate charges if a network error occurs after payment processing.
2010
+ *
2002
2011
  * @example
2003
2012
  * ```typescript
2004
2013
  * const result = await client.checkout.process({
@@ -2824,6 +2833,12 @@ declare class LiteService {
2824
2833
  interface CimplifyConfig {
2825
2834
  publicKey?: string;
2826
2835
  credentials?: RequestCredentials;
2836
+ /** Request timeout in milliseconds (default: 30000) */
2837
+ timeout?: number;
2838
+ /** Maximum retry attempts for retryable errors (default: 3) */
2839
+ maxRetries?: number;
2840
+ /** Base delay between retries in milliseconds (default: 1000) */
2841
+ retryDelay?: number;
2827
2842
  }
2828
2843
  declare class CimplifyClient {
2829
2844
  private baseUrl;
@@ -2831,6 +2846,9 @@ declare class CimplifyClient {
2831
2846
  private publicKey;
2832
2847
  private credentials;
2833
2848
  private sessionToken;
2849
+ private timeout;
2850
+ private maxRetries;
2851
+ private retryDelay;
2834
2852
  private _catalogue?;
2835
2853
  private _cart?;
2836
2854
  private _checkout?;
@@ -2849,6 +2867,11 @@ declare class CimplifyClient {
2849
2867
  private saveSessionToken;
2850
2868
  private getHeaders;
2851
2869
  private updateSessionFromResponse;
2870
+ /**
2871
+ * Resilient fetch with timeout and automatic retries for network errors.
2872
+ * Uses exponential backoff: 1s, 2s, 4s between retries.
2873
+ */
2874
+ private resilientFetch;
2852
2875
  query<T = unknown>(query: string, variables?: Record<string, unknown>): Promise<T>;
2853
2876
  call<T = unknown>(method: string, args?: unknown): Promise<T>;
2854
2877
  get<T = unknown>(path: string): Promise<T>;
@@ -3392,4 +3415,4 @@ interface ApiResponse<T> {
3392
3415
  metadata?: ResponseMetadata;
3393
3416
  }
3394
3417
 
3395
- export { AUTHORIZATION_TYPE, AUTH_MUTATION, type AddOn, type AddOnDetails, type AddOnGroupDetails, type AddOnOption, type AddOnOptionDetails, type AddOnOptionPrice, type AddOnWithOptions, type AddToCartInput, type AddressData, type AdjustmentType, type AmountToPay, type ApiError, type ApiResponse, type AppliedDiscount, type AuthResponse, AuthService, type AuthStatus, type AuthorizationType, type AvailabilityCheck, type AvailabilityResult, type AvailableSlot, type BenefitType, type Booking, type BookingRequirementOverride, type BookingStatus, type BookingWithDetails, type BufferTimes, type Bundle, type BundleComponentData, type BundleComponentInfo, type BundlePriceType, type BundleProduct, type BundleSelectionData, type BundleSelectionInput, type BundleStoredSelection, type BundleSummary, type BundleWithDetails, type Business, type BusinessHours, type BusinessPreferences, BusinessService, type BusinessSettings, type BusinessType, type BusinessWithLocations, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CURRENCY_SYMBOLS, type CancelBookingInput, type CancelOrderInput, type CancellationPolicy, type Cart, type CartAddOn, type CartChannel, type CartItem, type CartItemDetails, CartOperations, type CartStatus, type CartSummary, type CartTotals, CatalogueQueries, type Category, type CategoryInfo, type CategorySummary, type ChangePasswordInput, type CheckSlotAvailabilityInput, type CheckoutAddressInfo, type CheckoutCustomerInfo, type CheckoutFormData, type CheckoutInput, type CheckoutMode, CheckoutService as CheckoutOperations, type CheckoutOrderType, type CheckoutPaymentMethod, type CheckoutResult, CheckoutService, type CheckoutStep, type ChosenPrice, CimplifyClient, type CimplifyConfig, CimplifyError, type Collection, type CollectionProduct, type CollectionSummary, type ComponentGroup, type ComponentGroupWithComponents, type ComponentPriceBreakdown, type ComponentSelectionInput, type ComponentSourceType, type Composite, type CompositeComponent, type CompositePriceBreakdown, type CompositePriceResult, type CompositePricingMode, type CompositeSelectionData, type ComponentSelectionInput as CompositeSelectionInput, type CompositeStoredSelection, type CompositeWithDetails, type ContactType, type CreateAddressInput, type CreateMobileMoneyInput, type Currency, type Customer, type CustomerAddress, type CustomerLinkPreferences, type CustomerMobileMoney, type CustomerServicePreferences, DEFAULT_COUNTRY, DEFAULT_CURRENCY, type DayAvailability, type DepositResult, type DepositType, type DeviceType, type DigitalProductType, type DiscountBreakdown, type DiscountDetails, type DisplayAddOn, type DisplayAddOnOption, type DisplayCart, type DisplayCartItem, type EnrollAndLinkOrderInput, type EnrollAndLinkOrderResult, type EnrollmentData, type Err, ErrorCode, type ErrorCodeType, type FeeBearerType, type FormatCompactOptions, type FormatPriceOptions, type FulfillmentLink, type FulfillmentStatus, type FulfillmentType, type GetAvailableSlotsInput, type GetOrdersOptions, type GetProductsOptions, type GroupPricingBehavior, type InitializePaymentResult, InventoryService, type InventorySummary, type InventoryType, type KitchenOrderItem, type KitchenOrderResult, LINK_MUTATION, LINK_QUERY, type LineConfiguration, type LineItem, type LineType, type LinkData, type LinkEnrollResult, LinkService, type LinkSession, type LinkStatusResult, type LiteBootstrap, LiteService, type Location, type LocationAppointment, type LocationProductPrice, type LocationStock, type LocationTaxBehavior, type LocationTaxOverrides, type LocationTimeProfile, type LocationWithDetails, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, type MobileMoneyData, type MobileMoneyDetails, type MobileMoneyProvider, type Money, type MutationRequest, ORDER_MUTATION, ORDER_TYPE, type Ok, type Order, type OrderChannel, type OrderFilter, type OrderFulfillmentSummary, type OrderGroup, type OrderGroupDetails, type OrderGroupPayment, type OrderGroupPaymentState, type OrderGroupPaymentSummary, type OrderHistory, type OrderLineState, type OrderLineStatus, type OrderPaymentEvent, OrderQueries, type OrderSplitDetail, type OrderStatus, type OtpResult, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, type Pagination, type PaginationParams, type ParsedPrice, type Payment, type PaymentErrorDetails, type PaymentMethod, type PaymentMethodType, type PaymentProcessingState, type PaymentProvider, type PaymentResponse, type PaymentState, type PaymentStatus, type PaymentStatusResponse, type PickupTime, type PickupTimeType, type Price, type PriceAdjustment, type PriceDecisionPath, type PriceEntryType, type PriceInfo, type PricePathTaxInfo, type PriceSource, type PricingOverrides, type Product, type ProductAddOn, type ProductAvailability, type ProductStock, type ProductTimeProfile, type ProductType, type ProductVariant, type ProductVariantValue, type ProductWithDetails, type ProductWithPrice, QueryBuilder, type QueryRequest, type RefundOrderInput, type ReminderMethod, type ReminderSettings, type RequestOtpInput, type RescheduleBookingInput, type ResourceAssignment, type ResourceAvailabilityException, type ResourceAvailabilityRule, type ResourceType, type ResponseMetadata, type Result, type RevokeAllSessionsResult, type RevokeSessionResult, type Room, type SalesChannel, type SchedulingMetadata, type SchedulingResult, SchedulingService, type SearchOptions, type SelectedAddOnOption, type Service, type ServiceAvailabilityException, type ServiceAvailabilityParams, type ServiceAvailabilityResult, type ServiceAvailabilityRule, type ServiceCharge, type ServiceNotes, type ServiceScheduleRequest, type ServiceStaffRequirement, type ServiceStatus, type ServiceWithStaff, type Staff, type StaffAssignment, type StaffAvailabilityException, type StaffAvailabilityRule, type StaffBookingProfile, type StaffRole, type StaffScheduleItem, type Stock, type StockLevel, type StockOwnershipType, type StockStatus, type StorefrontBootstrap, type SubmitAuthorizationInput, type Table, type TableInfo, type TaxComponent, type TaxInfo, type TaxPathComponent, type TimeRange, type TimeRanges, type TimeSlot, type UICart, type UICartBusiness, type UICartCustomer, type UICartLocation, type UICartPricing, type UpdateAddressInput, type UpdateCartItemInput, type UpdateOrderStatusInput, type UpdateProfileInput, type VariantAxis, type VariantAxisSelection, type VariantAxisValue, type VariantAxisWithValues, type VariantDetails, type VariantDetailsDTO, type VariantDisplayAttribute, type VariantLocationAvailability, type VariantStock, type VariantStrategy, type VerifyOtpInput, categorizePaymentError, combine, combineObject, createCimplifyClient, detectMobileMoneyProvider, err, extractPriceInfo, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatProductPrice, fromPromise, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getMarkupPercentage, getOrElse, getProductCurrency, isCimplifyError, isErr, isOk, isOnSale, isRetryableError, mapError, mapResult, normalizePaymentResponse, normalizeStatusResponse, ok, parsePrice, parsePricePath, parsedPriceToPriceInfo, query, toNullable, tryCatch, unwrap };
3418
+ export { AUTHORIZATION_TYPE, AUTH_MUTATION, type AddOn, type AddOnDetails, type AddOnGroupDetails, type AddOnOption, type AddOnOptionDetails, type AddOnOptionPrice, type AddOnWithOptions, type AddToCartInput, type AddressData, type AdjustmentType, type AmountToPay, type ApiError, type ApiResponse, type AppliedDiscount, type AuthResponse, AuthService, type AuthStatus, type AuthorizationType, type AvailabilityCheck, type AvailabilityResult, type AvailableSlot, type BenefitType, type Booking, type BookingRequirementOverride, type BookingStatus, type BookingWithDetails, type BufferTimes, type Bundle, type BundleComponentData, type BundleComponentInfo, type BundlePriceType, type BundleProduct, type BundleSelectionData, type BundleSelectionInput, type BundleStoredSelection, type BundleSummary, type BundleWithDetails, type Business, type BusinessHours, type BusinessPreferences, BusinessService, type BusinessSettings, type BusinessType, type BusinessWithLocations, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CURRENCY_SYMBOLS, type CancelBookingInput, type CancelOrderInput, type CancellationPolicy, type Cart, type CartAddOn, type CartChannel, type CartItem, type CartItemDetails, CartOperations, type CartStatus, type CartSummary, type CartTotals, CatalogueQueries, type Category, type CategoryInfo, type CategorySummary, type ChangePasswordInput, type CheckSlotAvailabilityInput, type CheckoutAddressInfo, type CheckoutCustomerInfo, type CheckoutFormData, type CheckoutInput, type CheckoutMode, CheckoutService as CheckoutOperations, type CheckoutOrderType, type CheckoutPaymentMethod, type CheckoutResult, CheckoutService, type CheckoutStep, type ChosenPrice, CimplifyClient, type CimplifyConfig, CimplifyError, type Collection, type CollectionProduct, type CollectionSummary, type ComponentGroup, type ComponentGroupWithComponents, type ComponentPriceBreakdown, type ComponentSelectionInput, type ComponentSourceType, type Composite, type CompositeComponent, type CompositePriceBreakdown, type CompositePriceResult, type CompositePricingMode, type CompositeSelectionData, type ComponentSelectionInput as CompositeSelectionInput, type CompositeStoredSelection, type CompositeWithDetails, type ContactType, type CreateAddressInput, type CreateMobileMoneyInput, type Currency, type Customer, type CustomerAddress, type CustomerLinkPreferences, type CustomerMobileMoney, type CustomerServicePreferences, DEFAULT_COUNTRY, DEFAULT_CURRENCY, type DayAvailability, type DepositResult, type DepositType, type DeviceType, type DigitalProductType, type DiscountBreakdown, type DiscountDetails, type DisplayAddOn, type DisplayAddOnOption, type DisplayCart, type DisplayCartItem, type EnrollAndLinkOrderInput, type EnrollAndLinkOrderResult, type EnrollmentData, type Err, ErrorCode, type ErrorCodeType, type FeeBearerType, type FormatCompactOptions, type FormatPriceOptions, type FulfillmentLink, type FulfillmentStatus, type FulfillmentType, type GetAvailableSlotsInput, type GetOrdersOptions, type GetProductsOptions, type GroupPricingBehavior, type InitializePaymentResult, InventoryService, type InventorySummary, type InventoryType, type KitchenOrderItem, type KitchenOrderResult, LINK_MUTATION, LINK_QUERY, type LineConfiguration, type LineItem, type LineType, type LinkData, type LinkEnrollResult, LinkService, type LinkSession, type LinkStatusResult, type LiteBootstrap, LiteService, type Location, type LocationAppointment, type LocationProductPrice, type LocationStock, type LocationTaxBehavior, type LocationTaxOverrides, type LocationTimeProfile, type LocationWithDetails, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, type MobileMoneyData, type MobileMoneyDetails, type MobileMoneyProvider, type Money, type MutationRequest, ORDER_MUTATION, ORDER_TYPE, type Ok, type Order, type OrderChannel, type OrderFilter, type OrderFulfillmentSummary, type OrderGroup, type OrderGroupDetails, type OrderGroupPayment, type OrderGroupPaymentState, type OrderGroupPaymentSummary, type OrderHistory, type OrderLineState, type OrderLineStatus, type OrderPaymentEvent, OrderQueries, type OrderSplitDetail, type OrderStatus, type OtpResult, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, type Pagination, type PaginationParams, type ParsedPrice, type Payment, type PaymentErrorDetails, type PaymentMethod, type PaymentMethodType, type PaymentProcessingState, type PaymentProvider, type PaymentResponse, type PaymentState, type PaymentStatus, type PaymentStatusResponse, type PickupTime, type PickupTimeType, type Price, type PriceAdjustment, type PriceDecisionPath, type PriceEntryType, type PriceInfo, type PricePathTaxInfo, type PriceSource, type PricingOverrides, type Product, type ProductAddOn, type ProductAvailability, type ProductStock, type ProductTimeProfile, type ProductType, type ProductVariant, type ProductVariantValue, type ProductWithDetails, type ProductWithPrice, QueryBuilder, type QueryRequest, type RefundOrderInput, type ReminderMethod, type ReminderSettings, type RequestOtpInput, type RescheduleBookingInput, type ResourceAssignment, type ResourceAvailabilityException, type ResourceAvailabilityRule, type ResourceType, type ResponseMetadata, type Result, type RevokeAllSessionsResult, type RevokeSessionResult, type Room, type SalesChannel, type SchedulingMetadata, type SchedulingResult, SchedulingService, type SearchOptions, type SelectedAddOnOption, type Service, type ServiceAvailabilityException, type ServiceAvailabilityParams, type ServiceAvailabilityResult, type ServiceAvailabilityRule, type ServiceCharge, type ServiceNotes, type ServiceScheduleRequest, type ServiceStaffRequirement, type ServiceStatus, type ServiceWithStaff, type Staff, type StaffAssignment, type StaffAvailabilityException, type StaffAvailabilityRule, type StaffBookingProfile, type StaffRole, type StaffScheduleItem, type Stock, type StockLevel, type StockOwnershipType, type StockStatus, type StorefrontBootstrap, type SubmitAuthorizationInput, type Table, type TableInfo, type TaxComponent, type TaxInfo, type TaxPathComponent, type TimeRange, type TimeRanges, type TimeSlot, type UICart, type UICartBusiness, type UICartCustomer, type UICartLocation, type UICartPricing, type UpdateAddressInput, type UpdateCartItemInput, type UpdateOrderStatusInput, type UpdateProfileInput, type VariantAxis, type VariantAxisSelection, type VariantAxisValue, type VariantAxisWithValues, type VariantDetails, type VariantDetailsDTO, type VariantDisplayAttribute, type VariantLocationAvailability, type VariantStock, type VariantStrategy, type VerifyOtpInput, categorizePaymentError, combine, combineObject, createCimplifyClient, detectMobileMoneyProvider, err, extractPriceInfo, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatProductPrice, fromPromise, generateIdempotencyKey, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getMarkupPercentage, getOrElse, getProductCurrency, isCimplifyError, isErr, isOk, isOnSale, isRetryableError, mapError, mapResult, normalizePaymentResponse, normalizeStatusResponse, ok, parsePrice, parsePricePath, parsedPriceToPriceInfo, query, toNullable, tryCatch, unwrap };
package/dist/index.js CHANGED
@@ -645,6 +645,14 @@ async function safe3(promise) {
645
645
  return err(toCimplifyError3(error));
646
646
  }
647
647
  }
648
+ function generateIdempotencyKey() {
649
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
650
+ return `idem_${crypto.randomUUID()}`;
651
+ }
652
+ const timestamp = Date.now().toString(36);
653
+ const random = Math.random().toString(36).substring(2, 15);
654
+ return `idem_${timestamp}_${random}`;
655
+ }
648
656
  var CheckoutService = class {
649
657
  constructor(client) {
650
658
  this.client = client;
@@ -652,6 +660,10 @@ var CheckoutService = class {
652
660
  /**
653
661
  * Process checkout with cart data.
654
662
  *
663
+ * Automatically generates an idempotency key if not provided to ensure
664
+ * payment safety. The same key is used across retries, preventing
665
+ * duplicate charges if a network error occurs after payment processing.
666
+ *
655
667
  * @example
656
668
  * ```typescript
657
669
  * const result = await client.checkout.process({
@@ -675,9 +687,13 @@ var CheckoutService = class {
675
687
  * ```
676
688
  */
677
689
  async process(data) {
690
+ const checkoutData = {
691
+ ...data,
692
+ idempotency_key: data.idempotency_key || generateIdempotencyKey()
693
+ };
678
694
  return safe3(
679
695
  this.client.call(CHECKOUT_MUTATION.PROCESS, {
680
- checkout_data: data
696
+ checkout_data: checkoutData
681
697
  })
682
698
  );
683
699
  }
@@ -1391,6 +1407,51 @@ var LiteService = class {
1391
1407
  // src/client.ts
1392
1408
  var SESSION_TOKEN_HEADER = "x-session-token";
1393
1409
  var SESSION_STORAGE_KEY = "cimplify_session_token";
1410
+ var DEFAULT_TIMEOUT_MS = 3e4;
1411
+ var DEFAULT_MAX_RETRIES = 3;
1412
+ var DEFAULT_RETRY_DELAY_MS = 1e3;
1413
+ function sleep(ms) {
1414
+ return new Promise((resolve) => setTimeout(resolve, ms));
1415
+ }
1416
+ function isRetryable(error) {
1417
+ if (error instanceof TypeError && error.message.includes("fetch")) {
1418
+ return true;
1419
+ }
1420
+ if (error instanceof DOMException && error.name === "AbortError") {
1421
+ return true;
1422
+ }
1423
+ if (error instanceof CimplifyError) {
1424
+ return error.retryable;
1425
+ }
1426
+ if (error instanceof CimplifyError && error.code === "SERVER_ERROR") {
1427
+ return true;
1428
+ }
1429
+ return false;
1430
+ }
1431
+ function toNetworkError(error) {
1432
+ if (error instanceof DOMException && error.name === "AbortError") {
1433
+ return new CimplifyError(
1434
+ ErrorCode.TIMEOUT,
1435
+ "Request timed out. Please check your connection and try again.",
1436
+ true
1437
+ );
1438
+ }
1439
+ if (error instanceof TypeError && error.message.includes("fetch")) {
1440
+ return new CimplifyError(
1441
+ ErrorCode.NETWORK_ERROR,
1442
+ "Network error. Please check your internet connection.",
1443
+ true
1444
+ );
1445
+ }
1446
+ if (error instanceof CimplifyError) {
1447
+ return error;
1448
+ }
1449
+ return new CimplifyError(
1450
+ ErrorCode.UNKNOWN_ERROR,
1451
+ error instanceof Error ? error.message : "An unknown error occurred",
1452
+ false
1453
+ );
1454
+ }
1394
1455
  function deriveUrls() {
1395
1456
  const hostname = typeof window !== "undefined" ? window.location.hostname : "";
1396
1457
  if (hostname === "localhost" || hostname === "127.0.0.1") {
@@ -1413,6 +1474,9 @@ var CimplifyClient = class {
1413
1474
  this.baseUrl = urls.baseUrl;
1414
1475
  this.linkApiUrl = urls.linkApiUrl;
1415
1476
  this.credentials = config.credentials || "include";
1477
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;
1478
+ this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
1479
+ this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;
1416
1480
  this.sessionToken = this.loadSessionToken();
1417
1481
  }
1418
1482
  getSessionToken() {
@@ -1458,12 +1522,47 @@ var CimplifyClient = class {
1458
1522
  this.saveSessionToken(newToken);
1459
1523
  }
1460
1524
  }
1525
+ /**
1526
+ * Resilient fetch with timeout and automatic retries for network errors.
1527
+ * Uses exponential backoff: 1s, 2s, 4s between retries.
1528
+ */
1529
+ async resilientFetch(url, options) {
1530
+ let lastError;
1531
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
1532
+ try {
1533
+ const controller = new AbortController();
1534
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
1535
+ const response = await fetch(url, {
1536
+ ...options,
1537
+ signal: controller.signal
1538
+ });
1539
+ clearTimeout(timeoutId);
1540
+ if (response.ok || response.status >= 400 && response.status < 500) {
1541
+ return response;
1542
+ }
1543
+ if (response.status >= 500 && attempt < this.maxRetries) {
1544
+ const delay = this.retryDelay * Math.pow(2, attempt);
1545
+ await sleep(delay);
1546
+ continue;
1547
+ }
1548
+ return response;
1549
+ } catch (error) {
1550
+ lastError = error;
1551
+ if (!isRetryable(error) || attempt >= this.maxRetries) {
1552
+ throw toNetworkError(error);
1553
+ }
1554
+ const delay = this.retryDelay * Math.pow(2, attempt);
1555
+ await sleep(delay);
1556
+ }
1557
+ }
1558
+ throw toNetworkError(lastError);
1559
+ }
1461
1560
  async query(query2, variables) {
1462
1561
  const body = { query: query2 };
1463
1562
  if (variables) {
1464
1563
  body.variables = variables;
1465
1564
  }
1466
- const response = await fetch(`${this.baseUrl}/api/q`, {
1565
+ const response = await this.resilientFetch(`${this.baseUrl}/api/q`, {
1467
1566
  method: "POST",
1468
1567
  credentials: this.credentials,
1469
1568
  headers: this.getHeaders(),
@@ -1477,7 +1576,7 @@ var CimplifyClient = class {
1477
1576
  method,
1478
1577
  args: args !== void 0 ? [args] : []
1479
1578
  };
1480
- const response = await fetch(`${this.baseUrl}/api/m`, {
1579
+ const response = await this.resilientFetch(`${this.baseUrl}/api/m`, {
1481
1580
  method: "POST",
1482
1581
  credentials: this.credentials,
1483
1582
  headers: this.getHeaders(),
@@ -1487,7 +1586,7 @@ var CimplifyClient = class {
1487
1586
  return this.handleResponse(response);
1488
1587
  }
1489
1588
  async get(path) {
1490
- const response = await fetch(`${this.baseUrl}${path}`, {
1589
+ const response = await this.resilientFetch(`${this.baseUrl}${path}`, {
1491
1590
  method: "GET",
1492
1591
  credentials: this.credentials,
1493
1592
  headers: this.getHeaders()
@@ -1496,7 +1595,7 @@ var CimplifyClient = class {
1496
1595
  return this.handleRestResponse(response);
1497
1596
  }
1498
1597
  async post(path, body) {
1499
- const response = await fetch(`${this.baseUrl}${path}`, {
1598
+ const response = await this.resilientFetch(`${this.baseUrl}${path}`, {
1500
1599
  method: "POST",
1501
1600
  credentials: this.credentials,
1502
1601
  headers: this.getHeaders(),
@@ -1506,7 +1605,7 @@ var CimplifyClient = class {
1506
1605
  return this.handleRestResponse(response);
1507
1606
  }
1508
1607
  async delete(path) {
1509
- const response = await fetch(`${this.baseUrl}${path}`, {
1608
+ const response = await this.resilientFetch(`${this.baseUrl}${path}`, {
1510
1609
  method: "DELETE",
1511
1610
  credentials: this.credentials,
1512
1611
  headers: this.getHeaders()
@@ -1515,7 +1614,7 @@ var CimplifyClient = class {
1515
1614
  return this.handleRestResponse(response);
1516
1615
  }
1517
1616
  async linkGet(path) {
1518
- const response = await fetch(`${this.linkApiUrl}${path}`, {
1617
+ const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
1519
1618
  method: "GET",
1520
1619
  credentials: this.credentials,
1521
1620
  headers: this.getHeaders()
@@ -1524,7 +1623,7 @@ var CimplifyClient = class {
1524
1623
  return this.handleRestResponse(response);
1525
1624
  }
1526
1625
  async linkPost(path, body) {
1527
- const response = await fetch(`${this.linkApiUrl}${path}`, {
1626
+ const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
1528
1627
  method: "POST",
1529
1628
  credentials: this.credentials,
1530
1629
  headers: this.getHeaders(),
@@ -1534,7 +1633,7 @@ var CimplifyClient = class {
1534
1633
  return this.handleRestResponse(response);
1535
1634
  }
1536
1635
  async linkDelete(path) {
1537
- const response = await fetch(`${this.linkApiUrl}${path}`, {
1636
+ const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
1538
1637
  method: "DELETE",
1539
1638
  credentials: this.credentials,
1540
1639
  headers: this.getHeaders()
@@ -2228,6 +2327,7 @@ exports.formatPriceAdjustment = formatPriceAdjustment;
2228
2327
  exports.formatPriceCompact = formatPriceCompact;
2229
2328
  exports.formatProductPrice = formatProductPrice;
2230
2329
  exports.fromPromise = fromPromise;
2330
+ exports.generateIdempotencyKey = generateIdempotencyKey;
2231
2331
  exports.getBasePrice = getBasePrice;
2232
2332
  exports.getCurrencySymbol = getCurrencySymbol;
2233
2333
  exports.getDiscountPercentage = getDiscountPercentage;
package/dist/index.mjs CHANGED
@@ -643,6 +643,14 @@ async function safe3(promise) {
643
643
  return err(toCimplifyError3(error));
644
644
  }
645
645
  }
646
+ function generateIdempotencyKey() {
647
+ if (typeof crypto !== "undefined" && crypto.randomUUID) {
648
+ return `idem_${crypto.randomUUID()}`;
649
+ }
650
+ const timestamp = Date.now().toString(36);
651
+ const random = Math.random().toString(36).substring(2, 15);
652
+ return `idem_${timestamp}_${random}`;
653
+ }
646
654
  var CheckoutService = class {
647
655
  constructor(client) {
648
656
  this.client = client;
@@ -650,6 +658,10 @@ var CheckoutService = class {
650
658
  /**
651
659
  * Process checkout with cart data.
652
660
  *
661
+ * Automatically generates an idempotency key if not provided to ensure
662
+ * payment safety. The same key is used across retries, preventing
663
+ * duplicate charges if a network error occurs after payment processing.
664
+ *
653
665
  * @example
654
666
  * ```typescript
655
667
  * const result = await client.checkout.process({
@@ -673,9 +685,13 @@ var CheckoutService = class {
673
685
  * ```
674
686
  */
675
687
  async process(data) {
688
+ const checkoutData = {
689
+ ...data,
690
+ idempotency_key: data.idempotency_key || generateIdempotencyKey()
691
+ };
676
692
  return safe3(
677
693
  this.client.call(CHECKOUT_MUTATION.PROCESS, {
678
- checkout_data: data
694
+ checkout_data: checkoutData
679
695
  })
680
696
  );
681
697
  }
@@ -1389,6 +1405,51 @@ var LiteService = class {
1389
1405
  // src/client.ts
1390
1406
  var SESSION_TOKEN_HEADER = "x-session-token";
1391
1407
  var SESSION_STORAGE_KEY = "cimplify_session_token";
1408
+ var DEFAULT_TIMEOUT_MS = 3e4;
1409
+ var DEFAULT_MAX_RETRIES = 3;
1410
+ var DEFAULT_RETRY_DELAY_MS = 1e3;
1411
+ function sleep(ms) {
1412
+ return new Promise((resolve) => setTimeout(resolve, ms));
1413
+ }
1414
+ function isRetryable(error) {
1415
+ if (error instanceof TypeError && error.message.includes("fetch")) {
1416
+ return true;
1417
+ }
1418
+ if (error instanceof DOMException && error.name === "AbortError") {
1419
+ return true;
1420
+ }
1421
+ if (error instanceof CimplifyError) {
1422
+ return error.retryable;
1423
+ }
1424
+ if (error instanceof CimplifyError && error.code === "SERVER_ERROR") {
1425
+ return true;
1426
+ }
1427
+ return false;
1428
+ }
1429
+ function toNetworkError(error) {
1430
+ if (error instanceof DOMException && error.name === "AbortError") {
1431
+ return new CimplifyError(
1432
+ ErrorCode.TIMEOUT,
1433
+ "Request timed out. Please check your connection and try again.",
1434
+ true
1435
+ );
1436
+ }
1437
+ if (error instanceof TypeError && error.message.includes("fetch")) {
1438
+ return new CimplifyError(
1439
+ ErrorCode.NETWORK_ERROR,
1440
+ "Network error. Please check your internet connection.",
1441
+ true
1442
+ );
1443
+ }
1444
+ if (error instanceof CimplifyError) {
1445
+ return error;
1446
+ }
1447
+ return new CimplifyError(
1448
+ ErrorCode.UNKNOWN_ERROR,
1449
+ error instanceof Error ? error.message : "An unknown error occurred",
1450
+ false
1451
+ );
1452
+ }
1392
1453
  function deriveUrls() {
1393
1454
  const hostname = typeof window !== "undefined" ? window.location.hostname : "";
1394
1455
  if (hostname === "localhost" || hostname === "127.0.0.1") {
@@ -1411,6 +1472,9 @@ var CimplifyClient = class {
1411
1472
  this.baseUrl = urls.baseUrl;
1412
1473
  this.linkApiUrl = urls.linkApiUrl;
1413
1474
  this.credentials = config.credentials || "include";
1475
+ this.timeout = config.timeout ?? DEFAULT_TIMEOUT_MS;
1476
+ this.maxRetries = config.maxRetries ?? DEFAULT_MAX_RETRIES;
1477
+ this.retryDelay = config.retryDelay ?? DEFAULT_RETRY_DELAY_MS;
1414
1478
  this.sessionToken = this.loadSessionToken();
1415
1479
  }
1416
1480
  getSessionToken() {
@@ -1456,12 +1520,47 @@ var CimplifyClient = class {
1456
1520
  this.saveSessionToken(newToken);
1457
1521
  }
1458
1522
  }
1523
+ /**
1524
+ * Resilient fetch with timeout and automatic retries for network errors.
1525
+ * Uses exponential backoff: 1s, 2s, 4s between retries.
1526
+ */
1527
+ async resilientFetch(url, options) {
1528
+ let lastError;
1529
+ for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
1530
+ try {
1531
+ const controller = new AbortController();
1532
+ const timeoutId = setTimeout(() => controller.abort(), this.timeout);
1533
+ const response = await fetch(url, {
1534
+ ...options,
1535
+ signal: controller.signal
1536
+ });
1537
+ clearTimeout(timeoutId);
1538
+ if (response.ok || response.status >= 400 && response.status < 500) {
1539
+ return response;
1540
+ }
1541
+ if (response.status >= 500 && attempt < this.maxRetries) {
1542
+ const delay = this.retryDelay * Math.pow(2, attempt);
1543
+ await sleep(delay);
1544
+ continue;
1545
+ }
1546
+ return response;
1547
+ } catch (error) {
1548
+ lastError = error;
1549
+ if (!isRetryable(error) || attempt >= this.maxRetries) {
1550
+ throw toNetworkError(error);
1551
+ }
1552
+ const delay = this.retryDelay * Math.pow(2, attempt);
1553
+ await sleep(delay);
1554
+ }
1555
+ }
1556
+ throw toNetworkError(lastError);
1557
+ }
1459
1558
  async query(query2, variables) {
1460
1559
  const body = { query: query2 };
1461
1560
  if (variables) {
1462
1561
  body.variables = variables;
1463
1562
  }
1464
- const response = await fetch(`${this.baseUrl}/api/q`, {
1563
+ const response = await this.resilientFetch(`${this.baseUrl}/api/q`, {
1465
1564
  method: "POST",
1466
1565
  credentials: this.credentials,
1467
1566
  headers: this.getHeaders(),
@@ -1475,7 +1574,7 @@ var CimplifyClient = class {
1475
1574
  method,
1476
1575
  args: args !== void 0 ? [args] : []
1477
1576
  };
1478
- const response = await fetch(`${this.baseUrl}/api/m`, {
1577
+ const response = await this.resilientFetch(`${this.baseUrl}/api/m`, {
1479
1578
  method: "POST",
1480
1579
  credentials: this.credentials,
1481
1580
  headers: this.getHeaders(),
@@ -1485,7 +1584,7 @@ var CimplifyClient = class {
1485
1584
  return this.handleResponse(response);
1486
1585
  }
1487
1586
  async get(path) {
1488
- const response = await fetch(`${this.baseUrl}${path}`, {
1587
+ const response = await this.resilientFetch(`${this.baseUrl}${path}`, {
1489
1588
  method: "GET",
1490
1589
  credentials: this.credentials,
1491
1590
  headers: this.getHeaders()
@@ -1494,7 +1593,7 @@ var CimplifyClient = class {
1494
1593
  return this.handleRestResponse(response);
1495
1594
  }
1496
1595
  async post(path, body) {
1497
- const response = await fetch(`${this.baseUrl}${path}`, {
1596
+ const response = await this.resilientFetch(`${this.baseUrl}${path}`, {
1498
1597
  method: "POST",
1499
1598
  credentials: this.credentials,
1500
1599
  headers: this.getHeaders(),
@@ -1504,7 +1603,7 @@ var CimplifyClient = class {
1504
1603
  return this.handleRestResponse(response);
1505
1604
  }
1506
1605
  async delete(path) {
1507
- const response = await fetch(`${this.baseUrl}${path}`, {
1606
+ const response = await this.resilientFetch(`${this.baseUrl}${path}`, {
1508
1607
  method: "DELETE",
1509
1608
  credentials: this.credentials,
1510
1609
  headers: this.getHeaders()
@@ -1513,7 +1612,7 @@ var CimplifyClient = class {
1513
1612
  return this.handleRestResponse(response);
1514
1613
  }
1515
1614
  async linkGet(path) {
1516
- const response = await fetch(`${this.linkApiUrl}${path}`, {
1615
+ const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
1517
1616
  method: "GET",
1518
1617
  credentials: this.credentials,
1519
1618
  headers: this.getHeaders()
@@ -1522,7 +1621,7 @@ var CimplifyClient = class {
1522
1621
  return this.handleRestResponse(response);
1523
1622
  }
1524
1623
  async linkPost(path, body) {
1525
- const response = await fetch(`${this.linkApiUrl}${path}`, {
1624
+ const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
1526
1625
  method: "POST",
1527
1626
  credentials: this.credentials,
1528
1627
  headers: this.getHeaders(),
@@ -1532,7 +1631,7 @@ var CimplifyClient = class {
1532
1631
  return this.handleRestResponse(response);
1533
1632
  }
1534
1633
  async linkDelete(path) {
1535
- const response = await fetch(`${this.linkApiUrl}${path}`, {
1634
+ const response = await this.resilientFetch(`${this.linkApiUrl}${path}`, {
1536
1635
  method: "DELETE",
1537
1636
  credentials: this.credentials,
1538
1637
  headers: this.getHeaders()
@@ -2178,4 +2277,4 @@ function detectMobileMoneyProvider(phoneNumber) {
2178
2277
  return null;
2179
2278
  }
2180
2279
 
2181
- export { AUTHORIZATION_TYPE, AUTH_MUTATION, AuthService, BusinessService, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CURRENCY_SYMBOLS, CartOperations, CatalogueQueries, CheckoutService as CheckoutOperations, CheckoutService, CimplifyClient, CimplifyError, DEFAULT_COUNTRY, DEFAULT_CURRENCY, ErrorCode, InventoryService, LINK_MUTATION, LINK_QUERY, LinkService, LiteService, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, ORDER_MUTATION, ORDER_TYPE, OrderQueries, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, QueryBuilder, SchedulingService, categorizePaymentError, combine, combineObject, createCimplifyClient, detectMobileMoneyProvider, err, extractPriceInfo, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatProductPrice, fromPromise, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getMarkupPercentage, getOrElse, getProductCurrency, isCimplifyError, isErr, isOk, isOnSale, isRetryableError, mapError, mapResult, normalizePaymentResponse, normalizeStatusResponse, ok, parsePrice, parsePricePath, parsedPriceToPriceInfo, query, toNullable, tryCatch, unwrap };
2280
+ export { AUTHORIZATION_TYPE, AUTH_MUTATION, AuthService, BusinessService, CHECKOUT_MODE, CHECKOUT_MUTATION, CHECKOUT_STEP, CURRENCY_SYMBOLS, CartOperations, CatalogueQueries, CheckoutService as CheckoutOperations, CheckoutService, CimplifyClient, CimplifyError, DEFAULT_COUNTRY, DEFAULT_CURRENCY, ErrorCode, InventoryService, LINK_MUTATION, LINK_QUERY, LinkService, LiteService, MOBILE_MONEY_PROVIDER, MOBILE_MONEY_PROVIDERS, ORDER_MUTATION, ORDER_TYPE, OrderQueries, PAYMENT_METHOD, PAYMENT_MUTATION, PAYMENT_STATE, PICKUP_TIME_TYPE, QueryBuilder, SchedulingService, categorizePaymentError, combine, combineObject, createCimplifyClient, detectMobileMoneyProvider, err, extractPriceInfo, flatMap, formatMoney, formatNumberCompact, formatPrice, formatPriceAdjustment, formatPriceCompact, formatProductPrice, fromPromise, generateIdempotencyKey, getBasePrice, getCurrencySymbol, getDiscountPercentage, getDisplayPrice, getMarkupPercentage, getOrElse, getProductCurrency, isCimplifyError, isErr, isOk, isOnSale, isRetryableError, mapError, mapResult, normalizePaymentResponse, normalizeStatusResponse, ok, parsePrice, parsePricePath, parsedPriceToPriceInfo, query, toNullable, tryCatch, unwrap };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cimplify/sdk",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Cimplify Commerce SDK for storefronts",
5
5
  "keywords": [
6
6
  "cimplify",