@atomic-solutions/woocommerce-api-client 0.3.1 → 0.5.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.
@@ -72,6 +72,7 @@ interface ResponseOptions {
72
72
  errorReporter?: (error: Error) => void;
73
73
  onValidationError?: (error: Error) => void;
74
74
  }
75
+ declare const handleApiData: <T>(data: unknown, schema: ZodSchema<T>, options?: ResponseOptions, url?: string) => T;
75
76
  declare const handleApiResponse: <T>(response: AxiosResponse, schema: ZodSchema<T>, options?: ResponseOptions) => T;
76
77
  declare const isZodError: (error: unknown) => error is ZodError;
77
78
 
@@ -1641,6 +1642,81 @@ declare const addToCartInputSchema: z.ZodObject<{
1641
1642
  attribute: string;
1642
1643
  }[] | undefined;
1643
1644
  }>;
1645
+ declare const addItemsInputSchema: z.ZodObject<{
1646
+ items: z.ZodArray<z.ZodObject<{
1647
+ id: z.ZodNumber;
1648
+ quantity: z.ZodNumber;
1649
+ variation: z.ZodOptional<z.ZodArray<z.ZodObject<{
1650
+ attribute: z.ZodString;
1651
+ value: z.ZodString;
1652
+ }, "strip", z.ZodTypeAny, {
1653
+ value: string;
1654
+ attribute: string;
1655
+ }, {
1656
+ value: string;
1657
+ attribute: string;
1658
+ }>, "many">>;
1659
+ }, "strip", z.ZodTypeAny, {
1660
+ id: number;
1661
+ quantity: number;
1662
+ variation?: {
1663
+ value: string;
1664
+ attribute: string;
1665
+ }[] | undefined;
1666
+ }, {
1667
+ id: number;
1668
+ quantity: number;
1669
+ variation?: {
1670
+ value: string;
1671
+ attribute: string;
1672
+ }[] | undefined;
1673
+ }>, "many">;
1674
+ }, "strip", z.ZodTypeAny, {
1675
+ items: {
1676
+ id: number;
1677
+ quantity: number;
1678
+ variation?: {
1679
+ value: string;
1680
+ attribute: string;
1681
+ }[] | undefined;
1682
+ }[];
1683
+ }, {
1684
+ items: {
1685
+ id: number;
1686
+ quantity: number;
1687
+ variation?: {
1688
+ value: string;
1689
+ attribute: string;
1690
+ }[] | undefined;
1691
+ }[];
1692
+ }>;
1693
+ declare const batchResponseSchema: z.ZodObject<{
1694
+ responses: z.ZodArray<z.ZodObject<{
1695
+ status: z.ZodNumber;
1696
+ body: z.ZodUnknown;
1697
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1698
+ }, "strip", z.ZodTypeAny, {
1699
+ status: number;
1700
+ headers?: Record<string, unknown> | undefined;
1701
+ body?: unknown;
1702
+ }, {
1703
+ status: number;
1704
+ headers?: Record<string, unknown> | undefined;
1705
+ body?: unknown;
1706
+ }>, "many">;
1707
+ }, "strip", z.ZodTypeAny, {
1708
+ responses: {
1709
+ status: number;
1710
+ headers?: Record<string, unknown> | undefined;
1711
+ body?: unknown;
1712
+ }[];
1713
+ }, {
1714
+ responses: {
1715
+ status: number;
1716
+ headers?: Record<string, unknown> | undefined;
1717
+ body?: unknown;
1718
+ }[];
1719
+ }>;
1644
1720
  declare const updateCartItemInputSchema: z.ZodObject<{
1645
1721
  key: z.ZodString;
1646
1722
  quantity: z.ZodNumber;
@@ -1803,6 +1879,8 @@ declare const selectShippingRateInputSchema: z.ZodObject<{
1803
1879
  type Cart = z.infer<typeof cartSchema>;
1804
1880
  type CartItem = z.infer<typeof cartItemSchema>;
1805
1881
  type AddToCartInput = z.infer<typeof addToCartInputSchema>;
1882
+ type AddItemsInput = z.infer<typeof addItemsInputSchema>;
1883
+ type BatchResponse = z.infer<typeof batchResponseSchema>;
1806
1884
  type UpdateCartItemInput = z.infer<typeof updateCartItemInputSchema>;
1807
1885
  type RemoveCartItemInput = z.infer<typeof removeCartItemInputSchema>;
1808
1886
  type CouponInput = z.infer<typeof couponInputSchema>;
@@ -2893,12 +2971,14 @@ declare const storeProductsSearchParamsSchema: z.ZodObject<{
2893
2971
  order: z.ZodOptional<z.ZodEnum<["asc", "desc"]>>;
2894
2972
  search: z.ZodOptional<z.ZodString>;
2895
2973
  slug: z.ZodOptional<z.ZodString>;
2974
+ sku: z.ZodOptional<z.ZodString>;
2896
2975
  after: z.ZodOptional<z.ZodString>;
2897
2976
  before: z.ZodOptional<z.ZodString>;
2898
2977
  modified_after: z.ZodOptional<z.ZodString>;
2899
2978
  modified_before: z.ZodOptional<z.ZodString>;
2900
2979
  include: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
2901
2980
  exclude: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
2981
+ related: z.ZodOptional<z.ZodNumber>;
2902
2982
  parent: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
2903
2983
  parent_exclude: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
2904
2984
  type: z.ZodOptional<z.ZodEnum<["simple", "grouped", "external", "variable", "variation"]>>;
@@ -2938,6 +3018,7 @@ declare const storeProductsSearchParamsSchema: z.ZodObject<{
2938
3018
  status?: "pending" | "any" | "draft" | "private" | "publish" | undefined;
2939
3019
  order?: "asc" | "desc" | undefined;
2940
3020
  orderby?: "id" | "price" | "date" | "slug" | "menu_order" | "include" | "title" | "popularity" | "rating" | "date_modified" | undefined;
3021
+ sku?: string | undefined;
2941
3022
  catalog_visibility?: "search" | "any" | "visible" | "catalog" | "hidden" | undefined;
2942
3023
  slug?: string | undefined;
2943
3024
  parent?: number[] | undefined;
@@ -2949,6 +3030,7 @@ declare const storeProductsSearchParamsSchema: z.ZodObject<{
2949
3030
  modified_after?: string | undefined;
2950
3031
  modified_before?: string | undefined;
2951
3032
  exclude?: number[] | undefined;
3033
+ related?: number | undefined;
2952
3034
  parent_exclude?: number[] | undefined;
2953
3035
  featured?: boolean | undefined;
2954
3036
  stock_status?: ("instock" | "outofstock" | "onbackorder")[] | undefined;
@@ -2973,6 +3055,7 @@ declare const storeProductsSearchParamsSchema: z.ZodObject<{
2973
3055
  per_page?: number | undefined;
2974
3056
  order?: "asc" | "desc" | undefined;
2975
3057
  orderby?: "id" | "price" | "date" | "slug" | "menu_order" | "include" | "title" | "popularity" | "rating" | "date_modified" | undefined;
3058
+ sku?: string | undefined;
2976
3059
  catalog_visibility?: "search" | "any" | "visible" | "catalog" | "hidden" | undefined;
2977
3060
  slug?: string | undefined;
2978
3061
  parent?: number[] | undefined;
@@ -2984,6 +3067,7 @@ declare const storeProductsSearchParamsSchema: z.ZodObject<{
2984
3067
  modified_after?: string | undefined;
2985
3068
  modified_before?: string | undefined;
2986
3069
  exclude?: number[] | undefined;
3070
+ related?: number | undefined;
2987
3071
  parent_exclude?: number[] | undefined;
2988
3072
  featured?: boolean | undefined;
2989
3073
  stock_status?: ("instock" | "outofstock" | "onbackorder")[] | undefined;
@@ -3026,16 +3110,16 @@ declare const productSchema: z.ZodObject<{
3026
3110
  text: z.ZodString;
3027
3111
  url: z.ZodString;
3028
3112
  }, "strip", z.ZodTypeAny, {
3029
- text: string;
3030
3113
  minimum: number;
3031
3114
  maximum: number;
3115
+ text: string;
3032
3116
  multiple_of: number;
3033
3117
  description: string;
3034
3118
  url: string;
3035
3119
  }, {
3036
- text: string;
3037
3120
  minimum: number;
3038
3121
  maximum: number;
3122
+ text: string;
3039
3123
  multiple_of: number;
3040
3124
  description: string;
3041
3125
  url: string;
@@ -3232,9 +3316,9 @@ declare const productSchema: z.ZodObject<{
3232
3316
  extensions: z.ZodRecord<z.ZodString, z.ZodUnknown>;
3233
3317
  }, "strip", z.ZodTypeAny, {
3234
3318
  add_to_cart: {
3235
- text: string;
3236
3319
  minimum: number;
3237
3320
  maximum: number;
3321
+ text: string;
3238
3322
  multiple_of: number;
3239
3323
  description: string;
3240
3324
  url: string;
@@ -3316,9 +3400,9 @@ declare const productSchema: z.ZodObject<{
3316
3400
  review_count: number;
3317
3401
  }, {
3318
3402
  add_to_cart: {
3319
- text: string;
3320
3403
  minimum: number;
3321
3404
  maximum: number;
3405
+ text: string;
3322
3406
  multiple_of: number;
3323
3407
  description: string;
3324
3408
  url: string;
@@ -3459,9 +3543,19 @@ interface ProductsAPI {
3459
3543
  get: (id: number) => Promise<Product>;
3460
3544
  categories: () => Promise<ProductCategory[]>;
3461
3545
  }
3546
+ interface AddItemsResult {
3547
+ cart: Cart;
3548
+ results: {
3549
+ item: AddToCartInput;
3550
+ status: number;
3551
+ code?: string;
3552
+ message?: string;
3553
+ }[];
3554
+ }
3462
3555
  interface CartAPI {
3463
3556
  get: () => Promise<Cart>;
3464
3557
  addItem: (input: AddToCartInput) => Promise<Cart>;
3558
+ addItems: (input: AddItemsInput) => Promise<AddItemsResult>;
3465
3559
  updateItem: (input: UpdateCartItemInput) => Promise<Cart>;
3466
3560
  removeItem: (input: RemoveCartItemInput) => Promise<Cart>;
3467
3561
  applyCoupon: (input: CouponInput) => Promise<Cart>;
@@ -3490,4 +3584,4 @@ interface WooCommerceClient {
3490
3584
  orders: OrdersAPI;
3491
3585
  }
3492
3586
 
3493
- export { selectShippingRateInputSchema as $, type AddToCartInput as A, BaseError as B, type CartHeadersAdapter as C, type StoreApiOrder as D, type UpdateCustomerInput as E, WooCommerceApiError as F, type GetOrderInput as G, type WooCommerceApiErrorOptions as H, addToCartInputSchema as I, type JwtTokenAdapter as J, cartItemImageSchema as K, cartSchema as L, checkoutInputSchema as M, checkoutSchema as N, type OrderStatus as O, type PaginatedResponse as P, couponInputSchema as Q, type ResponseOptions as R, type StoreApiVersion as S, productCategorySchema as T, type UpdateCartItemInput as U, type ValidationMode as V, type WooCommerceConfig as W, productImageSchema as X, productSchema as Y, removeCartItemInputSchema as Z, storeProductsSearchParamsSchema as _, type WooCommerceClient as a, storeApiOrderSchema as a0, updateCartItemInputSchema as a1, updateCustomerInputSchema as a2, handlePaginatedApiResponse as b, type Pagination as c, calculatePagination as d, type BaseErrorOptions as e, type ValidationReportableData as f, type WooCommerceDataValidationErrorOptions as g, handleApiResponse as h, isZodError as i, type Cart as j, type CartAPI as k, type CartItem as l, type CartItemImage as m, type Checkout as n, type CheckoutAPI as o, type CheckoutInput as p, type CouponInput as q, type OrdersAPI as r, setupErrorInterceptor as s, type Product as t, type ProductCategory as u, type ProductImage as v, type ProductParams as w, type ProductsAPI as x, type RemoveCartItemInput as y, type SelectShippingRateInput as z };
3587
+ export { checkoutSchema as $, type AddItemsInput as A, BaseError as B, type CartHeadersAdapter as C, type ProductImage as D, type ProductParams as E, type ProductsAPI as F, type GetOrderInput as G, type RemoveCartItemInput as H, type SelectShippingRateInput as I, type JwtTokenAdapter as J, type StoreApiOrder as K, type UpdateCustomerInput as L, WooCommerceApiError as M, type WooCommerceApiErrorOptions as N, type OrderStatus as O, type PaginatedResponse as P, addItemsInputSchema as Q, type ResponseOptions as R, type StoreApiVersion as S, addToCartInputSchema as T, type UpdateCartItemInput as U, type ValidationMode as V, type WooCommerceConfig as W, batchResponseSchema as X, cartItemImageSchema as Y, cartSchema as Z, checkoutInputSchema as _, type WooCommerceClient as a, couponInputSchema as a0, productCategorySchema as a1, productImageSchema as a2, productSchema as a3, removeCartItemInputSchema as a4, storeProductsSearchParamsSchema as a5, selectShippingRateInputSchema as a6, storeApiOrderSchema as a7, updateCartItemInputSchema as a8, updateCustomerInputSchema as a9, handleApiResponse as b, handlePaginatedApiResponse as c, type Pagination as d, calculatePagination as e, type WooCommerceApiErrorCode as f, type BaseErrorOptions as g, handleApiData as h, isZodError as i, type ValidationReportableData as j, type WooCommerceDataValidationErrorOptions as k, type AddItemsResult as l, type AddToCartInput as m, type BatchResponse as n, type Cart as o, type CartAPI as p, type CartItem as q, type CartItemImage as r, setupErrorInterceptor as s, type Checkout as t, type CheckoutAPI as u, type CheckoutInput as v, type CouponInput as w, type OrdersAPI as x, type Product as y, type ProductCategory as z };
@@ -72,6 +72,7 @@ interface ResponseOptions {
72
72
  errorReporter?: (error: Error) => void;
73
73
  onValidationError?: (error: Error) => void;
74
74
  }
75
+ declare const handleApiData: <T>(data: unknown, schema: ZodSchema<T>, options?: ResponseOptions, url?: string) => T;
75
76
  declare const handleApiResponse: <T>(response: AxiosResponse, schema: ZodSchema<T>, options?: ResponseOptions) => T;
76
77
  declare const isZodError: (error: unknown) => error is ZodError;
77
78
 
@@ -1641,6 +1642,81 @@ declare const addToCartInputSchema: z.ZodObject<{
1641
1642
  attribute: string;
1642
1643
  }[] | undefined;
1643
1644
  }>;
1645
+ declare const addItemsInputSchema: z.ZodObject<{
1646
+ items: z.ZodArray<z.ZodObject<{
1647
+ id: z.ZodNumber;
1648
+ quantity: z.ZodNumber;
1649
+ variation: z.ZodOptional<z.ZodArray<z.ZodObject<{
1650
+ attribute: z.ZodString;
1651
+ value: z.ZodString;
1652
+ }, "strip", z.ZodTypeAny, {
1653
+ value: string;
1654
+ attribute: string;
1655
+ }, {
1656
+ value: string;
1657
+ attribute: string;
1658
+ }>, "many">>;
1659
+ }, "strip", z.ZodTypeAny, {
1660
+ id: number;
1661
+ quantity: number;
1662
+ variation?: {
1663
+ value: string;
1664
+ attribute: string;
1665
+ }[] | undefined;
1666
+ }, {
1667
+ id: number;
1668
+ quantity: number;
1669
+ variation?: {
1670
+ value: string;
1671
+ attribute: string;
1672
+ }[] | undefined;
1673
+ }>, "many">;
1674
+ }, "strip", z.ZodTypeAny, {
1675
+ items: {
1676
+ id: number;
1677
+ quantity: number;
1678
+ variation?: {
1679
+ value: string;
1680
+ attribute: string;
1681
+ }[] | undefined;
1682
+ }[];
1683
+ }, {
1684
+ items: {
1685
+ id: number;
1686
+ quantity: number;
1687
+ variation?: {
1688
+ value: string;
1689
+ attribute: string;
1690
+ }[] | undefined;
1691
+ }[];
1692
+ }>;
1693
+ declare const batchResponseSchema: z.ZodObject<{
1694
+ responses: z.ZodArray<z.ZodObject<{
1695
+ status: z.ZodNumber;
1696
+ body: z.ZodUnknown;
1697
+ headers: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
1698
+ }, "strip", z.ZodTypeAny, {
1699
+ status: number;
1700
+ headers?: Record<string, unknown> | undefined;
1701
+ body?: unknown;
1702
+ }, {
1703
+ status: number;
1704
+ headers?: Record<string, unknown> | undefined;
1705
+ body?: unknown;
1706
+ }>, "many">;
1707
+ }, "strip", z.ZodTypeAny, {
1708
+ responses: {
1709
+ status: number;
1710
+ headers?: Record<string, unknown> | undefined;
1711
+ body?: unknown;
1712
+ }[];
1713
+ }, {
1714
+ responses: {
1715
+ status: number;
1716
+ headers?: Record<string, unknown> | undefined;
1717
+ body?: unknown;
1718
+ }[];
1719
+ }>;
1644
1720
  declare const updateCartItemInputSchema: z.ZodObject<{
1645
1721
  key: z.ZodString;
1646
1722
  quantity: z.ZodNumber;
@@ -1803,6 +1879,8 @@ declare const selectShippingRateInputSchema: z.ZodObject<{
1803
1879
  type Cart = z.infer<typeof cartSchema>;
1804
1880
  type CartItem = z.infer<typeof cartItemSchema>;
1805
1881
  type AddToCartInput = z.infer<typeof addToCartInputSchema>;
1882
+ type AddItemsInput = z.infer<typeof addItemsInputSchema>;
1883
+ type BatchResponse = z.infer<typeof batchResponseSchema>;
1806
1884
  type UpdateCartItemInput = z.infer<typeof updateCartItemInputSchema>;
1807
1885
  type RemoveCartItemInput = z.infer<typeof removeCartItemInputSchema>;
1808
1886
  type CouponInput = z.infer<typeof couponInputSchema>;
@@ -2893,12 +2971,14 @@ declare const storeProductsSearchParamsSchema: z.ZodObject<{
2893
2971
  order: z.ZodOptional<z.ZodEnum<["asc", "desc"]>>;
2894
2972
  search: z.ZodOptional<z.ZodString>;
2895
2973
  slug: z.ZodOptional<z.ZodString>;
2974
+ sku: z.ZodOptional<z.ZodString>;
2896
2975
  after: z.ZodOptional<z.ZodString>;
2897
2976
  before: z.ZodOptional<z.ZodString>;
2898
2977
  modified_after: z.ZodOptional<z.ZodString>;
2899
2978
  modified_before: z.ZodOptional<z.ZodString>;
2900
2979
  include: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
2901
2980
  exclude: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
2981
+ related: z.ZodOptional<z.ZodNumber>;
2902
2982
  parent: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
2903
2983
  parent_exclude: z.ZodOptional<z.ZodArray<z.ZodNumber, "many">>;
2904
2984
  type: z.ZodOptional<z.ZodEnum<["simple", "grouped", "external", "variable", "variation"]>>;
@@ -2938,6 +3018,7 @@ declare const storeProductsSearchParamsSchema: z.ZodObject<{
2938
3018
  status?: "pending" | "any" | "draft" | "private" | "publish" | undefined;
2939
3019
  order?: "asc" | "desc" | undefined;
2940
3020
  orderby?: "id" | "price" | "date" | "slug" | "menu_order" | "include" | "title" | "popularity" | "rating" | "date_modified" | undefined;
3021
+ sku?: string | undefined;
2941
3022
  catalog_visibility?: "search" | "any" | "visible" | "catalog" | "hidden" | undefined;
2942
3023
  slug?: string | undefined;
2943
3024
  parent?: number[] | undefined;
@@ -2949,6 +3030,7 @@ declare const storeProductsSearchParamsSchema: z.ZodObject<{
2949
3030
  modified_after?: string | undefined;
2950
3031
  modified_before?: string | undefined;
2951
3032
  exclude?: number[] | undefined;
3033
+ related?: number | undefined;
2952
3034
  parent_exclude?: number[] | undefined;
2953
3035
  featured?: boolean | undefined;
2954
3036
  stock_status?: ("instock" | "outofstock" | "onbackorder")[] | undefined;
@@ -2973,6 +3055,7 @@ declare const storeProductsSearchParamsSchema: z.ZodObject<{
2973
3055
  per_page?: number | undefined;
2974
3056
  order?: "asc" | "desc" | undefined;
2975
3057
  orderby?: "id" | "price" | "date" | "slug" | "menu_order" | "include" | "title" | "popularity" | "rating" | "date_modified" | undefined;
3058
+ sku?: string | undefined;
2976
3059
  catalog_visibility?: "search" | "any" | "visible" | "catalog" | "hidden" | undefined;
2977
3060
  slug?: string | undefined;
2978
3061
  parent?: number[] | undefined;
@@ -2984,6 +3067,7 @@ declare const storeProductsSearchParamsSchema: z.ZodObject<{
2984
3067
  modified_after?: string | undefined;
2985
3068
  modified_before?: string | undefined;
2986
3069
  exclude?: number[] | undefined;
3070
+ related?: number | undefined;
2987
3071
  parent_exclude?: number[] | undefined;
2988
3072
  featured?: boolean | undefined;
2989
3073
  stock_status?: ("instock" | "outofstock" | "onbackorder")[] | undefined;
@@ -3026,16 +3110,16 @@ declare const productSchema: z.ZodObject<{
3026
3110
  text: z.ZodString;
3027
3111
  url: z.ZodString;
3028
3112
  }, "strip", z.ZodTypeAny, {
3029
- text: string;
3030
3113
  minimum: number;
3031
3114
  maximum: number;
3115
+ text: string;
3032
3116
  multiple_of: number;
3033
3117
  description: string;
3034
3118
  url: string;
3035
3119
  }, {
3036
- text: string;
3037
3120
  minimum: number;
3038
3121
  maximum: number;
3122
+ text: string;
3039
3123
  multiple_of: number;
3040
3124
  description: string;
3041
3125
  url: string;
@@ -3232,9 +3316,9 @@ declare const productSchema: z.ZodObject<{
3232
3316
  extensions: z.ZodRecord<z.ZodString, z.ZodUnknown>;
3233
3317
  }, "strip", z.ZodTypeAny, {
3234
3318
  add_to_cart: {
3235
- text: string;
3236
3319
  minimum: number;
3237
3320
  maximum: number;
3321
+ text: string;
3238
3322
  multiple_of: number;
3239
3323
  description: string;
3240
3324
  url: string;
@@ -3316,9 +3400,9 @@ declare const productSchema: z.ZodObject<{
3316
3400
  review_count: number;
3317
3401
  }, {
3318
3402
  add_to_cart: {
3319
- text: string;
3320
3403
  minimum: number;
3321
3404
  maximum: number;
3405
+ text: string;
3322
3406
  multiple_of: number;
3323
3407
  description: string;
3324
3408
  url: string;
@@ -3459,9 +3543,19 @@ interface ProductsAPI {
3459
3543
  get: (id: number) => Promise<Product>;
3460
3544
  categories: () => Promise<ProductCategory[]>;
3461
3545
  }
3546
+ interface AddItemsResult {
3547
+ cart: Cart;
3548
+ results: {
3549
+ item: AddToCartInput;
3550
+ status: number;
3551
+ code?: string;
3552
+ message?: string;
3553
+ }[];
3554
+ }
3462
3555
  interface CartAPI {
3463
3556
  get: () => Promise<Cart>;
3464
3557
  addItem: (input: AddToCartInput) => Promise<Cart>;
3558
+ addItems: (input: AddItemsInput) => Promise<AddItemsResult>;
3465
3559
  updateItem: (input: UpdateCartItemInput) => Promise<Cart>;
3466
3560
  removeItem: (input: RemoveCartItemInput) => Promise<Cart>;
3467
3561
  applyCoupon: (input: CouponInput) => Promise<Cart>;
@@ -3490,4 +3584,4 @@ interface WooCommerceClient {
3490
3584
  orders: OrdersAPI;
3491
3585
  }
3492
3586
 
3493
- export { selectShippingRateInputSchema as $, type AddToCartInput as A, BaseError as B, type CartHeadersAdapter as C, type StoreApiOrder as D, type UpdateCustomerInput as E, WooCommerceApiError as F, type GetOrderInput as G, type WooCommerceApiErrorOptions as H, addToCartInputSchema as I, type JwtTokenAdapter as J, cartItemImageSchema as K, cartSchema as L, checkoutInputSchema as M, checkoutSchema as N, type OrderStatus as O, type PaginatedResponse as P, couponInputSchema as Q, type ResponseOptions as R, type StoreApiVersion as S, productCategorySchema as T, type UpdateCartItemInput as U, type ValidationMode as V, type WooCommerceConfig as W, productImageSchema as X, productSchema as Y, removeCartItemInputSchema as Z, storeProductsSearchParamsSchema as _, type WooCommerceClient as a, storeApiOrderSchema as a0, updateCartItemInputSchema as a1, updateCustomerInputSchema as a2, handlePaginatedApiResponse as b, type Pagination as c, calculatePagination as d, type BaseErrorOptions as e, type ValidationReportableData as f, type WooCommerceDataValidationErrorOptions as g, handleApiResponse as h, isZodError as i, type Cart as j, type CartAPI as k, type CartItem as l, type CartItemImage as m, type Checkout as n, type CheckoutAPI as o, type CheckoutInput as p, type CouponInput as q, type OrdersAPI as r, setupErrorInterceptor as s, type Product as t, type ProductCategory as u, type ProductImage as v, type ProductParams as w, type ProductsAPI as x, type RemoveCartItemInput as y, type SelectShippingRateInput as z };
3587
+ export { checkoutSchema as $, type AddItemsInput as A, BaseError as B, type CartHeadersAdapter as C, type ProductImage as D, type ProductParams as E, type ProductsAPI as F, type GetOrderInput as G, type RemoveCartItemInput as H, type SelectShippingRateInput as I, type JwtTokenAdapter as J, type StoreApiOrder as K, type UpdateCustomerInput as L, WooCommerceApiError as M, type WooCommerceApiErrorOptions as N, type OrderStatus as O, type PaginatedResponse as P, addItemsInputSchema as Q, type ResponseOptions as R, type StoreApiVersion as S, addToCartInputSchema as T, type UpdateCartItemInput as U, type ValidationMode as V, type WooCommerceConfig as W, batchResponseSchema as X, cartItemImageSchema as Y, cartSchema as Z, checkoutInputSchema as _, type WooCommerceClient as a, couponInputSchema as a0, productCategorySchema as a1, productImageSchema as a2, productSchema as a3, removeCartItemInputSchema as a4, storeProductsSearchParamsSchema as a5, selectShippingRateInputSchema as a6, storeApiOrderSchema as a7, updateCartItemInputSchema as a8, updateCustomerInputSchema as a9, handleApiResponse as b, handlePaginatedApiResponse as c, type Pagination as d, calculatePagination as e, type WooCommerceApiErrorCode as f, type BaseErrorOptions as g, handleApiData as h, isZodError as i, type ValidationReportableData as j, type WooCommerceDataValidationErrorOptions as k, type AddItemsResult as l, type AddToCartInput as m, type BatchResponse as n, type Cart as o, type CartAPI as p, type CartItem as q, type CartItemImage as r, setupErrorInterceptor as s, type Checkout as t, type CheckoutAPI as u, type CheckoutInput as v, type CouponInput as w, type OrdersAPI as x, type Product as y, type ProductCategory as z };
@@ -1,5 +1,5 @@
1
- import { C as CartHeadersAdapter } from '../types-BF4_UUqp.mjs';
2
- export { P as PaginatedResponse, c as Pagination, R as ResponseOptions, V as ValidationMode, d as calculatePagination, h as handleApiResponse, b as handlePaginatedApiResponse, i as isZodError } from '../types-BF4_UUqp.mjs';
1
+ import { C as CartHeadersAdapter } from '../types-aYzN4O5x.mjs';
2
+ export { P as PaginatedResponse, d as Pagination, R as ResponseOptions, V as ValidationMode, e as calculatePagination, b as handleApiResponse, c as handlePaginatedApiResponse, i as isZodError } from '../types-aYzN4O5x.mjs';
3
3
  import { AxiosResponse, AxiosInstance } from 'axios';
4
4
  import 'zod';
5
5
 
@@ -1,5 +1,5 @@
1
- import { C as CartHeadersAdapter } from '../types-BF4_UUqp.js';
2
- export { P as PaginatedResponse, c as Pagination, R as ResponseOptions, V as ValidationMode, d as calculatePagination, h as handleApiResponse, b as handlePaginatedApiResponse, i as isZodError } from '../types-BF4_UUqp.js';
1
+ import { C as CartHeadersAdapter } from '../types-aYzN4O5x.js';
2
+ export { P as PaginatedResponse, d as Pagination, R as ResponseOptions, V as ValidationMode, e as calculatePagination, b as handleApiResponse, c as handlePaginatedApiResponse, i as isZodError } from '../types-aYzN4O5x.js';
3
3
  import { AxiosResponse, AxiosInstance } from 'axios';
4
4
  import 'zod';
5
5
 
@@ -131,34 +131,34 @@ var WooCommerceDataValidationError = class _WooCommerceDataValidationError exten
131
131
  };
132
132
 
133
133
  // src/http/handleApiResponse.ts
134
- var handleApiResponse = (response, schema, options) => {
134
+ var handleApiData = (data, schema, options, url) => {
135
135
  const validationMode = options?.validationMode ?? "strict";
136
136
  if (validationMode === "warn") {
137
- const result = schema.safeParse(response.data);
137
+ const result = schema.safeParse(data);
138
138
  if (!result.success) {
139
139
  const validationError = new WooCommerceDataValidationError({
140
- message: `WooCommerce API response validation failed for ${response.config.url || "unknown endpoint"}`,
141
- url: response.config.url,
140
+ message: `WooCommerce API response validation failed for ${url || "unknown endpoint"}`,
141
+ url,
142
142
  zodError: result.error,
143
- value: response.data,
143
+ value: data,
144
144
  userMessage: "Received unexpected data from WooCommerce"
145
145
  });
146
146
  options?.onValidationError?.(validationError);
147
147
  options?.errorReporter?.(validationError);
148
148
  console.warn("[woocommerce-utils] Validation warning:", validationError.message);
149
- return response.data;
149
+ return data;
150
150
  }
151
151
  return result.data;
152
152
  }
153
153
  try {
154
- return schema.parse(response.data);
154
+ return schema.parse(data);
155
155
  } catch (error) {
156
156
  if (error && typeof error === "object" && "issues" in error) {
157
157
  const validationError = new WooCommerceDataValidationError({
158
- message: `WooCommerce API response validation failed for ${response.config.url || "unknown endpoint"}`,
159
- url: response.config.url,
158
+ message: `WooCommerce API response validation failed for ${url || "unknown endpoint"}`,
159
+ url,
160
160
  zodError: error,
161
- value: response.data,
161
+ value: data,
162
162
  userMessage: "Received unexpected data from WooCommerce"
163
163
  });
164
164
  options?.onValidationError?.(validationError);
@@ -168,6 +168,7 @@ var handleApiResponse = (response, schema, options) => {
168
168
  throw error;
169
169
  }
170
170
  };
171
+ var handleApiResponse = (response, schema, options) => handleApiData(response.data, schema, options, response.config.url);
171
172
  var isZodError = (error) => {
172
173
  return error instanceof Error && error.name === "ZodError";
173
174
  };
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/errors/classes/BaseError.ts","../../src/errors/classes/WooCommerceDataValidationError.ts","../../src/http/handleApiResponse.ts","../../src/utils/calculatePagination.ts","../../src/utils/getPaginationMeta.ts","../../src/http/handlePaginatedApiResponse.ts","../../src/logging/logger.ts","../../src/utils/initializeCartSession.ts"],"names":[],"mappings":";;;AASO,IAAM,SAAA,GAAN,cAGG,KAAA,CAAM;AAAA,EACd,YAA4B,OAAA,EAAmB;AAC7C,IAAA,KAAA,CAAM,QAAQ,OAAO,CAAA;AADK,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AAI1B,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAGhD,IAAA,IAAA,CAAK,IAAA,GAAO,KAAK,WAAA,CAAY,IAAA;AAG7B,IAAA,IAAI,MAAM,iBAAA,EAAmB;AAC3B,MAAA,KAAA,CAAM,iBAAA,CAAkB,IAAA,EAAM,IAAA,CAAK,WAAW,CAAA;AAAA,IAChD;AAGA,IAAA,IAAI,KAAK,OAAA,CAAQ,KAAA,YAAiB,SAAS,IAAA,CAAK,OAAA,CAAQ,MAAM,KAAA,EAAO;AACnE,MAAA,IAAA,CAAK,KAAA,GAAQ,CAAA,EAAG,IAAA,CAAK,KAAK;AAAA,WAAA,EAAgB,IAAA,CAAK,OAAA,CAAQ,KAAA,CAAM,KAAK,CAAA,CAAA;AAAA,IACpE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,iBAAA,GAAiC;AAC/B,IAAA,MAAM,EAAE,IAAA,EAAM,SAAA,EAAW,WAAA,EAAa,SAAA,KAAc,IAAA,CAAK,OAAA;AACzD,IAAA,OAAO;AAAA,MACL,IAAA;AAAA,MACA,SAAA;AAAA,MACA,WAAA;AAAA,MACA;AAAA,KACF;AAAA,EACF;AAAA;AA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ACjB,CAAA;AAAA,IACH;AAAA,EACF,SAAS,KAAA,EAAO;AACd,IAAA,KAAA,CAAM,SAAA,EAAW,qCAAqC,KAAK,CAAA;AAC3D,IAAA,MAAM,KAAA;AAAA,EACR;AACF","file":"index.js","sourcesContent":["/**\n * Base error class for all package errors\n *\n * Generic over:\n * - TOptions: The options type for this error class\n * - TReportable: The reportable data structure for error tracking\n */\nimport type { BaseErrorOptions, BaseReportableData } from './types';\n\nexport class BaseError<\n TOptions extends BaseErrorOptions = BaseErrorOptions,\n TReportable extends BaseReportableData = BaseReportableData,\n> extends Error {\n constructor(public readonly options: TOptions) {\n super(options.message);\n\n // Maintain proper prototype chain\n Object.setPrototypeOf(this, new.target.prototype);\n\n // Set error name\n this.name = this.constructor.name;\n\n // Capture stack trace (excluding constructor call)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n // If there's a cause with a stack, preserve it\n if (this.options.cause instanceof Error && this.options.cause.stack) {\n this.stack = `${this.stack}\\nCaused by: ${this.options.cause.stack}`;\n }\n }\n\n /**\n * Get reportable data for error tracking/logging\n * Subclasses should override this to add their own reportable fields\n */\n getReportableData(): TReportable {\n const { code, operation, userMessage, retryable } = this.options;\n return {\n code,\n operation,\n userMessage,\n retryable,\n } as TReportable;\n }\n\n /**\n * Custom JSON serialization\n * Makes the error properly serializable for logging/reporting\n */\n toJSON(): Record<string, unknown> {\n return {\n ...this.getReportableData(),\n name: this.name,\n message: this.message,\n stack: this.stack,\n } as unknown as Record<string, unknown>;\n }\n}\n","/**\n * WooCommerce validation error class\n * Thrown when API response validation fails\n */\n\nimport type { ZodError } from 'zod';\n\nimport { BaseError } from './BaseError';\nimport type {\n BaseErrorOptions,\n ValidationReportableData,\n WooCommerceDataValidationErrorOptions,\n} from './types';\n\n/**\n * Internal options type that combines user options with computed fields\n */\ninterface WooCommerceDataValidationErrorInternalOptions extends BaseErrorOptions {\n url?: string;\n zodError?: ZodError;\n value?: unknown;\n fieldErrors?: Record<string, string[]>;\n}\n\n/**\n * WooCommerce validation error\n *\n * Thrown when API response validation fails using Zod schemas\n */\nexport class WooCommerceDataValidationError extends BaseError<\n WooCommerceDataValidationErrorInternalOptions,\n ValidationReportableData\n> {\n constructor(options: WooCommerceDataValidationErrorOptions) {\n // Extract field errors from Zod error if provided\n const fieldErrors = options.zodError\n ? WooCommerceDataValidationError.extractFieldErrorsFromZod(options.zodError)\n : undefined;\n\n super({\n code: 'validation_error',\n message: options.message,\n operation: options.operation,\n userMessage: options.userMessage || 'Received unexpected data from WooCommerce',\n retryable: false,\n cause: options.cause,\n url: options.url,\n zodError: options.zodError,\n value: options.value,\n fieldErrors,\n });\n }\n\n // Convenient getters for validation-specific fields (no duplication)\n get url(): string | undefined {\n return this.options.url;\n }\n\n get zodError(): ZodError | undefined {\n return this.options.zodError;\n }\n\n get invalidValue(): unknown | undefined {\n return this.options.value;\n }\n\n get fieldErrors(): Record<string, string[]> | undefined {\n return this.options.fieldErrors;\n }\n\n /**\n * Get reportable data for error tracking/logging\n * Includes validation-specific fields\n */\n override getReportableData(): ValidationReportableData {\n return {\n code: this.options.code,\n operation: this.options.operation,\n userMessage: this.options.userMessage,\n retryable: false,\n fieldErrors: this.options.fieldErrors,\n url: this.options.url,\n };\n }\n\n /**\n * Extract field errors from Zod error\n */\n private static extractFieldErrorsFromZod(\n zodError: ZodError\n ): Record<string, string[]> | undefined {\n if (!zodError?.errors) {\n return undefined;\n }\n\n const fieldErrors: Record<string, string[]> = {};\n\n for (const issue of zodError.errors) {\n const path = issue.path.join('.');\n if (!fieldErrors[path]) {\n fieldErrors[path] = [];\n }\n fieldErrors[path].push(issue.message);\n }\n\n return fieldErrors;\n }\n\n /**\n * Get all error messages as a flat array\n */\n getMessages(): string[] {\n if (!this.fieldErrors) {\n return [this.message];\n }\n\n const messages: string[] = [];\n for (const fieldMessages of Object.values(this.fieldErrors)) {\n messages.push(...fieldMessages);\n }\n\n return messages;\n }\n\n /**\n * Check if a specific field has errors\n */\n hasFieldError(field: string): boolean {\n return this.fieldErrors ? field in this.fieldErrors : false;\n }\n\n /**\n * Get error messages for a specific field\n */\n getFieldError(field: string): string[] | undefined {\n return this.fieldErrors?.[field];\n }\n}\n","/**\n * Response validation utilities\n */\n\nimport type { AxiosResponse } from 'axios';\nimport type { ZodError, ZodSchema } from 'zod';\n\nimport { WooCommerceDataValidationError } from '@/errors';\n\n/**\n * Validation mode for API responses\n * - 'strict': Throw error on validation failure (default)\n * - 'warn': Log warning and continue on validation failure\n */\nexport type ValidationMode = 'strict' | 'warn';\n\n/**\n * Options for response handling\n */\nexport interface ResponseOptions {\n /** Validation mode */\n validationMode?: ValidationMode;\n\n /** Error reporter for validation errors */\n errorReporter?: (error: Error) => void;\n\n /** Optional validation error handler (called before errorReporter) */\n onValidationError?: (error: Error) => void;\n}\n\n/**\n * Handle and validate API response\n *\n * @param response - Axios response\n * @param schema - Zod schema for validation\n * @param options - Response handling options\n * @returns Validated data\n * @throws ValidationError if validation fails in strict mode\n */\nexport const handleApiResponse = <T>(\n response: AxiosResponse,\n schema: ZodSchema<T>,\n options?: ResponseOptions\n): T => {\n const validationMode = options?.validationMode ?? 'strict';\n\n // Warn mode - use safeParse and continue on validation failure\n if (validationMode === 'warn') {\n const result = schema.safeParse(response.data);\n\n if (!result.success) {\n const validationError = new WooCommerceDataValidationError({\n message: `WooCommerce API response validation failed for ${response.config.url || 'unknown endpoint'}`,\n url: response.config.url,\n zodError: result.error,\n value: response.data,\n userMessage: 'Received unexpected data from WooCommerce',\n });\n\n // Call optional validation error handler\n options?.onValidationError?.(validationError);\n\n // Report to error tracker (if provided)\n options?.errorReporter?.(validationError);\n\n // Log warning to console in warn mode\n console.warn('[woocommerce-utils] Validation warning:', validationError.message);\n\n // Return raw data to allow app to continue\n return response.data as T;\n }\n\n return result.data;\n }\n\n // Strict mode - throw on validation failure\n try {\n return schema.parse(response.data);\n } catch (error) {\n if (error && typeof error === 'object' && 'issues' in error) {\n const validationError = new WooCommerceDataValidationError({\n message: `WooCommerce API response validation failed for ${response.config.url || 'unknown endpoint'}`,\n url: response.config.url,\n zodError: error as ZodError,\n value: response.data,\n userMessage: 'Received unexpected data from WooCommerce',\n });\n\n // Call optional validation error handler\n options?.onValidationError?.(validationError);\n\n // Report to error tracker (if provided)\n options?.errorReporter?.(validationError);\n\n throw validationError;\n }\n throw error;\n }\n};\n\n/**\n * Check if error is a Zod validation error\n */\nexport const isZodError = (error: unknown): error is ZodError => {\n return error instanceof Error && error.name === 'ZodError';\n};\n","/**\n * Calculate pagination navigation\n */\n\nexport interface Pagination {\n page: number;\n perPage: number;\n total: number;\n totalPages: number;\n hasNextPage: boolean;\n hasPrevPage: boolean;\n nextPage: number | null;\n prevPage: number | null;\n}\n\nexport interface CalculatePaginationInput {\n page: number;\n perPage: number;\n total: number;\n totalPages: number;\n}\n\n/**\n * Calculate pagination navigation from WooCommerce pagination metadata\n *\n * @param input - Current pagination state\n * @returns Full pagination object with navigation helpers\n */\nexport const calculatePagination = (input: CalculatePaginationInput): Pagination => {\n const { page, perPage, total, totalPages } = input;\n\n const hasNextPage = page < totalPages;\n const hasPrevPage = page > 1;\n\n return {\n page,\n perPage,\n total,\n totalPages,\n hasNextPage,\n hasPrevPage,\n nextPage: hasNextPage ? page + 1 : null,\n prevPage: hasPrevPage ? page - 1 : null,\n };\n};\n","/**\n * Extract pagination metadata from WooCommerce response headers\n */\n\nimport type { AxiosResponse } from 'axios';\n\nexport interface PaginationMeta {\n total: number;\n totalPages: number;\n}\n\nexport const getPaginationMeta = (headers: AxiosResponse['headers']): PaginationMeta => {\n // Handle undefined/null headers\n if (!headers) {\n return {\n total: 0,\n totalPages: 0,\n };\n }\n\n const wpTotal = headers['x-wp-total'];\n const wpTotalPages = headers['x-wp-totalpages'];\n\n if (!wpTotal || !wpTotalPages) {\n return {\n total: 0,\n totalPages: 0,\n };\n }\n\n const total = parseInt(wpTotal, 10);\n const totalPages = parseInt(wpTotalPages, 10);\n\n return {\n total,\n totalPages,\n };\n};\n","/**\n * Pagination utilities for WooCommerce API responses\n */\n\nimport type { AxiosResponse } from 'axios';\nimport type { ZodError, ZodSchema } from 'zod';\n\nimport { WooCommerceDataValidationError } from '../errors';\nimport { calculatePagination, type Pagination } from '../utils/calculatePagination';\nimport { getPaginationMeta } from '../utils/getPaginationMeta';\nimport type { ResponseOptions } from './handleApiResponse';\n\n/**\n * Paginated response wrapper\n */\nexport interface PaginatedResponse<T> {\n data: T[];\n pagination: Pagination;\n}\n\n/**\n * Handle paginated API response\n *\n * @param response - Axios response\n * @param schema - Zod schema for validating array items\n * @param params - Request parameters (page, per_page)\n * @param options - Response handling options\n * @returns Paginated response with validated data\n * @throws ValidationError if validation fails in strict mode\n */\nexport const handlePaginatedApiResponse = <T>(\n response: AxiosResponse,\n schema: ZodSchema<T[]>,\n params: { page?: number; per_page?: number } = {},\n options?: ResponseOptions\n): PaginatedResponse<T> => {\n const validationMode = options?.validationMode ?? 'strict';\n let data: T[];\n\n // Warn mode - use safeParse and continue on validation failure\n if (validationMode === 'warn') {\n const result = schema.safeParse(response.data);\n\n if (!result.success) {\n const validationError = new WooCommerceDataValidationError({\n message: `WooCommerce API response validation failed for ${response.config.url || 'unknown endpoint'}`,\n url: response.config.url,\n zodError: result.error,\n value: response.data,\n userMessage: 'Received unexpected data from WooCommerce',\n });\n\n // Call optional validation error handler\n options?.onValidationError?.(validationError);\n\n // Report to error tracker (if provided)\n options?.errorReporter?.(validationError);\n\n // Log warning to console in warn mode\n console.warn('[woocommerce-utils] Validation warning:', validationError.message);\n\n // Return raw data as array (best effort)\n data = Array.isArray(response.data) ? response.data : [];\n } else {\n data = result.data;\n }\n } else {\n // Strict mode - throw on validation failure\n try {\n data = schema.parse(response.data);\n } catch (error) {\n if (error && typeof error === 'object' && 'issues' in error) {\n const validationError = new WooCommerceDataValidationError({\n message: `WooCommerce API response validation failed for ${response.config.url || 'unknown endpoint'}`,\n url: response.config.url,\n zodError: error as ZodError,\n value: response.data,\n userMessage: 'Received unexpected data from WooCommerce',\n });\n\n // Call optional validation error handler\n options?.onValidationError?.(validationError);\n\n // Report to error tracker (if provided)\n options?.errorReporter?.(validationError);\n\n throw validationError;\n }\n throw error;\n }\n }\n\n const { total, totalPages } = getPaginationMeta(response.headers);\n const page = params.page || 1;\n const perPage = params.per_page || 10;\n\n const pagination = calculatePagination({\n page,\n perPage,\n total,\n totalPages,\n });\n\n return {\n data,\n pagination,\n };\n};\n","/**\n * Debug logger for WooCommerce utils\n */\n\nconst DEBUG_PREFIX = '[woocommerce-utils]';\n\n/**\n * Check if debug mode is enabled\n */\nexport const isDebugEnabled = (): boolean => {\n if (typeof process !== 'undefined' && process.env) {\n return process.env.DEBUG === 'true' || process.env.DEBUG === '1';\n }\n return false;\n};\n\n/**\n * Log debug message (only if DEBUG is enabled)\n */\nexport const debug = (...args: unknown[]): void => {\n if (isDebugEnabled()) {\n console.log(DEBUG_PREFIX, ...args);\n }\n};\n\n/**\n * Log warning message\n */\nexport const warn = (...args: unknown[]): void => {\n console.warn(DEBUG_PREFIX, ...args);\n};\n\n/**\n * Log error message\n */\nexport const error = (...args: unknown[]): void => {\n console.error(DEBUG_PREFIX, ...args);\n};\n","/**\n * Cart session initialization utility\n */\n\nimport type { AxiosInstance } from 'axios';\n\nimport type { CartHeadersAdapter } from '../client/types';\nimport { debug } from '../logging/logger';\n\n/**\n * Initialize cart session by fetching cart and saving headers\n *\n * This is called when nonce errors occur to get a fresh nonce/cart-token\n *\n * @param client - Axios instance\n * @param cartHeaders - Cart headers adapter\n */\nexport const initializeCartSession = async (\n client: AxiosInstance,\n cartHeaders: CartHeadersAdapter\n): Promise<void> => {\n try {\n debug('session', 'Initializing cart session');\n\n // Make GET request to cart endpoint\n const response = await client.get('/wc/store/v1/cart');\n\n // Extract headers\n const nonce = response.headers['nonce'] || response.headers['Nonce'];\n const cartToken = response.headers['cart-token'] || response.headers['Cart-Token'];\n\n // Save headers\n if (nonce || cartToken) {\n await cartHeaders.save({\n nonce: nonce || undefined,\n cartToken: cartToken || undefined,\n });\n\n debug('session', 'Cart session initialized', {\n hasNonce: !!nonce,\n hasCartToken: !!cartToken,\n });\n }\n } catch (error) {\n debug('session', 'Failed to initialize cart session', error);\n throw error;\n }\n};\n"]}
1
+ {"version":3,"sources":["../../src/errors/classes/BaseError.ts","../../src/errors/classes/WooCommerceDataValidationError.ts","../../src/http/handleApiResponse.ts","../../src/utils/calculatePagination.ts","../../src/utils/getPaginationMeta.ts","../../src/http/handlePaginatedApiResponse.ts","../../src/logging/logger.ts","../../src/utils/initializeCartSession.ts"],"names":[],"mappings":";;;AASO,IAAM,SAAA,GAAN,cAGG,KAAA,CAAM;AAAA,EACd,YAA4B,OAAA,EAAmB;AAC7C,IAAA,KAAA,CAAM,QAAQ,OAAO,CAAA;AADK,IAAA,IAAA,CAAA,OAAA,GAAA,OAAA;AAI1B,IAAA,MAAA,CAAO,cAAA,CAAe,IAAA,EAAM,GAAA,CAAA,MAAA,CAAW,SAAS,CAAA;AAGhD,IAAA,IAAA,CAAK,IAAA,GAAO,KAAK,WAAA,CAAY,IAAA;AAG7B,IAAA,IAAI,MAAM,iBAAA,EAAmB;AAC3B,MAAA,KAAA,CAAM,iBAAA,CAAkB,IAAA,EAAM,IAAA,CAAK,WAAW,CAAA;AAAA,IAChD;AAGA,IAAA,IAAI,KAAK,OAAA,CAAQ,KAAA,YAAiB,SAAS,IAAA,CAAK,OAAA,CAAQ,MAAM,KAAA,EAAO;AACnE,MAAA,IAAA,CAAK,KAAA,GAAQ,CAAA,EAAG,IAAA,CAAK,KAAK;AAAA,WAAA,EAAgB,IAAA,CAAK,OAAA,CAAQ,KAAA,CAAM,KAAK,CAAA,CAAA;AAAA,IACpE;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA,EAMA,iBAAA,GAAiC;AAC/B,IAAA,MAAM,EAAE,IAAA,EAAM,SAAA,EAAW,WAAA,EAAa,SAAA,KAAc,IAAA,CAAK,OAAA;AACzD,IAAA,OAAO;AAAA,MACL,IAAA;AA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AAA,QAC3C,QAAA,EAAU,CAAC,CAAC,KAAA;AAAA,QACZ,YAAA,EAAc,CAAC,CAAC;AAAA,OACjB,CAAA;AAAA,IACH;AAAA,EACF,SAAS,KAAA,EAAO;AACd,IAAA,KAAA,CAAM,SAAA,EAAW,qCAAqC,KAAK,CAAA;AAC3D,IAAA,MAAM,KAAA;AAAA,EACR;AACF","file":"index.js","sourcesContent":["/**\n * Base error class for all package errors\n *\n * Generic over:\n * - TOptions: The options type for this error class\n * - TReportable: The reportable data structure for error tracking\n */\nimport type { BaseErrorOptions, BaseReportableData } from './types';\n\nexport class BaseError<\n TOptions extends BaseErrorOptions = BaseErrorOptions,\n TReportable extends BaseReportableData = BaseReportableData,\n> extends Error {\n constructor(public readonly options: TOptions) {\n super(options.message);\n\n // Maintain proper prototype chain\n Object.setPrototypeOf(this, new.target.prototype);\n\n // Set error name\n this.name = this.constructor.name;\n\n // Capture stack trace (excluding constructor call)\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, this.constructor);\n }\n\n // If there's a cause with a stack, preserve it\n if (this.options.cause instanceof Error && this.options.cause.stack) {\n this.stack = `${this.stack}\\nCaused by: ${this.options.cause.stack}`;\n }\n }\n\n /**\n * Get reportable data for error tracking/logging\n * Subclasses should override this to add their own reportable fields\n */\n getReportableData(): TReportable {\n const { code, operation, userMessage, retryable } = this.options;\n return {\n code,\n operation,\n userMessage,\n retryable,\n } as TReportable;\n }\n\n /**\n * Custom JSON serialization\n * Makes the error properly serializable for logging/reporting\n */\n toJSON(): Record<string, unknown> {\n return {\n ...this.getReportableData(),\n name: this.name,\n message: this.message,\n stack: this.stack,\n } as unknown as Record<string, unknown>;\n }\n}\n","/**\n * WooCommerce validation error class\n * Thrown when API response validation fails\n */\n\nimport type { ZodError } from 'zod';\n\nimport { BaseError } from './BaseError';\nimport type {\n BaseErrorOptions,\n ValidationReportableData,\n WooCommerceDataValidationErrorOptions,\n} from './types';\n\n/**\n * Internal options type that combines user options with computed fields\n */\ninterface WooCommerceDataValidationErrorInternalOptions extends BaseErrorOptions {\n url?: string;\n zodError?: ZodError;\n value?: unknown;\n fieldErrors?: Record<string, string[]>;\n}\n\n/**\n * WooCommerce validation error\n *\n * Thrown when API response validation fails using Zod schemas\n */\nexport class WooCommerceDataValidationError extends BaseError<\n WooCommerceDataValidationErrorInternalOptions,\n ValidationReportableData\n> {\n constructor(options: WooCommerceDataValidationErrorOptions) {\n // Extract field errors from Zod error if provided\n const fieldErrors = options.zodError\n ? WooCommerceDataValidationError.extractFieldErrorsFromZod(options.zodError)\n : undefined;\n\n super({\n code: 'validation_error',\n message: options.message,\n operation: options.operation,\n userMessage: options.userMessage || 'Received unexpected data from WooCommerce',\n retryable: false,\n cause: options.cause,\n url: options.url,\n zodError: options.zodError,\n value: options.value,\n fieldErrors,\n });\n }\n\n // Convenient getters for validation-specific fields (no duplication)\n get url(): string | undefined {\n return this.options.url;\n }\n\n get zodError(): ZodError | undefined {\n return this.options.zodError;\n }\n\n get invalidValue(): unknown | undefined {\n return this.options.value;\n }\n\n get fieldErrors(): Record<string, string[]> | undefined {\n return this.options.fieldErrors;\n }\n\n /**\n * Get reportable data for error tracking/logging\n * Includes validation-specific fields\n */\n override getReportableData(): ValidationReportableData {\n return {\n code: this.options.code,\n operation: this.options.operation,\n userMessage: this.options.userMessage,\n retryable: false,\n fieldErrors: this.options.fieldErrors,\n url: this.options.url,\n };\n }\n\n /**\n * Extract field errors from Zod error\n */\n private static extractFieldErrorsFromZod(\n zodError: ZodError\n ): Record<string, string[]> | undefined {\n if (!zodError?.errors) {\n return undefined;\n }\n\n const fieldErrors: Record<string, string[]> = {};\n\n for (const issue of zodError.errors) {\n const path = issue.path.join('.');\n if (!fieldErrors[path]) {\n fieldErrors[path] = [];\n }\n fieldErrors[path].push(issue.message);\n }\n\n return fieldErrors;\n }\n\n /**\n * Get all error messages as a flat array\n */\n getMessages(): string[] {\n if (!this.fieldErrors) {\n return [this.message];\n }\n\n const messages: string[] = [];\n for (const fieldMessages of Object.values(this.fieldErrors)) {\n messages.push(...fieldMessages);\n }\n\n return messages;\n }\n\n /**\n * Check if a specific field has errors\n */\n hasFieldError(field: string): boolean {\n return this.fieldErrors ? field in this.fieldErrors : false;\n }\n\n /**\n * Get error messages for a specific field\n */\n getFieldError(field: string): string[] | undefined {\n return this.fieldErrors?.[field];\n }\n}\n","/**\n * Response validation utilities\n */\n\nimport type { AxiosResponse } from 'axios';\nimport type { ZodError, ZodSchema } from 'zod';\n\nimport { WooCommerceDataValidationError } from '@/errors';\n\n/**\n * Validation mode for API responses\n * - 'strict': Throw error on validation failure (default)\n * - 'warn': Log warning and continue on validation failure\n */\nexport type ValidationMode = 'strict' | 'warn';\n\n/**\n * Options for response handling\n */\nexport interface ResponseOptions {\n /** Validation mode */\n validationMode?: ValidationMode;\n\n /** Error reporter for validation errors */\n errorReporter?: (error: Error) => void;\n\n /** Optional validation error handler (called before errorReporter) */\n onValidationError?: (error: Error) => void;\n}\n\n/**\n * Handle and validate API response\n *\n * @param response - Axios response\n * @param schema - Zod schema for validation\n * @param options - Response handling options\n * @returns Validated data\n * @throws ValidationError if validation fails in strict mode\n */\nexport const handleApiData = <T>(\n data: unknown,\n schema: ZodSchema<T>,\n options?: ResponseOptions,\n url?: string\n): T => {\n const validationMode = options?.validationMode ?? 'strict';\n\n // Warn mode - use safeParse and continue on validation failure\n if (validationMode === 'warn') {\n const result = schema.safeParse(data);\n\n if (!result.success) {\n const validationError = new WooCommerceDataValidationError({\n message: `WooCommerce API response validation failed for ${url || 'unknown endpoint'}`,\n url,\n zodError: result.error,\n value: data,\n userMessage: 'Received unexpected data from WooCommerce',\n });\n\n // Call optional validation error handler\n options?.onValidationError?.(validationError);\n\n // Report to error tracker (if provided)\n options?.errorReporter?.(validationError);\n\n // Log warning to console in warn mode\n console.warn('[woocommerce-utils] Validation warning:', validationError.message);\n\n // Return raw data to allow app to continue\n return data as T;\n }\n\n return result.data;\n }\n\n // Strict mode - throw on validation failure\n try {\n return schema.parse(data);\n } catch (error) {\n if (error && typeof error === 'object' && 'issues' in error) {\n const validationError = new WooCommerceDataValidationError({\n message: `WooCommerce API response validation failed for ${url || 'unknown endpoint'}`,\n url,\n zodError: error as ZodError,\n value: data,\n userMessage: 'Received unexpected data from WooCommerce',\n });\n\n // Call optional validation error handler\n options?.onValidationError?.(validationError);\n\n // Report to error tracker (if provided)\n options?.errorReporter?.(validationError);\n\n throw validationError;\n }\n throw error;\n }\n};\n\nexport const handleApiResponse = <T>(\n response: AxiosResponse,\n schema: ZodSchema<T>,\n options?: ResponseOptions\n): T => handleApiData(response.data, schema, options, response.config.url);\n\n/**\n * Check if error is a Zod validation error\n */\nexport const isZodError = (error: unknown): error is ZodError => {\n return error instanceof Error && error.name === 'ZodError';\n};\n","/**\n * Calculate pagination navigation\n */\n\nexport interface Pagination {\n page: number;\n perPage: number;\n total: number;\n totalPages: number;\n hasNextPage: boolean;\n hasPrevPage: boolean;\n nextPage: number | null;\n prevPage: number | null;\n}\n\nexport interface CalculatePaginationInput {\n page: number;\n perPage: number;\n total: number;\n totalPages: number;\n}\n\n/**\n * Calculate pagination navigation from WooCommerce pagination metadata\n *\n * @param input - Current pagination state\n * @returns Full pagination object with navigation helpers\n */\nexport const calculatePagination = (input: CalculatePaginationInput): Pagination => {\n const { page, perPage, total, totalPages } = input;\n\n const hasNextPage = page < totalPages;\n const hasPrevPage = page > 1;\n\n return {\n page,\n perPage,\n total,\n totalPages,\n hasNextPage,\n hasPrevPage,\n nextPage: hasNextPage ? page + 1 : null,\n prevPage: hasPrevPage ? page - 1 : null,\n };\n};\n","/**\n * Extract pagination metadata from WooCommerce response headers\n */\n\nimport type { AxiosResponse } from 'axios';\n\nexport interface PaginationMeta {\n total: number;\n totalPages: number;\n}\n\nexport const getPaginationMeta = (headers: AxiosResponse['headers']): PaginationMeta => {\n // Handle undefined/null headers\n if (!headers) {\n return {\n total: 0,\n totalPages: 0,\n };\n }\n\n const wpTotal = headers['x-wp-total'];\n const wpTotalPages = headers['x-wp-totalpages'];\n\n if (!wpTotal || !wpTotalPages) {\n return {\n total: 0,\n totalPages: 0,\n };\n }\n\n const total = parseInt(wpTotal, 10);\n const totalPages = parseInt(wpTotalPages, 10);\n\n return {\n total,\n totalPages,\n };\n};\n","/**\n * Pagination utilities for WooCommerce API responses\n */\n\nimport type { AxiosResponse } from 'axios';\nimport type { ZodError, ZodSchema } from 'zod';\n\nimport { WooCommerceDataValidationError } from '../errors';\nimport { calculatePagination, type Pagination } from '../utils/calculatePagination';\nimport { getPaginationMeta } from '../utils/getPaginationMeta';\nimport type { ResponseOptions } from './handleApiResponse';\n\n/**\n * Paginated response wrapper\n */\nexport interface PaginatedResponse<T> {\n data: T[];\n pagination: Pagination;\n}\n\n/**\n * Handle paginated API response\n *\n * @param response - Axios response\n * @param schema - Zod schema for validating array items\n * @param params - Request parameters (page, per_page)\n * @param options - Response handling options\n * @returns Paginated response with validated data\n * @throws ValidationError if validation fails in strict mode\n */\nexport const handlePaginatedApiResponse = <T>(\n response: AxiosResponse,\n schema: ZodSchema<T[]>,\n params: { page?: number; per_page?: number } = {},\n options?: ResponseOptions\n): PaginatedResponse<T> => {\n const validationMode = options?.validationMode ?? 'strict';\n let data: T[];\n\n // Warn mode - use safeParse and continue on validation failure\n if (validationMode === 'warn') {\n const result = schema.safeParse(response.data);\n\n if (!result.success) {\n const validationError = new WooCommerceDataValidationError({\n message: `WooCommerce API response validation failed for ${response.config.url || 'unknown endpoint'}`,\n url: response.config.url,\n zodError: result.error,\n value: response.data,\n userMessage: 'Received unexpected data from WooCommerce',\n });\n\n // Call optional validation error handler\n options?.onValidationError?.(validationError);\n\n // Report to error tracker (if provided)\n options?.errorReporter?.(validationError);\n\n // Log warning to console in warn mode\n console.warn('[woocommerce-utils] Validation warning:', validationError.message);\n\n // Return raw data as array (best effort)\n data = Array.isArray(response.data) ? response.data : [];\n } else {\n data = result.data;\n }\n } else {\n // Strict mode - throw on validation failure\n try {\n data = schema.parse(response.data);\n } catch (error) {\n if (error && typeof error === 'object' && 'issues' in error) {\n const validationError = new WooCommerceDataValidationError({\n message: `WooCommerce API response validation failed for ${response.config.url || 'unknown endpoint'}`,\n url: response.config.url,\n zodError: error as ZodError,\n value: response.data,\n userMessage: 'Received unexpected data from WooCommerce',\n });\n\n // Call optional validation error handler\n options?.onValidationError?.(validationError);\n\n // Report to error tracker (if provided)\n options?.errorReporter?.(validationError);\n\n throw validationError;\n }\n throw error;\n }\n }\n\n const { total, totalPages } = getPaginationMeta(response.headers);\n const page = params.page || 1;\n const perPage = params.per_page || 10;\n\n const pagination = calculatePagination({\n page,\n perPage,\n total,\n totalPages,\n });\n\n return {\n data,\n pagination,\n };\n};\n","/**\n * Debug logger for WooCommerce utils\n */\n\nconst DEBUG_PREFIX = '[woocommerce-utils]';\n\n/**\n * Check if debug mode is enabled\n */\nexport const isDebugEnabled = (): boolean => {\n if (typeof process !== 'undefined' && process.env) {\n return process.env.DEBUG === 'true' || process.env.DEBUG === '1';\n }\n return false;\n};\n\n/**\n * Log debug message (only if DEBUG is enabled)\n */\nexport const debug = (...args: unknown[]): void => {\n if (isDebugEnabled()) {\n console.log(DEBUG_PREFIX, ...args);\n }\n};\n\n/**\n * Log warning message\n */\nexport const warn = (...args: unknown[]): void => {\n console.warn(DEBUG_PREFIX, ...args);\n};\n\n/**\n * Log error message\n */\nexport const error = (...args: unknown[]): void => {\n console.error(DEBUG_PREFIX, ...args);\n};\n","/**\n * Cart session initialization utility\n */\n\nimport type { AxiosInstance } from 'axios';\n\nimport type { CartHeadersAdapter } from '../client/types';\nimport { debug } from '../logging/logger';\n\n/**\n * Initialize cart session by fetching cart and saving headers\n *\n * This is called when nonce errors occur to get a fresh nonce/cart-token\n *\n * @param client - Axios instance\n * @param cartHeaders - Cart headers adapter\n */\nexport const initializeCartSession = async (\n client: AxiosInstance,\n cartHeaders: CartHeadersAdapter\n): Promise<void> => {\n try {\n debug('session', 'Initializing cart session');\n\n // Make GET request to cart endpoint\n const response = await client.get('/wc/store/v1/cart');\n\n // Extract headers\n const nonce = response.headers['nonce'] || response.headers['Nonce'];\n const cartToken = response.headers['cart-token'] || response.headers['Cart-Token'];\n\n // Save headers\n if (nonce || cartToken) {\n await cartHeaders.save({\n nonce: nonce || undefined,\n cartToken: cartToken || undefined,\n });\n\n debug('session', 'Cart session initialized', {\n hasNonce: !!nonce,\n hasCartToken: !!cartToken,\n });\n }\n } catch (error) {\n debug('session', 'Failed to initialize cart session', error);\n throw error;\n }\n};\n"]}