@payloadcms/plugin-ecommerce 3.69.0-internal.424436e → 3.69.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.
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/react/provider/index.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAa,MAAM,SAAS,CAAA;AAI/D,OAAO,KASN,MAAM,OAAO,CAAA;AAEd,OAAO,KAAK,EACV,mBAAmB,EAEnB,eAAe,EACf,YAAY,EACZ,QAAQ,EACR,oBAAoB,EACrB,MAAM,sBAAsB,CAAA;AAwC7B,eAAO,MAAM,iBAAiB,EAAE,KAAK,CAAC,EAAE,CAAC,YAAY,CA20BpD,CAAA;AAED,eAAO,MAAM,YAAY,4BAQxB,CAAA;AAED,eAAO,MAAM,WAAW;;6BAIX,IAAI,GAAG,MAAM,YAAY;QAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,KAAG,MAAM;;;CAkCrE,CAAA;AAED,wBAAgB,OAAO,CAAC,CAAC,SAAS,eAAe;;;;;UAU/B,CAAC;;;;;;EAOlB;AAED,eAAO,MAAM,WAAW;;;;;;;;;;CASvB,CAAA;AAED,wBAAgB,YAAY,CAAC,CAAC,SAAS,mBAAmB;eAOvB,CAAC,EAAE;;;;;;;;;;EACrC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../../src/react/provider/index.tsx"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,qBAAqB,EAAa,MAAM,SAAS,CAAA;AAI/D,OAAO,KASN,MAAM,OAAO,CAAA;AAEd,OAAO,KAAK,EACV,mBAAmB,EAEnB,eAAe,EACf,YAAY,EACZ,QAAQ,EACR,oBAAoB,EACrB,MAAM,sBAAsB,CAAA;AAwC7B,eAAO,MAAM,iBAAiB,EAAE,KAAK,CAAC,EAAE,CAAC,YAAY,CA80BpD,CAAA;AAED,eAAO,MAAM,YAAY,4BAQxB,CAAA;AAED,eAAO,MAAM,WAAW;;6BAIX,IAAI,GAAG,MAAM,YAAY;QAAE,QAAQ,CAAC,EAAE,QAAQ,CAAA;KAAE,KAAG,MAAM;;;CAkCrE,CAAA;AAED,wBAAgB,OAAO,CAAC,CAAC,SAAS,eAAe;;;;;UAU/B,CAAC;;;;;;EAOlB;AAED,eAAO,MAAM,WAAW;;;;;;;;;;CASvB,CAAA;AAED,wBAAgB,YAAY,CAAC,CAAC,SAAS,mBAAmB;eAOvB,CAAC,EAAE;;;;;;;;;;EACrC"}
@@ -1,6 +1,6 @@
1
1
  'use client';
2
2
  import { jsx as _jsx } from "react/jsx-runtime";
3
- import { deepMergeSimple } from 'payload/shared';
3
+ import { deepMergeSimple, formatAdminURL } from 'payload/shared';
4
4
  import * as qs from 'qs-esm';
5
5
  import React, { createContext, use, useCallback, useEffect, useMemo, useRef, useState, useTransition } from 'react';
6
6
  const defaultContext = {
@@ -53,8 +53,11 @@ export const EcommerceProvider = ({ addressesSlug = 'addresses', api, cartsSlug
53
53
  ...defaultLocalStorage,
54
54
  ...syncLocalStorage
55
55
  } : defaultLocalStorage;
56
- const { apiRoute = '/api', cartsFetchQuery = {}, serverURL = '' } = api || {};
57
- const baseAPIURL = `${serverURL}${apiRoute}`;
56
+ const { apiRoute = '/api', cartsFetchQuery = {} } = api || {};
57
+ const baseAPIURL = formatAdminURL({
58
+ apiRoute,
59
+ path: ''
60
+ });
58
61
  const [isLoading, startTransition] = useTransition();
59
62
  const [user, setUser] = useState(null);
60
63
  const [addresses, setAddresses] = useState();
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../src/react/provider/index.tsx"],"sourcesContent":["'use client'\nimport type { DefaultDocumentIDType, TypedUser } from 'payload'\n\nimport { deepMergeSimple } from 'payload/shared'\nimport * as qs from 'qs-esm'\nimport React, {\n createContext,\n use,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useTransition,\n} from 'react'\n\nimport type {\n AddressesCollection,\n CartItem,\n CartsCollection,\n ContextProps,\n Currency,\n EcommerceContextType,\n} from '../../types/index.js'\n\nconst defaultContext: EcommerceContextType = {\n addItem: async () => {},\n clearCart: async () => {},\n confirmOrder: async () => {},\n createAddress: async () => {},\n currenciesConfig: {\n defaultCurrency: 'USD',\n supportedCurrencies: [\n {\n code: 'USD',\n decimals: 2,\n label: 'US Dollar',\n symbol: '$',\n },\n ],\n },\n currency: {\n code: 'USD',\n decimals: 2,\n label: 'US Dollar',\n symbol: '$',\n },\n decrementItem: async () => {},\n incrementItem: async () => {},\n initiatePayment: async () => {},\n isLoading: false,\n paymentMethods: [],\n removeItem: async () => {},\n setCurrency: () => {},\n updateAddress: async () => {},\n}\n\nconst EcommerceContext = createContext<EcommerceContextType>(defaultContext)\n\nconst defaultLocalStorage = {\n key: 'cart',\n}\n\nexport const EcommerceProvider: React.FC<ContextProps> = ({\n addressesSlug = 'addresses',\n api,\n cartsSlug = 'carts',\n children,\n currenciesConfig = {\n defaultCurrency: 'USD',\n supportedCurrencies: [\n {\n code: 'USD',\n decimals: 2,\n label: 'US Dollar',\n symbol: '$',\n },\n ],\n },\n customersSlug = 'users',\n debug = false,\n paymentMethods = [],\n syncLocalStorage = true,\n}) => {\n const localStorageConfig =\n syncLocalStorage && typeof syncLocalStorage === 'object'\n ? {\n ...defaultLocalStorage,\n ...syncLocalStorage,\n }\n : defaultLocalStorage\n\n const { apiRoute = '/api', cartsFetchQuery = {}, serverURL = '' } = api || {}\n const baseAPIURL = `${serverURL}${apiRoute}`\n\n const [isLoading, startTransition] = useTransition()\n\n const [user, setUser] = useState<null | TypedUser>(null)\n\n const [addresses, setAddresses] = useState<AddressesCollection[]>()\n\n const hasRendered = useRef(false)\n\n /**\n * The ID of the cart associated with the current session.\n * This is used to identify the cart in the database or local storage.\n * It can be null if no cart has been created yet.\n */\n const [cartID, setCartID] = useState<DefaultDocumentIDType>()\n /**\n * The secret for accessing guest carts without authentication.\n * This is generated when a guest user creates a cart.\n */\n const [cartSecret, setCartSecret] = useState<string | undefined>(undefined)\n const [cart, setCart] = useState<CartsCollection>()\n\n const [selectedCurrency, setSelectedCurrency] = useState<Currency>(\n () =>\n currenciesConfig.supportedCurrencies.find(\n (c) => c.code === currenciesConfig.defaultCurrency,\n )!,\n )\n\n const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<null | string>(null)\n\n const cartQuery = useMemo(() => {\n const priceField = `priceIn${selectedCurrency.code}`\n\n const baseQuery = {\n depth: 0,\n populate: {\n products: {\n [priceField]: true,\n },\n variants: {\n options: true,\n [priceField]: true,\n },\n },\n select: {\n items: true,\n subtotal: true,\n },\n }\n\n return deepMergeSimple(baseQuery, cartsFetchQuery)\n }, [selectedCurrency.code, cartsFetchQuery])\n\n const createCart = useCallback(\n async (initialData: Record<string, unknown>) => {\n const query = qs.stringify(cartQuery)\n\n const response = await fetch(`${baseAPIURL}/${cartsSlug}?${query}`, {\n body: JSON.stringify({\n ...initialData,\n currency: selectedCurrency.code,\n customer: user?.id,\n }),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to create cart: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Cart creation error: ${data.error}`)\n }\n\n // Store the secret for guest cart access\n if (!user && data.doc?.secret) {\n setCartSecret(data.doc.secret)\n }\n\n return data.doc as CartsCollection\n },\n [baseAPIURL, cartQuery, cartsSlug, selectedCurrency.code, user],\n )\n\n const getCart = useCallback(\n async (cartID: DefaultDocumentIDType, options?: { secret?: string }) => {\n const secret = options?.secret\n\n // Build query params with secret if provided\n const queryParams = {\n ...cartQuery,\n ...(secret ? { secret } : {}),\n }\n const query = qs.stringify(queryParams)\n\n const response = await fetch(`${baseAPIURL}/${cartsSlug}/${cartID}?${query}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to fetch cart: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Cart fetch error: ${data.error}`)\n }\n\n return data as CartsCollection\n },\n [baseAPIURL, cartQuery, cartsSlug],\n )\n\n const updateCart = useCallback(\n async (cartID: DefaultDocumentIDType, data: Partial<CartsCollection>) => {\n // Build query params with secret if provided\n const queryParams = {\n ...cartQuery,\n ...(cartSecret ? { secret: cartSecret } : {}),\n }\n const query = qs.stringify(queryParams)\n\n const response = await fetch(`${baseAPIURL}/${cartsSlug}/${cartID}?${query}`, {\n body: JSON.stringify(data),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'PATCH',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to update cart: ${errorText}`)\n }\n\n const updatedCart = await response.json()\n\n setCart(updatedCart.doc as CartsCollection)\n },\n [baseAPIURL, cartQuery, cartsSlug, cartSecret],\n )\n\n const deleteCart = useCallback(\n async (cartID: DefaultDocumentIDType) => {\n // Build query params with secret if provided\n const queryParams = cartSecret ? { secret: cartSecret } : {}\n const query = qs.stringify(queryParams)\n const url = `${baseAPIURL}/${cartsSlug}/${cartID}${query ? `?${query}` : ''}`\n\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'DELETE',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to delete cart: ${errorText}`)\n }\n\n setCart(undefined)\n setCartID(undefined)\n setCartSecret(undefined)\n },\n [baseAPIURL, cartsSlug, cartSecret],\n )\n\n // Persist cart ID and secret to localStorage\n useEffect(() => {\n if (hasRendered.current) {\n if (syncLocalStorage) {\n if (cartID) {\n localStorage.setItem(localStorageConfig.key, cartID as string)\n } else {\n localStorage.removeItem(localStorageConfig.key)\n }\n\n if (cartSecret) {\n localStorage.setItem(`${localStorageConfig.key}_secret`, cartSecret)\n } else {\n localStorage.removeItem(`${localStorageConfig.key}_secret`)\n }\n }\n }\n }, [cartID, cartSecret, localStorageConfig.key, syncLocalStorage])\n\n const addItem: EcommerceContextType['addItem'] = useCallback(\n async (item, quantity = 1) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (cartID) {\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n\n setCartID(undefined)\n setCart(undefined)\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => {\n const productID =\n typeof cartItem.product === 'object' ? cartItem.product.id : item.product\n const variantID =\n cartItem.variant && typeof cartItem.variant === 'object'\n ? cartItem.variant.id\n : item.variant\n\n return (\n productID === item.product &&\n (item.variant && variantID ? variantID === item.variant : true)\n )\n }) ?? -1\n\n let updatedItems = existingCart.items ? [...existingCart.items] : []\n\n if (existingItemIndex !== -1) {\n // If the item exists, update its quantity\n updatedItems[existingItemIndex].quantity =\n updatedItems[existingItemIndex].quantity + quantity\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n } else {\n // If the item does not exist, add it to the cart\n updatedItems = [...(existingCart.items ?? []), { ...item, quantity }]\n }\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n } else {\n // If no cartID exists, create a new cart\n const newCart = await createCart({ items: [{ ...item, quantity }] })\n\n setCartID(newCart.id)\n setCart(newCart)\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, createCart, getCart, startTransition, updateCart],\n )\n\n const removeItem: EcommerceContextType['removeItem'] = useCallback(\n async (targetID) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (!cartID) {\n resolve()\n return\n }\n\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n setCartID(undefined)\n setCart(undefined)\n resolve()\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => cartItem.id === targetID) ?? -1\n\n if (existingItemIndex !== -1) {\n // If the item exists, remove it from the cart\n const updatedItems = existingCart.items ? [...existingCart.items] : []\n updatedItems.splice(existingItemIndex, 1)\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, getCart, startTransition, updateCart],\n )\n\n const incrementItem: EcommerceContextType['incrementItem'] = useCallback(\n async (targetID) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (!cartID) {\n resolve()\n return\n }\n\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n setCartID(undefined)\n setCart(undefined)\n resolve()\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => cartItem.id === targetID) ?? -1\n\n let updatedItems = existingCart.items ? [...existingCart.items] : []\n\n if (existingItemIndex !== -1) {\n // If the item exists, increment its quantity\n updatedItems[existingItemIndex].quantity = updatedItems[existingItemIndex].quantity + 1 // Increment by 1\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n } else {\n // If the item does not exist, add it to the cart with quantity 1\n updatedItems = [...(existingCart.items ?? []), { product: targetID, quantity: 1 }]\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, getCart, startTransition, updateCart],\n )\n\n const decrementItem: EcommerceContextType['decrementItem'] = useCallback(\n async (targetID) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (!cartID) {\n resolve()\n return\n }\n\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n setCartID(undefined)\n setCart(undefined)\n resolve()\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => cartItem.id === targetID) ?? -1\n\n const updatedItems = existingCart.items ? [...existingCart.items] : []\n\n if (existingItemIndex !== -1) {\n // If the item exists, decrement its quantity\n updatedItems[existingItemIndex].quantity = updatedItems[existingItemIndex].quantity - 1 // Decrement by 1\n\n // If the quantity reaches 0, remove the item from the cart\n if (updatedItems[existingItemIndex].quantity <= 0) {\n updatedItems.splice(existingItemIndex, 1)\n }\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, getCart, startTransition, updateCart],\n )\n\n const clearCart: EcommerceContextType['clearCart'] = useCallback(async () => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (cartID) {\n await deleteCart(cartID)\n }\n resolve()\n })\n })\n }, [cartID, deleteCart, startTransition])\n\n const setCurrency: EcommerceContextType['setCurrency'] = useCallback(\n (currency) => {\n if (selectedCurrency.code === currency) {\n return\n }\n\n const foundCurrency = currenciesConfig.supportedCurrencies.find((c) => c.code === currency)\n if (!foundCurrency) {\n throw new Error(`Currency with code \"${currency}\" not found in config`)\n }\n\n setSelectedCurrency(foundCurrency)\n },\n [currenciesConfig.supportedCurrencies, selectedCurrency.code],\n )\n\n const initiatePayment = useCallback<EcommerceContextType['initiatePayment']>(\n async (paymentMethodID, options) => {\n const paymentMethod = paymentMethods.find((method) => method.name === paymentMethodID)\n\n if (!paymentMethod) {\n throw new Error(`Payment method with ID \"${paymentMethodID}\" not found`)\n }\n\n if (!cartID) {\n throw new Error(`No cart is provided.`)\n }\n\n setSelectedPaymentMethod(paymentMethodID)\n\n if (paymentMethod.initiatePayment) {\n const fetchURL = `${baseAPIURL}/payments/${paymentMethodID}/initiate`\n\n const data = {\n cartID,\n currency: selectedCurrency.code,\n }\n\n try {\n const response = await fetch(fetchURL, {\n body: JSON.stringify({\n ...data,\n ...(options?.additionalData || {}),\n }),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const responseError = await response.text()\n throw new Error(responseError)\n }\n\n const responseData = await response.json()\n\n if (responseData.error) {\n throw new Error(responseData.error)\n }\n\n return responseData\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error initiating payment:', error)\n }\n throw new Error(error instanceof Error ? error.message : 'Failed to initiate payment')\n }\n } else {\n throw new Error(`Payment method \"${paymentMethodID}\" does not support payment initiation`)\n }\n },\n [baseAPIURL, cartID, debug, paymentMethods, selectedCurrency.code],\n )\n\n const confirmOrder = useCallback<EcommerceContextType['initiatePayment']>(\n async (paymentMethodID, options) => {\n if (!cartID) {\n throw new Error(`Cart is empty.`)\n }\n\n const paymentMethod = paymentMethods.find((pm) => pm.name === paymentMethodID)\n\n if (!paymentMethod) {\n throw new Error(`Payment method with ID \"${paymentMethodID}\" not found`)\n }\n\n if (paymentMethod.confirmOrder) {\n const fetchURL = `${baseAPIURL}/payments/${paymentMethodID}/confirm-order`\n\n const data = {\n cartID,\n currency: selectedCurrency.code,\n }\n\n const response = await fetch(fetchURL, {\n body: JSON.stringify({\n ...data,\n ...(options?.additionalData || {}),\n }),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const responseError = await response.text()\n throw new Error(responseError)\n }\n\n const responseData = await response.json()\n\n if (responseData.error) {\n throw new Error(responseData.error)\n }\n\n return responseData\n } else {\n throw new Error(`Payment method \"${paymentMethodID}\" does not support order confirmation`)\n }\n },\n [baseAPIURL, cartID, paymentMethods, selectedCurrency.code],\n )\n\n const getUser = useCallback(async () => {\n try {\n const query = qs.stringify({\n depth: 0,\n select: {\n id: true,\n carts: true,\n },\n })\n\n const response = await fetch(`${baseAPIURL}/${customersSlug}/me?${query}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to fetch user: ${errorText}`)\n }\n\n const userData = await response.json()\n\n if (userData.error) {\n throw new Error(`User fetch error: ${userData.error}`)\n }\n\n if (userData.user) {\n setUser(userData.user as TypedUser)\n return userData.user as TypedUser\n }\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error fetching user:', error)\n }\n setUser(null)\n throw new Error(\n `Failed to fetch user: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n }, [baseAPIURL, customersSlug, debug])\n\n const getAddresses = useCallback(async () => {\n if (!user) {\n return\n }\n\n try {\n const query = qs.stringify({\n depth: 0,\n limit: 0,\n pagination: false,\n })\n\n const response = await fetch(`${baseAPIURL}/${addressesSlug}?${query}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n\n throw new Error(errorText)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Address fetch error: ${data.error}`)\n }\n\n if (data.docs && data.docs.length > 0) {\n setAddresses(data.docs)\n }\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error fetching addresses:', error)\n }\n setAddresses(undefined)\n throw new Error(\n `Failed to fetch addresses: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n }, [user, baseAPIURL, addressesSlug, debug])\n\n const updateAddress = useCallback<EcommerceContextType['updateAddress']>(\n async (addressID, address) => {\n if (!user) {\n throw new Error('User must be logged in to update or create an address')\n }\n\n try {\n const response = await fetch(`${baseAPIURL}/${addressesSlug}/${addressID}`, {\n body: JSON.stringify(address),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'PATCH',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to update or create address: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Address update/create error: ${data.error}`)\n }\n\n // Refresh addresses after updating or creating\n await getAddresses()\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error updating or creating address:', error)\n }\n\n throw new Error(\n `Failed to update or create address: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n },\n [user, baseAPIURL, addressesSlug, getAddresses, debug],\n )\n\n const createAddress = useCallback<EcommerceContextType['createAddress']>(\n async (address) => {\n if (!user) {\n throw new Error('User must be logged in to update or create an address')\n }\n\n try {\n const response = await fetch(`${baseAPIURL}/${addressesSlug}`, {\n body: JSON.stringify(address),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to update or create address: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Address update/create error: ${data.error}`)\n }\n\n // Refresh addresses after updating or creating\n await getAddresses()\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error updating or creating address:', error)\n }\n\n throw new Error(\n `Failed to update or create address: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n },\n [user, baseAPIURL, addressesSlug, getAddresses, debug],\n )\n\n // If localStorage is enabled, restore cart from storage\n useEffect(() => {\n if (!hasRendered.current) {\n if (syncLocalStorage) {\n const storedCartID = localStorage.getItem(localStorageConfig.key)\n const storedSecret = localStorage.getItem(`${localStorageConfig.key}_secret`)\n\n if (storedCartID) {\n getCart(storedCartID, { secret: storedSecret || undefined })\n .then((fetchedCart) => {\n setCart(fetchedCart)\n setCartID(storedCartID as DefaultDocumentIDType)\n if (storedSecret) {\n setCartSecret(storedSecret)\n }\n })\n .catch((_) => {\n // console.error('Error fetching cart from localStorage:', error)\n // If there's an error fetching the cart, clear it from localStorage\n localStorage.removeItem(localStorageConfig.key)\n localStorage.removeItem(`${localStorageConfig.key}_secret`)\n setCartID(undefined)\n setCart(undefined)\n setCartSecret(undefined)\n })\n }\n }\n\n hasRendered.current = true\n\n void getUser().then((user) => {\n if (user && user.cart?.docs && user.cart.docs.length > 0) {\n // If the user has carts, we can set the cartID to the first cart\n const cartID =\n typeof user.cart.docs[0] === 'object' ? user.cart.docs[0].id : user.cart.docs[0]\n\n if (cartID) {\n getCart(cartID)\n .then((fetchedCart) => {\n setCart(fetchedCart)\n setCartID(cartID)\n })\n .catch((error) => {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error fetching user cart:', error)\n }\n\n setCart(undefined)\n setCartID(undefined)\n\n throw new Error(`Failed to fetch user cart: ${error.message}`)\n })\n }\n }\n })\n }\n }, [debug, getAddresses, getCart, getUser, localStorageConfig.key, syncLocalStorage])\n\n useEffect(() => {\n if (user) {\n // If the user is logged in, fetch their addresses\n void getAddresses()\n } else {\n // If no user is logged in, clear addresses\n setAddresses(undefined)\n }\n }, [getAddresses, user])\n\n return (\n <EcommerceContext\n value={{\n addItem,\n addresses,\n cart,\n clearCart,\n confirmOrder,\n createAddress,\n currenciesConfig,\n currency: selectedCurrency,\n decrementItem,\n incrementItem,\n initiatePayment,\n isLoading,\n paymentMethods,\n removeItem,\n selectedPaymentMethod,\n setCurrency,\n updateAddress,\n }}\n >\n {children}\n </EcommerceContext>\n )\n}\n\nexport const useEcommerce = () => {\n const context = use(EcommerceContext)\n\n if (!context) {\n throw new Error('useEcommerce must be used within an EcommerceProvider')\n }\n\n return context\n}\n\nexport const useCurrency = () => {\n const { currenciesConfig, currency, setCurrency } = useEcommerce()\n\n const formatCurrency = useCallback(\n (value?: null | number, options?: { currency?: Currency }): string => {\n if (value === undefined || value === null) {\n return ''\n }\n\n const currencyToUse = options?.currency || currency\n\n if (!currencyToUse) {\n return value.toString()\n }\n\n if (value === 0) {\n return `${currencyToUse.symbol}0.${'0'.repeat(currencyToUse.decimals)}`\n }\n\n // Convert from base value (e.g., cents) to decimal value (e.g., dollars)\n const decimalValue = value / Math.pow(10, currencyToUse.decimals)\n\n // Format with the correct number of decimal places\n return `${currencyToUse.symbol}${decimalValue.toFixed(currencyToUse.decimals)}`\n },\n [currency],\n )\n\n if (!currency) {\n throw new Error('useCurrency must be used within an EcommerceProvider')\n }\n\n return {\n currency,\n formatCurrency,\n setCurrency,\n supportedCurrencies: currenciesConfig.supportedCurrencies,\n }\n}\n\nexport function useCart<T extends CartsCollection>() {\n const { addItem, cart, clearCart, decrementItem, incrementItem, isLoading, removeItem } =\n useEcommerce()\n\n if (!addItem) {\n throw new Error('useCart must be used within an EcommerceProvider')\n }\n\n return {\n addItem,\n cart: cart as T,\n clearCart,\n decrementItem,\n incrementItem,\n isLoading,\n removeItem,\n }\n}\n\nexport const usePayments = () => {\n const { confirmOrder, initiatePayment, isLoading, paymentMethods, selectedPaymentMethod } =\n useEcommerce()\n\n if (!initiatePayment) {\n throw new Error('usePayments must be used within an EcommerceProvider')\n }\n\n return { confirmOrder, initiatePayment, isLoading, paymentMethods, selectedPaymentMethod }\n}\n\nexport function useAddresses<T extends AddressesCollection>() {\n const { addresses, createAddress, isLoading, updateAddress } = useEcommerce()\n\n if (!createAddress) {\n throw new Error('usePayments must be used within an EcommerceProvider')\n }\n\n return { addresses: addresses as T[], createAddress, isLoading, updateAddress }\n}\n"],"names":["deepMergeSimple","qs","React","createContext","use","useCallback","useEffect","useMemo","useRef","useState","useTransition","defaultContext","addItem","clearCart","confirmOrder","createAddress","currenciesConfig","defaultCurrency","supportedCurrencies","code","decimals","label","symbol","currency","decrementItem","incrementItem","initiatePayment","isLoading","paymentMethods","removeItem","setCurrency","updateAddress","EcommerceContext","defaultLocalStorage","key","EcommerceProvider","addressesSlug","api","cartsSlug","children","customersSlug","debug","syncLocalStorage","localStorageConfig","apiRoute","cartsFetchQuery","serverURL","baseAPIURL","startTransition","user","setUser","addresses","setAddresses","hasRendered","cartID","setCartID","cartSecret","setCartSecret","undefined","cart","setCart","selectedCurrency","setSelectedCurrency","find","c","selectedPaymentMethod","setSelectedPaymentMethod","cartQuery","priceField","baseQuery","depth","populate","products","variants","options","select","items","subtotal","createCart","initialData","query","stringify","response","fetch","body","JSON","customer","id","credentials","headers","method","ok","errorText","text","Error","data","json","error","doc","secret","getCart","queryParams","updateCart","updatedCart","deleteCart","url","current","localStorage","setItem","item","quantity","Promise","resolve","existingCart","existingItemIndex","findIndex","cartItem","productID","product","variantID","variant","updatedItems","newCart","targetID","splice","foundCurrency","paymentMethodID","paymentMethod","name","fetchURL","additionalData","responseError","responseData","console","message","pm","getUser","carts","userData","getAddresses","limit","pagination","docs","length","addressID","address","storedCartID","getItem","storedSecret","then","fetchedCart","catch","_","value","useEcommerce","context","useCurrency","formatCurrency","currencyToUse","toString","repeat","decimalValue","Math","pow","toFixed","useCart","usePayments","useAddresses"],"mappings":"AAAA;;AAGA,SAASA,eAAe,QAAQ,iBAAgB;AAChD,YAAYC,QAAQ,SAAQ;AAC5B,OAAOC,SACLC,aAAa,EACbC,GAAG,EACHC,WAAW,EACXC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,QAAQ,EACRC,aAAa,QACR,QAAO;AAWd,MAAMC,iBAAuC;IAC3CC,SAAS,WAAa;IACtBC,WAAW,WAAa;IACxBC,cAAc,WAAa;IAC3BC,eAAe,WAAa;IAC5BC,kBAAkB;QAChBC,iBAAiB;QACjBC,qBAAqB;YACnB;gBACEC,MAAM;gBACNC,UAAU;gBACVC,OAAO;gBACPC,QAAQ;YACV;SACD;IACH;IACAC,UAAU;QACRJ,MAAM;QACNC,UAAU;QACVC,OAAO;QACPC,QAAQ;IACV;IACAE,eAAe,WAAa;IAC5BC,eAAe,WAAa;IAC5BC,iBAAiB,WAAa;IAC9BC,WAAW;IACXC,gBAAgB,EAAE;IAClBC,YAAY,WAAa;IACzBC,aAAa,KAAO;IACpBC,eAAe,WAAa;AAC9B;AAEA,MAAMC,iCAAmB7B,cAAoCQ;AAE7D,MAAMsB,sBAAsB;IAC1BC,KAAK;AACP;AAEA,OAAO,MAAMC,oBAA4C,CAAC,EACxDC,gBAAgB,WAAW,EAC3BC,GAAG,EACHC,YAAY,OAAO,EACnBC,QAAQ,EACRvB,mBAAmB;IACjBC,iBAAiB;IACjBC,qBAAqB;QACnB;YACEC,MAAM;YACNC,UAAU;YACVC,OAAO;YACPC,QAAQ;QACV;KAC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AAEA,OAAO,MAAMyI,cAAc;IACzB,MAAM,EAAExJ,YAAY,EAAEY,eAAe,EAAEC,SAAS,EAAEC,cAAc,EAAEqC,qBAAqB,EAAE,GACvFyF;IAEF,IAAI,CAAChI,iBAAiB;QACpB,MAAM,IAAIoE,MAAM;IAClB;IAEA,OAAO;QAAEhF;QAAcY;QAAiBC;QAAWC;QAAgBqC;IAAsB;AAC3F,EAAC;AAED,OAAO,SAASsG;IACd,MAAM,EAAEpH,SAAS,EAAEpC,aAAa,EAAEY,SAAS,EAAEI,aAAa,EAAE,GAAG2H;IAE/D,IAAI,CAAC3I,eAAe;QAClB,MAAM,IAAI+E,MAAM;IAClB;IAEA,OAAO;QAAE3C,WAAWA;QAAkBpC;QAAeY;QAAWI;IAAc;AAChF"}
1
+ {"version":3,"sources":["../../../src/react/provider/index.tsx"],"sourcesContent":["'use client'\nimport type { DefaultDocumentIDType, TypedUser } from 'payload'\n\nimport { deepMergeSimple, formatAdminURL } from 'payload/shared'\nimport * as qs from 'qs-esm'\nimport React, {\n createContext,\n use,\n useCallback,\n useEffect,\n useMemo,\n useRef,\n useState,\n useTransition,\n} from 'react'\n\nimport type {\n AddressesCollection,\n CartItem,\n CartsCollection,\n ContextProps,\n Currency,\n EcommerceContextType,\n} from '../../types/index.js'\n\nconst defaultContext: EcommerceContextType = {\n addItem: async () => {},\n clearCart: async () => {},\n confirmOrder: async () => {},\n createAddress: async () => {},\n currenciesConfig: {\n defaultCurrency: 'USD',\n supportedCurrencies: [\n {\n code: 'USD',\n decimals: 2,\n label: 'US Dollar',\n symbol: '$',\n },\n ],\n },\n currency: {\n code: 'USD',\n decimals: 2,\n label: 'US Dollar',\n symbol: '$',\n },\n decrementItem: async () => {},\n incrementItem: async () => {},\n initiatePayment: async () => {},\n isLoading: false,\n paymentMethods: [],\n removeItem: async () => {},\n setCurrency: () => {},\n updateAddress: async () => {},\n}\n\nconst EcommerceContext = createContext<EcommerceContextType>(defaultContext)\n\nconst defaultLocalStorage = {\n key: 'cart',\n}\n\nexport const EcommerceProvider: React.FC<ContextProps> = ({\n addressesSlug = 'addresses',\n api,\n cartsSlug = 'carts',\n children,\n currenciesConfig = {\n defaultCurrency: 'USD',\n supportedCurrencies: [\n {\n code: 'USD',\n decimals: 2,\n label: 'US Dollar',\n symbol: '$',\n },\n ],\n },\n customersSlug = 'users',\n debug = false,\n paymentMethods = [],\n syncLocalStorage = true,\n}) => {\n const localStorageConfig =\n syncLocalStorage && typeof syncLocalStorage === 'object'\n ? {\n ...defaultLocalStorage,\n ...syncLocalStorage,\n }\n : defaultLocalStorage\n\n const { apiRoute = '/api', cartsFetchQuery = {} } = api || {}\n const baseAPIURL = formatAdminURL({\n apiRoute,\n path: '',\n })\n\n const [isLoading, startTransition] = useTransition()\n\n const [user, setUser] = useState<null | TypedUser>(null)\n\n const [addresses, setAddresses] = useState<AddressesCollection[]>()\n\n const hasRendered = useRef(false)\n\n /**\n * The ID of the cart associated with the current session.\n * This is used to identify the cart in the database or local storage.\n * It can be null if no cart has been created yet.\n */\n const [cartID, setCartID] = useState<DefaultDocumentIDType>()\n /**\n * The secret for accessing guest carts without authentication.\n * This is generated when a guest user creates a cart.\n */\n const [cartSecret, setCartSecret] = useState<string | undefined>(undefined)\n const [cart, setCart] = useState<CartsCollection>()\n\n const [selectedCurrency, setSelectedCurrency] = useState<Currency>(\n () =>\n currenciesConfig.supportedCurrencies.find(\n (c) => c.code === currenciesConfig.defaultCurrency,\n )!,\n )\n\n const [selectedPaymentMethod, setSelectedPaymentMethod] = useState<null | string>(null)\n\n const cartQuery = useMemo(() => {\n const priceField = `priceIn${selectedCurrency.code}`\n\n const baseQuery = {\n depth: 0,\n populate: {\n products: {\n [priceField]: true,\n },\n variants: {\n options: true,\n [priceField]: true,\n },\n },\n select: {\n items: true,\n subtotal: true,\n },\n }\n\n return deepMergeSimple(baseQuery, cartsFetchQuery)\n }, [selectedCurrency.code, cartsFetchQuery])\n\n const createCart = useCallback(\n async (initialData: Record<string, unknown>) => {\n const query = qs.stringify(cartQuery)\n\n const response = await fetch(`${baseAPIURL}/${cartsSlug}?${query}`, {\n body: JSON.stringify({\n ...initialData,\n currency: selectedCurrency.code,\n customer: user?.id,\n }),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to create cart: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Cart creation error: ${data.error}`)\n }\n\n // Store the secret for guest cart access\n if (!user && data.doc?.secret) {\n setCartSecret(data.doc.secret)\n }\n\n return data.doc as CartsCollection\n },\n [baseAPIURL, cartQuery, cartsSlug, selectedCurrency.code, user],\n )\n\n const getCart = useCallback(\n async (cartID: DefaultDocumentIDType, options?: { secret?: string }) => {\n const secret = options?.secret\n\n // Build query params with secret if provided\n const queryParams = {\n ...cartQuery,\n ...(secret ? { secret } : {}),\n }\n const query = qs.stringify(queryParams)\n\n const response = await fetch(`${baseAPIURL}/${cartsSlug}/${cartID}?${query}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to fetch cart: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Cart fetch error: ${data.error}`)\n }\n\n return data as CartsCollection\n },\n [baseAPIURL, cartQuery, cartsSlug],\n )\n\n const updateCart = useCallback(\n async (cartID: DefaultDocumentIDType, data: Partial<CartsCollection>) => {\n // Build query params with secret if provided\n const queryParams = {\n ...cartQuery,\n ...(cartSecret ? { secret: cartSecret } : {}),\n }\n const query = qs.stringify(queryParams)\n\n const response = await fetch(`${baseAPIURL}/${cartsSlug}/${cartID}?${query}`, {\n body: JSON.stringify(data),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'PATCH',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to update cart: ${errorText}`)\n }\n\n const updatedCart = await response.json()\n\n setCart(updatedCart.doc as CartsCollection)\n },\n [baseAPIURL, cartQuery, cartsSlug, cartSecret],\n )\n\n const deleteCart = useCallback(\n async (cartID: DefaultDocumentIDType) => {\n // Build query params with secret if provided\n const queryParams = cartSecret ? { secret: cartSecret } : {}\n const query = qs.stringify(queryParams)\n const url = `${baseAPIURL}/${cartsSlug}/${cartID}${query ? `?${query}` : ''}`\n\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'DELETE',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to delete cart: ${errorText}`)\n }\n\n setCart(undefined)\n setCartID(undefined)\n setCartSecret(undefined)\n },\n [baseAPIURL, cartsSlug, cartSecret],\n )\n\n // Persist cart ID and secret to localStorage\n useEffect(() => {\n if (hasRendered.current) {\n if (syncLocalStorage) {\n if (cartID) {\n localStorage.setItem(localStorageConfig.key, cartID as string)\n } else {\n localStorage.removeItem(localStorageConfig.key)\n }\n\n if (cartSecret) {\n localStorage.setItem(`${localStorageConfig.key}_secret`, cartSecret)\n } else {\n localStorage.removeItem(`${localStorageConfig.key}_secret`)\n }\n }\n }\n }, [cartID, cartSecret, localStorageConfig.key, syncLocalStorage])\n\n const addItem: EcommerceContextType['addItem'] = useCallback(\n async (item, quantity = 1) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (cartID) {\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n\n setCartID(undefined)\n setCart(undefined)\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => {\n const productID =\n typeof cartItem.product === 'object' ? cartItem.product.id : item.product\n const variantID =\n cartItem.variant && typeof cartItem.variant === 'object'\n ? cartItem.variant.id\n : item.variant\n\n return (\n productID === item.product &&\n (item.variant && variantID ? variantID === item.variant : true)\n )\n }) ?? -1\n\n let updatedItems = existingCart.items ? [...existingCart.items] : []\n\n if (existingItemIndex !== -1) {\n // If the item exists, update its quantity\n updatedItems[existingItemIndex].quantity =\n updatedItems[existingItemIndex].quantity + quantity\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n } else {\n // If the item does not exist, add it to the cart\n updatedItems = [...(existingCart.items ?? []), { ...item, quantity }]\n }\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n } else {\n // If no cartID exists, create a new cart\n const newCart = await createCart({ items: [{ ...item, quantity }] })\n\n setCartID(newCart.id)\n setCart(newCart)\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, createCart, getCart, startTransition, updateCart],\n )\n\n const removeItem: EcommerceContextType['removeItem'] = useCallback(\n async (targetID) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (!cartID) {\n resolve()\n return\n }\n\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n setCartID(undefined)\n setCart(undefined)\n resolve()\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => cartItem.id === targetID) ?? -1\n\n if (existingItemIndex !== -1) {\n // If the item exists, remove it from the cart\n const updatedItems = existingCart.items ? [...existingCart.items] : []\n updatedItems.splice(existingItemIndex, 1)\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, getCart, startTransition, updateCart],\n )\n\n const incrementItem: EcommerceContextType['incrementItem'] = useCallback(\n async (targetID) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (!cartID) {\n resolve()\n return\n }\n\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n setCartID(undefined)\n setCart(undefined)\n resolve()\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => cartItem.id === targetID) ?? -1\n\n let updatedItems = existingCart.items ? [...existingCart.items] : []\n\n if (existingItemIndex !== -1) {\n // If the item exists, increment its quantity\n updatedItems[existingItemIndex].quantity = updatedItems[existingItemIndex].quantity + 1 // Increment by 1\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n } else {\n // If the item does not exist, add it to the cart with quantity 1\n updatedItems = [...(existingCart.items ?? []), { product: targetID, quantity: 1 }]\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, getCart, startTransition, updateCart],\n )\n\n const decrementItem: EcommerceContextType['decrementItem'] = useCallback(\n async (targetID) => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (!cartID) {\n resolve()\n return\n }\n\n const existingCart = await getCart(cartID, { secret: cartSecret })\n\n if (!existingCart) {\n // console.error(`Cart with ID \"${cartID}\" not found`)\n setCartID(undefined)\n setCart(undefined)\n resolve()\n return\n }\n\n // Check if the item already exists in the cart\n const existingItemIndex =\n existingCart.items?.findIndex((cartItem: CartItem) => cartItem.id === targetID) ?? -1\n\n const updatedItems = existingCart.items ? [...existingCart.items] : []\n\n if (existingItemIndex !== -1) {\n // If the item exists, decrement its quantity\n updatedItems[existingItemIndex].quantity = updatedItems[existingItemIndex].quantity - 1 // Decrement by 1\n\n // If the quantity reaches 0, remove the item from the cart\n if (updatedItems[existingItemIndex].quantity <= 0) {\n updatedItems.splice(existingItemIndex, 1)\n }\n\n // Update the cart with the new items\n await updateCart(cartID, {\n items: updatedItems,\n })\n }\n resolve()\n })\n })\n },\n [cartID, cartSecret, getCart, startTransition, updateCart],\n )\n\n const clearCart: EcommerceContextType['clearCart'] = useCallback(async () => {\n return new Promise<void>((resolve) => {\n startTransition(async () => {\n if (cartID) {\n await deleteCart(cartID)\n }\n resolve()\n })\n })\n }, [cartID, deleteCart, startTransition])\n\n const setCurrency: EcommerceContextType['setCurrency'] = useCallback(\n (currency) => {\n if (selectedCurrency.code === currency) {\n return\n }\n\n const foundCurrency = currenciesConfig.supportedCurrencies.find((c) => c.code === currency)\n if (!foundCurrency) {\n throw new Error(`Currency with code \"${currency}\" not found in config`)\n }\n\n setSelectedCurrency(foundCurrency)\n },\n [currenciesConfig.supportedCurrencies, selectedCurrency.code],\n )\n\n const initiatePayment = useCallback<EcommerceContextType['initiatePayment']>(\n async (paymentMethodID, options) => {\n const paymentMethod = paymentMethods.find((method) => method.name === paymentMethodID)\n\n if (!paymentMethod) {\n throw new Error(`Payment method with ID \"${paymentMethodID}\" not found`)\n }\n\n if (!cartID) {\n throw new Error(`No cart is provided.`)\n }\n\n setSelectedPaymentMethod(paymentMethodID)\n\n if (paymentMethod.initiatePayment) {\n const fetchURL = `${baseAPIURL}/payments/${paymentMethodID}/initiate`\n\n const data = {\n cartID,\n currency: selectedCurrency.code,\n }\n\n try {\n const response = await fetch(fetchURL, {\n body: JSON.stringify({\n ...data,\n ...(options?.additionalData || {}),\n }),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const responseError = await response.text()\n throw new Error(responseError)\n }\n\n const responseData = await response.json()\n\n if (responseData.error) {\n throw new Error(responseData.error)\n }\n\n return responseData\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error initiating payment:', error)\n }\n throw new Error(error instanceof Error ? error.message : 'Failed to initiate payment')\n }\n } else {\n throw new Error(`Payment method \"${paymentMethodID}\" does not support payment initiation`)\n }\n },\n [baseAPIURL, cartID, debug, paymentMethods, selectedCurrency.code],\n )\n\n const confirmOrder = useCallback<EcommerceContextType['initiatePayment']>(\n async (paymentMethodID, options) => {\n if (!cartID) {\n throw new Error(`Cart is empty.`)\n }\n\n const paymentMethod = paymentMethods.find((pm) => pm.name === paymentMethodID)\n\n if (!paymentMethod) {\n throw new Error(`Payment method with ID \"${paymentMethodID}\" not found`)\n }\n\n if (paymentMethod.confirmOrder) {\n const fetchURL = `${baseAPIURL}/payments/${paymentMethodID}/confirm-order`\n\n const data = {\n cartID,\n currency: selectedCurrency.code,\n }\n\n const response = await fetch(fetchURL, {\n body: JSON.stringify({\n ...data,\n ...(options?.additionalData || {}),\n }),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const responseError = await response.text()\n throw new Error(responseError)\n }\n\n const responseData = await response.json()\n\n if (responseData.error) {\n throw new Error(responseData.error)\n }\n\n return responseData\n } else {\n throw new Error(`Payment method \"${paymentMethodID}\" does not support order confirmation`)\n }\n },\n [baseAPIURL, cartID, paymentMethods, selectedCurrency.code],\n )\n\n const getUser = useCallback(async () => {\n try {\n const query = qs.stringify({\n depth: 0,\n select: {\n id: true,\n carts: true,\n },\n })\n\n const response = await fetch(`${baseAPIURL}/${customersSlug}/me?${query}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to fetch user: ${errorText}`)\n }\n\n const userData = await response.json()\n\n if (userData.error) {\n throw new Error(`User fetch error: ${userData.error}`)\n }\n\n if (userData.user) {\n setUser(userData.user as TypedUser)\n return userData.user as TypedUser\n }\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error fetching user:', error)\n }\n setUser(null)\n throw new Error(\n `Failed to fetch user: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n }, [baseAPIURL, customersSlug, debug])\n\n const getAddresses = useCallback(async () => {\n if (!user) {\n return\n }\n\n try {\n const query = qs.stringify({\n depth: 0,\n limit: 0,\n pagination: false,\n })\n\n const response = await fetch(`${baseAPIURL}/${addressesSlug}?${query}`, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'GET',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n\n throw new Error(errorText)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Address fetch error: ${data.error}`)\n }\n\n if (data.docs && data.docs.length > 0) {\n setAddresses(data.docs)\n }\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error fetching addresses:', error)\n }\n setAddresses(undefined)\n throw new Error(\n `Failed to fetch addresses: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n }, [user, baseAPIURL, addressesSlug, debug])\n\n const updateAddress = useCallback<EcommerceContextType['updateAddress']>(\n async (addressID, address) => {\n if (!user) {\n throw new Error('User must be logged in to update or create an address')\n }\n\n try {\n const response = await fetch(`${baseAPIURL}/${addressesSlug}/${addressID}`, {\n body: JSON.stringify(address),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'PATCH',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to update or create address: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Address update/create error: ${data.error}`)\n }\n\n // Refresh addresses after updating or creating\n await getAddresses()\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error updating or creating address:', error)\n }\n\n throw new Error(\n `Failed to update or create address: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n },\n [user, baseAPIURL, addressesSlug, getAddresses, debug],\n )\n\n const createAddress = useCallback<EcommerceContextType['createAddress']>(\n async (address) => {\n if (!user) {\n throw new Error('User must be logged in to update or create an address')\n }\n\n try {\n const response = await fetch(`${baseAPIURL}/${addressesSlug}`, {\n body: JSON.stringify(address),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n })\n\n if (!response.ok) {\n const errorText = await response.text()\n throw new Error(`Failed to update or create address: ${errorText}`)\n }\n\n const data = await response.json()\n\n if (data.error) {\n throw new Error(`Address update/create error: ${data.error}`)\n }\n\n // Refresh addresses after updating or creating\n await getAddresses()\n } catch (error) {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error updating or creating address:', error)\n }\n\n throw new Error(\n `Failed to update or create address: ${error instanceof Error ? error.message : 'Unknown error'}`,\n )\n }\n },\n [user, baseAPIURL, addressesSlug, getAddresses, debug],\n )\n\n // If localStorage is enabled, restore cart from storage\n useEffect(() => {\n if (!hasRendered.current) {\n if (syncLocalStorage) {\n const storedCartID = localStorage.getItem(localStorageConfig.key)\n const storedSecret = localStorage.getItem(`${localStorageConfig.key}_secret`)\n\n if (storedCartID) {\n getCart(storedCartID, { secret: storedSecret || undefined })\n .then((fetchedCart) => {\n setCart(fetchedCart)\n setCartID(storedCartID as DefaultDocumentIDType)\n if (storedSecret) {\n setCartSecret(storedSecret)\n }\n })\n .catch((_) => {\n // console.error('Error fetching cart from localStorage:', error)\n // If there's an error fetching the cart, clear it from localStorage\n localStorage.removeItem(localStorageConfig.key)\n localStorage.removeItem(`${localStorageConfig.key}_secret`)\n setCartID(undefined)\n setCart(undefined)\n setCartSecret(undefined)\n })\n }\n }\n\n hasRendered.current = true\n\n void getUser().then((user) => {\n if (user && user.cart?.docs && user.cart.docs.length > 0) {\n // If the user has carts, we can set the cartID to the first cart\n const cartID =\n typeof user.cart.docs[0] === 'object' ? user.cart.docs[0].id : user.cart.docs[0]\n\n if (cartID) {\n getCart(cartID)\n .then((fetchedCart) => {\n setCart(fetchedCart)\n setCartID(cartID)\n })\n .catch((error) => {\n if (debug) {\n // eslint-disable-next-line no-console\n console.error('Error fetching user cart:', error)\n }\n\n setCart(undefined)\n setCartID(undefined)\n\n throw new Error(`Failed to fetch user cart: ${error.message}`)\n })\n }\n }\n })\n }\n }, [debug, getAddresses, getCart, getUser, localStorageConfig.key, syncLocalStorage])\n\n useEffect(() => {\n if (user) {\n // If the user is logged in, fetch their addresses\n void getAddresses()\n } else {\n // If no user is logged in, clear addresses\n setAddresses(undefined)\n }\n }, [getAddresses, user])\n\n return (\n <EcommerceContext\n value={{\n addItem,\n addresses,\n cart,\n clearCart,\n confirmOrder,\n createAddress,\n currenciesConfig,\n currency: selectedCurrency,\n decrementItem,\n incrementItem,\n initiatePayment,\n isLoading,\n paymentMethods,\n removeItem,\n selectedPaymentMethod,\n setCurrency,\n updateAddress,\n }}\n >\n {children}\n </EcommerceContext>\n )\n}\n\nexport const useEcommerce = () => {\n const context = use(EcommerceContext)\n\n if (!context) {\n throw new Error('useEcommerce must be used within an EcommerceProvider')\n }\n\n return context\n}\n\nexport const useCurrency = () => {\n const { currenciesConfig, currency, setCurrency } = useEcommerce()\n\n const formatCurrency = useCallback(\n (value?: null | number, options?: { currency?: Currency }): string => {\n if (value === undefined || value === null) {\n return ''\n }\n\n const currencyToUse = options?.currency || currency\n\n if (!currencyToUse) {\n return value.toString()\n }\n\n if (value === 0) {\n return `${currencyToUse.symbol}0.${'0'.repeat(currencyToUse.decimals)}`\n }\n\n // Convert from base value (e.g., cents) to decimal value (e.g., dollars)\n const decimalValue = value / Math.pow(10, currencyToUse.decimals)\n\n // Format with the correct number of decimal places\n return `${currencyToUse.symbol}${decimalValue.toFixed(currencyToUse.decimals)}`\n },\n [currency],\n )\n\n if (!currency) {\n throw new Error('useCurrency must be used within an EcommerceProvider')\n }\n\n return {\n currency,\n formatCurrency,\n setCurrency,\n supportedCurrencies: currenciesConfig.supportedCurrencies,\n }\n}\n\nexport function useCart<T extends CartsCollection>() {\n const { addItem, cart, clearCart, decrementItem, incrementItem, isLoading, removeItem } =\n useEcommerce()\n\n if (!addItem) {\n throw new Error('useCart must be used within an EcommerceProvider')\n }\n\n return {\n addItem,\n cart: cart as T,\n clearCart,\n decrementItem,\n incrementItem,\n isLoading,\n removeItem,\n }\n}\n\nexport const usePayments = () => {\n const { confirmOrder, initiatePayment, isLoading, paymentMethods, selectedPaymentMethod } =\n useEcommerce()\n\n if (!initiatePayment) {\n throw new Error('usePayments must be used within an EcommerceProvider')\n }\n\n return { confirmOrder, initiatePayment, isLoading, paymentMethods, selectedPaymentMethod }\n}\n\nexport function useAddresses<T extends AddressesCollection>() {\n const { addresses, createAddress, isLoading, updateAddress } = useEcommerce()\n\n if (!createAddress) {\n throw new Error('usePayments must be used within an EcommerceProvider')\n }\n\n return { addresses: addresses as T[], createAddress, isLoading, updateAddress }\n}\n"],"names":["deepMergeSimple","formatAdminURL","qs","React","createContext","use","useCallback","useEffect","useMemo","useRef","useState","useTransition","defaultContext","addItem","clearCart","confirmOrder","createAddress","currenciesConfig","defaultCurrency","supportedCurrencies","code","decimals","label","symbol","currency","decrementItem","incrementItem","initiatePayment","isLoading","paymentMethods","removeItem","setCurrency","updateAddress","EcommerceContext","defaultLocalStorage","key","EcommerceProvider","addressesSlug","api","cartsSlug","children","customersSlug","debug","syncLocalStorage","localStorageConfig","apiRoute","cartsFetchQuery","baseAPIURL","path","startTransition","user","setUser","addresses","setAddresses","hasRendered","cartID","setCartID","cartSecret","setCartSecret","undefined","cart","setCart","selectedCurrency","setSelectedCurrency","find","c","selectedPaymentMethod","setSelectedPaymentMethod","cartQuery","priceField","baseQuery","depth","populate","products","variants","options","select","items","subtotal","createCart","initialData","query","stringify","response","fetch","body","JSON","customer","id","credentials","headers","method","ok","errorText","text","Error","data","json","error","doc","secret","getCart","queryParams","updateCart","updatedCart","deleteCart","url","current","localStorage","setItem","item","quantity","Promise","resolve","existingCart","existingItemIndex","findIndex","cartItem","productID","product","variantID","variant","updatedItems","newCart","targetID","splice","foundCurrency","paymentMethodID","paymentMethod","name","fetchURL","additionalData","responseError","responseData","console","message","pm","getUser","carts","userData","getAddresses","limit","pagination","docs","length","addressID","address","storedCartID","getItem","storedSecret","then","fetchedCart","catch","_","value","useEcommerce","context","useCurrency","formatCurrency","currencyToUse","toString","repeat","decimalValue","Math","pow","toFixed","useCart","usePayments","useAddresses"],"mappings":"AAAA;;AAGA,SAASA,eAAe,EAAEC,cAAc,QAAQ,iBAAgB;AAChE,YAAYC,QAAQ,SAAQ;AAC5B,OAAOC,SACLC,aAAa,EACbC,GAAG,EACHC,WAAW,EACXC,SAAS,EACTC,OAAO,EACPC,MAAM,EACNC,QAAQ,EACRC,aAAa,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-1,3 +1,4 @@
1
+ import { describe, it, expect } from 'vitest';
1
2
  import { accessAND, conditional, accessOR } from './accessComposition';
2
3
  // Mock access args for testing
3
4
  const mockArgs = {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/accessComposition.spec.ts"],"sourcesContent":["import type { Access, AccessArgs, Where } from 'payload'\n\nimport { accessAND, conditional, accessOR } from './accessComposition'\n\n// Mock access args for testing\nconst mockArgs: AccessArgs = {\n req: {\n user: null,\n headers: new Headers(),\n payload: {} as any,\n context: {},\n } as any,\n}\n\nconst mockArgsWithUser: AccessArgs = {\n req: {\n user: { id: '123', email: 'test@example.com' },\n headers: new Headers(),\n payload: {} as any,\n context: {},\n } as any,\n}\n\ndescribe('Access Composition Utilities', () => {\n describe('or', () => {\n it('should return true when first checker returns true', async () => {\n const checker1: Access = async () => true\n const checker2: Access = async () => false\n\n const result = await accessOR(checker1, checker2)(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should return true when any checker returns true', async () => {\n const checker1: Access = async () => false\n const checker2: Access = async () => true\n const checker3: Access = async () => false\n\n const result = await accessOR(checker1, checker2, checker3)(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should return false when all checkers return false', async () => {\n const checker1: Access = async () => false\n const checker2: Access = async () => false\n const checker3: Access = async () => false\n\n const result = await accessOR(checker1, checker2, checker3)(mockArgs)\n\n expect(result).toBe(false)\n })\n\n it('should combine Where queries with OR logic', async () => {\n const checker1: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker2: Access = async () => ({\n status: { equals: 'published' },\n })\n\n const result = await accessOR(checker1, checker2)(mockArgs)\n\n expect(result).toEqual({\n or: [{ customer: { equals: '123' } }, { status: { equals: 'published' } }],\n })\n })\n\n it('should return true when one checker returns true and others return Where queries', async () => {\n const checker1: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker2: Access = async () => true\n\n const result = await accessOR(checker1, checker2)(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should ignore false values when combining Where queries', async () => {\n const checker1: Access = async () => false\n const checker2: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker3: Access = async () => false\n const checker4: Access = async () => ({\n status: { equals: 'published' },\n })\n\n const result = await accessOR(checker1, checker2, checker3, checker4)(mockArgs)\n\n expect(result).toEqual({\n or: [{ customer: { equals: '123' } }, { status: { equals: 'published' } }],\n })\n })\n\n it('should return a single Where query when only one checker returns a Where query', async () => {\n const checker1: Access = async () => false\n const checker2: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker3: Access = async () => false\n\n const result = await accessOR(checker1, checker2, checker3)(mockArgs)\n\n expect(result).toEqual({\n or: [{ customer: { equals: '123' } }],\n })\n })\n\n it('should short-circuit on first true result for performance', async () => {\n let secondCheckerCalled = false\n\n const checker1: Access = async () => true\n const checker2: Access = async () => {\n secondCheckerCalled = true\n return false\n }\n\n await accessOR(checker1, checker2)(mockArgs)\n\n expect(secondCheckerCalled).toBe(false)\n })\n\n it('should handle empty checkers array', async () => {\n const result = await accessOR()(mockArgs)\n\n expect(result).toBe(false)\n })\n\n it('should handle complex nested Where queries', async () => {\n const checker1: Access = async () =>\n ({\n and: [{ customer: { equals: '123' } }, { status: { equals: 'active' } }],\n }) as Where\n const checker2: Access = async () => ({\n role: { equals: 'admin' },\n })\n\n const result = await accessOR(checker1, checker2)(mockArgs)\n\n expect(result).toEqual({\n or: [\n { and: [{ customer: { equals: '123' } }, { status: { equals: 'active' } }] },\n { role: { equals: 'admin' } },\n ],\n })\n })\n })\n\n describe('and', () => {\n it('should return false when any checker returns false', async () => {\n const checker1: Access = async () => true\n const checker2: Access = async () => false\n\n const result = await accessAND(checker1, checker2)(mockArgs)\n\n expect(result).toBe(false)\n })\n\n it('should return true when all checkers return true', async () => {\n const checker1: Access = async () => true\n const checker2: Access = async () => true\n const checker3: Access = async () => true\n\n const result = await accessAND(checker1, checker2, checker3)(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should combine Where queries with AND logic', async () => {\n const checker1: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker2: Access = async () => ({\n status: { equals: 'published' },\n })\n\n const result = await accessAND(checker1, checker2)(mockArgs)\n\n expect(result).toEqual({\n and: [{ customer: { equals: '123' } }, { status: { equals: 'published' } }],\n })\n })\n\n it('should return false when one checker returns false and others return Where queries', async () => {\n const checker1: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker2: Access = async () => false\n\n const result = await accessAND(checker1, checker2)(mockArgs)\n\n expect(result).toBe(false)\n })\n\n it('should return Where query when all checkers return Where queries except one returns true', async () => {\n const checker1: Access = async () => true\n const checker2: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker3: Access = async () => ({\n status: { equals: 'published' },\n })\n\n const result = await accessAND(checker1, checker2, checker3)(mockArgs)\n\n expect(result).toEqual({\n and: [{ customer: { equals: '123' } }, { status: { equals: 'published' } }],\n })\n })\n\n it('should short-circuit on first false result for performance', async () => {\n let secondCheckerCalled = false\n\n const checker1: Access = async () => false\n const checker2: Access = async () => {\n secondCheckerCalled = true\n return true\n }\n\n await accessAND(checker1, checker2)(mockArgs)\n\n expect(secondCheckerCalled).toBe(false)\n })\n\n it('should handle empty checkers array', async () => {\n const result = await accessAND()(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should return a single Where query when only one checker returns a Where query', async () => {\n const checker1: Access = async () => true\n const checker2: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker3: Access = async () => true\n\n const result = await accessAND(checker1, checker2, checker3)(mockArgs)\n\n expect(result).toEqual({\n and: [{ customer: { equals: '123' } }],\n })\n })\n\n it('should handle complex nested Where queries', async () => {\n const checker1: Access = async () => ({\n or: [{ customer: { equals: '123' } }, { customer: { equals: '456' } }],\n })\n const checker2: Access = async () => ({\n status: { equals: 'active' },\n })\n\n const result = await accessAND(checker1, checker2)(mockArgs)\n\n expect(result).toEqual({\n and: [\n { or: [{ customer: { equals: '123' } }, { customer: { equals: '456' } }] },\n { status: { equals: 'active' } },\n ],\n })\n })\n\n it('should return false immediately when first checker returns false', async () => {\n const checker1: Access = async () => false\n const checker2: Access = async () => {\n throw new Error('Should not be called')\n }\n\n const result = await accessAND(checker1, checker2)(mockArgs)\n\n expect(result).toBe(false)\n })\n })\n\n describe('conditional', () => {\n it('should apply checker when condition is true', async () => {\n const checker: Access = async () => true\n\n const result = await conditional(true, checker)(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should return false when condition is false', async () => {\n const checker: Access = async () => true\n\n const result = await conditional(false, checker)(mockArgs)\n\n expect(result).toBe(false)\n })\n\n it('should apply checker when condition function returns true', async () => {\n const condition = ({ req }: AccessArgs) => !!req.user\n const checker: Access = async () => true\n\n const result = await conditional(condition, checker)(mockArgsWithUser)\n\n expect(result).toBe(true)\n })\n\n it('should return false when condition function returns false', async () => {\n const condition = ({ req }: AccessArgs) => !!req.user\n const checker: Access = async () => true\n\n const result = await conditional(condition, checker)(mockArgs)\n\n expect(result).toBe(false)\n })\n\n it('should pass Where query through when condition is true', async () => {\n const checker: Access = async () => ({\n customer: { equals: '123' },\n })\n\n const result = await conditional(true, checker)(mockArgs)\n\n expect(result).toEqual({\n customer: { equals: '123' },\n })\n })\n\n it('should not call checker when condition is false', async () => {\n let checkerCalled = false\n\n const checker: Access = async () => {\n checkerCalled = true\n return true\n }\n\n await conditional(false, checker)(mockArgs)\n\n expect(checkerCalled).toBe(false)\n })\n\n it('should evaluate condition function each time', async () => {\n const condition = ({ req }: AccessArgs) => !!req.user\n const checker: Access = async () => true\n\n // First call without user\n const result1 = await conditional(condition, checker)(mockArgs)\n expect(result1).toBe(false)\n\n // Second call with user\n const result2 = await conditional(condition, checker)(mockArgsWithUser)\n expect(result2).toBe(true)\n })\n\n it('should work with false checker result when condition is true', async () => {\n const checker: Access = async () => false\n\n const result = await conditional(true, checker)(mockArgs)\n\n expect(result).toBe(false)\n })\n })\n\n describe('combined composition', () => {\n it('should compose or, and, and conditional together', async () => {\n const isAdmin: Access = async ({ req }) => req.user?.role === 'admin'\n const isOwner: Access = async ({ req }) => ({\n customer: { equals: req.user?.id },\n })\n const isGuest: Access = async ({ req }) => !req.user\n\n const allowGuestCarts = true\n\n const access = accessOR(isAdmin, accessAND(isOwner), conditional(allowGuestCarts, isGuest))\n\n // Guest user (no user)\n const guestResult = await access(mockArgs)\n expect(guestResult).toBe(true)\n\n // Admin user\n const adminResult = await access({\n req: {\n user: { id: '123', role: 'admin' },\n headers: new Headers(),\n payload: {} as any,\n context: {},\n } as any,\n })\n expect(adminResult).toBe(true)\n\n // Regular user (owner)\n const ownerResult = await access({\n req: {\n user: { id: '123', role: 'customer' },\n headers: new Headers(),\n payload: {} as any,\n context: {},\n } as any,\n })\n expect(ownerResult).toEqual({\n or: [{ and: [{ customer: { equals: '123' } }] }],\n })\n })\n\n it('should handle complex nested compositions', async () => {\n const checker1: Access = async () => ({\n status: { equals: 'published' },\n })\n const checker2: Access = async () => ({\n visibility: { equals: 'public' },\n })\n const checker3: Access = async ({ req }) => !!req.user\n const checker4: Access = async () => ({\n customer: { equals: '123' },\n })\n\n // ((published AND public) OR (authenticated AND customer=123))\n const access = accessOR(accessAND(checker1, checker2), accessAND(checker3, checker4))\n\n // Without user\n const result1 = await access(mockArgs)\n expect(result1).toEqual({\n or: [\n {\n and: [{ status: { equals: 'published' } }, { visibility: { equals: 'public' } }],\n },\n ],\n })\n\n // With user\n const result2 = await access(mockArgsWithUser)\n expect(result2).toEqual({\n or: [\n {\n and: [{ status: { equals: 'published' } }, { visibility: { equals: 'public' } }],\n },\n {\n and: [{ customer: { equals: '123' } }],\n },\n ],\n })\n })\n\n it('should handle conditional inside or composition', async () => {\n const isAdmin: Access = async () => false\n const isGuest: Access = async () => true\n const allowGuestAccess = true\n\n const access = accessOR(isAdmin, conditional(allowGuestAccess, isGuest))\n\n const result = await access(mockArgs)\n expect(result).toBe(true)\n })\n\n it('should handle conditional inside and composition', async () => {\n const hasPermission: Access = async () => ({\n permissions: { contains: 'read' },\n })\n const isActiveUser: Access = async () => true\n const featureFlagEnabled = true\n\n const access = accessAND(hasPermission, conditional(featureFlagEnabled, isActiveUser))\n\n const result = await access(mockArgs)\n expect(result).toEqual({\n and: [{ permissions: { contains: 'read' } }],\n })\n })\n\n it('should correctly handle multiple levels of nesting', async () => {\n const a: Access = async () => true\n const b: Access = async () => false\n const c: Access = async () => ({ field1: { equals: 'value1' } })\n const d: Access = async () => ({ field2: { equals: 'value2' } })\n\n // (a AND (b OR (c AND d)))\n const access = accessAND(a, accessOR(b, accessAND(c, d)))\n\n const result = await access(mockArgs)\n expect(result).toEqual({\n and: [\n { or: [{ and: [{ field1: { equals: 'value1' } }, { field2: { equals: 'value2' } }] }] },\n ],\n })\n })\n })\n\n describe('edge cases and failure scenarios', () => {\n it('should handle checker that throws an error', async () => {\n const checker1: Access = async () => {\n throw new Error('Access check failed')\n }\n const checker2: Access = async () => true\n\n await expect(accessOR(checker1, checker2)(mockArgs)).rejects.toThrow('Access check failed')\n })\n\n it('should handle null or undefined returns gracefully', async () => {\n const checker1: Access = async () => null as any\n const checker2: Access = async () => undefined as any\n const checker3: Access = async () => true\n\n const result = await accessOR(checker1, checker2, checker3)(mockArgs)\n expect(result).toBe(true)\n })\n\n it('should handle deeply nested Where queries', async () => {\n const checker: Access = async () =>\n ({\n and: [\n {\n or: [\n { field1: { equals: 'value1' } },\n {\n and: [{ field2: { equals: 'value2' } }, { field3: { equals: 'value3' } }],\n },\n ],\n },\n { field4: { not_equals: 'value4' } },\n ],\n }) as Where\n\n const result = await accessOR(checker)(mockArgs)\n\n expect(result).toEqual({\n or: [\n {\n and: [\n {\n or: [\n { field1: { equals: 'value1' } },\n {\n and: [{ field2: { equals: 'value2' } }, { field3: { equals: 'value3' } }],\n },\n ],\n },\n { field4: { not_equals: 'value4' } },\n ],\n },\n ],\n })\n })\n\n it('should handle async checker that takes time', async () => {\n const checker1: Access = async () => {\n await new Promise((resolve) => setTimeout(resolve, 10))\n return false\n }\n const checker2: Access = async () => {\n await new Promise((resolve) => setTimeout(resolve, 10))\n return true\n }\n\n const start = Date.now()\n const result = await accessOR(checker1, checker2)(mockArgs)\n const duration = Date.now() - start\n\n expect(result).toBe(true)\n expect(duration).toBeGreaterThanOrEqual(20)\n })\n\n it('should handle all checkers returning null/undefined', async () => {\n const checker1: Access = async () => null as any\n const checker2: Access = async () => undefined as any\n\n const result = await accessOR(checker1, checker2)(mockArgs)\n\n // null and undefined should be treated as false\n expect(result).toBe(false)\n })\n\n it('should handle Where query with empty object', async () => {\n const checker: Access = async () => ({}) as Where\n\n const result = await accessOR(checker)(mockArgs)\n\n expect(result).toEqual({})\n })\n\n it('should handle conditional with complex condition function', async () => {\n const condition = ({ req }: AccessArgs): boolean => {\n return !!(req.user && req.user.email && req.user.email.endsWith('@admin.com'))\n }\n\n const checker: Access = async () => true\n\n // Non-admin email\n const result1 = await conditional(\n condition,\n checker,\n )({\n req: {\n user: { id: '123', email: 'user@example.com' },\n headers: new Headers(),\n payload: {} as any,\n context: {},\n } as any,\n })\n expect(result1).toBe(false)\n\n // Admin email\n const result2 = await conditional(\n condition,\n checker,\n )({\n req: {\n user: { id: '123', email: 'admin@admin.com' },\n headers: new Headers(),\n payload: {} as any,\n context: {},\n } as any,\n })\n expect(result2).toBe(true)\n })\n\n it('should handle very large number of checkers in or', async () => {\n const checkers: Access[] = Array.from({ length: 100 }, (_, i) => async () => ({\n field: { equals: `value${i}` },\n }))\n\n const result = await accessOR(...checkers)(mockArgs)\n\n expect(result).toHaveProperty('or')\n expect((result as any).or).toHaveLength(100)\n })\n\n it('should handle very large number of checkers in and', async () => {\n const checkers: Access[] = Array.from({ length: 100 }, (_, i) => async () => ({\n field: { equals: `value${i}` },\n }))\n\n const result = await accessAND(...checkers)(mockArgs)\n\n expect(result).toHaveProperty('and')\n expect((result as any).and).toHaveLength(100)\n })\n\n it('should handle alternating true/false in or correctly', async () => {\n const checkers: Access[] = [\n async () => false,\n async () => false,\n async () => false,\n async () => true, // This should cause short-circuit\n async () => {\n throw new Error('Should not be called')\n },\n ]\n\n const result = await accessOR(...checkers)(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should handle alternating true/false in and correctly', async () => {\n const checkers: Access[] = [\n async () => true,\n async () => true,\n async () => false, // This should cause short-circuit\n async () => {\n throw new Error('Should not be called')\n },\n ]\n\n const result = await accessAND(...checkers)(mockArgs)\n\n expect(result).toBe(false)\n })\n })\n})\n"],"names":["accessAND","conditional","accessOR","mockArgs","req","user","headers","Headers","payload","context","mockArgsWithUser","id","email","describe","it","checker1","checker2","result","expect","toBe","checker3","customer","equals","status","toEqual","or","checker4","secondCheckerCalled","and","role","Error","checker","condition","checkerCalled","result1","result2","isAdmin","isOwner","isGuest","allowGuestCarts","access","guestResult","adminResult","ownerResult","visibility","allowGuestAccess","hasPermission","permissions","contains","isActiveUser","featureFlagEnabled","a","b","c","field1","d","field2","rejects","toThrow","undefined","field3","field4","not_equals","Promise","resolve","setTimeout","start","Date","now","duration","toBeGreaterThanOrEqual","endsWith","checkers","Array","from","length","_","i","field","toHaveProperty","toHaveLength"],"mappings":"AAEA,SAASA,SAAS,EAAEC,WAAW,EAAEC,QAAQ,QAAQ,sBAAqB;AAEtE,+BAA+B;AAC/B,MAAMC,WAAuB;IAC3BC,KAAK;QACHC,MAAM;QACNC,SAAS,IAAIC;QACbC,SAAS,CAAC;QACVC,SAAS,CAAC;IACZ;AACF;AAEA,MAAMC,mBAA+B;IACnCN,KAAK;QACHC,MAAM;YAAEM,IAAI;YAAOC,OAAO;QAAmB;QAC7CN,SAAS,IAAIC;QACbC,SAAS,CAAC;QACVC,SAAS,CAAC;IACZ;AACF;AAEAI,SAAS,gCAAgC;IACvCA,SAAS,MAAM;QACbC,GAAG,sDAAsD;YACvD,MAAMC,WAAmB,UAAY;YACrC,MAAMC,WAAmB,UAAY;YAErC,MAAMC,SAAS,MAAMf,SAASa,UAAUC,UAAUb;YAElDe,OAAOD,QAAQE,IAAI,CAAC;QACtB;QAEAL,GAAG,oDAAoD;YACrD,MAAMC,WAAmB,UAAY;YACrC,MAAMC,WAAmB,UAAY;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AAI,CAAC;gBAAEC,QAAQ;YAAI,GAAG,CAACC,GAAGC,IAAM,UAAa,CAAA;wBAC5EC,OAAO;4BAAExD,QAAQ,CAAC,KAAK,EAAEuD,GAAG;wBAAC;oBAC/B,CAAA;YAEA,MAAM5D,SAAS,MAAMjB,aAAawE,UAAUrE;YAE5Ce,OAAOD,QAAQ8D,cAAc,CAAC;YAC9B7D,OAAO,AAACD,OAAeW,GAAG,EAAEoD,YAAY,CAAC;QAC3C;QAEAlE,GAAG,wDAAwD;YACzD,MAAM0D,WAAqB;gBACzB,UAAY;gBACZ,UAAY;gBACZ,UAAY;gBACZ,UAAY;gBACZ;oBACE,MAAM,IAAI1C,MAAM;gBAClB;aACD;YAED,MAAMb,SAAS,MAAMf,YAAYsE,UAAUrE;YAE3Ce,OAAOD,QAAQE,IAAI,CAAC;QACtB;QAEAL,GAAG,yDAAyD;YAC1D,MAAM0D,WAAqB;gBACzB,UAAY;gBACZ,UAAY;gBACZ,UAAY;gBACZ;oBACE,MAAM,IAAI1C,MAAM;gBAClB;aACD;YAED,MAAMb,SAAS,MAAMjB,aAAawE,UAAUrE;YAE5Ce,OAAOD,QAAQE,IAAI,CAAC;QACtB;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/utilities/accessComposition.spec.ts"],"sourcesContent":["import { describe, it, expect } from 'vitest'\nimport type { Access, AccessArgs, Where } from 'payload'\n\nimport { accessAND, conditional, accessOR } from './accessComposition'\n\n// Mock access args for testing\nconst mockArgs: AccessArgs = {\n req: {\n user: null,\n headers: new Headers(),\n payload: {} as any,\n context: {},\n } as any,\n}\n\nconst mockArgsWithUser: AccessArgs = {\n req: {\n user: { id: '123', email: 'test@example.com' },\n headers: new Headers(),\n payload: {} as any,\n context: {},\n } as any,\n}\n\ndescribe('Access Composition Utilities', () => {\n describe('or', () => {\n it('should return true when first checker returns true', async () => {\n const checker1: Access = async () => true\n const checker2: Access = async () => false\n\n const result = await accessOR(checker1, checker2)(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should return true when any checker returns true', async () => {\n const checker1: Access = async () => false\n const checker2: Access = async () => true\n const checker3: Access = async () => false\n\n const result = await accessOR(checker1, checker2, checker3)(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should return false when all checkers return false', async () => {\n const checker1: Access = async () => false\n const checker2: Access = async () => false\n const checker3: Access = async () => false\n\n const result = await accessOR(checker1, checker2, checker3)(mockArgs)\n\n expect(result).toBe(false)\n })\n\n it('should combine Where queries with OR logic', async () => {\n const checker1: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker2: Access = async () => ({\n status: { equals: 'published' },\n })\n\n const result = await accessOR(checker1, checker2)(mockArgs)\n\n expect(result).toEqual({\n or: [{ customer: { equals: '123' } }, { status: { equals: 'published' } }],\n })\n })\n\n it('should return true when one checker returns true and others return Where queries', async () => {\n const checker1: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker2: Access = async () => true\n\n const result = await accessOR(checker1, checker2)(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should ignore false values when combining Where queries', async () => {\n const checker1: Access = async () => false\n const checker2: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker3: Access = async () => false\n const checker4: Access = async () => ({\n status: { equals: 'published' },\n })\n\n const result = await accessOR(checker1, checker2, checker3, checker4)(mockArgs)\n\n expect(result).toEqual({\n or: [{ customer: { equals: '123' } }, { status: { equals: 'published' } }],\n })\n })\n\n it('should return a single Where query when only one checker returns a Where query', async () => {\n const checker1: Access = async () => false\n const checker2: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker3: Access = async () => false\n\n const result = await accessOR(checker1, checker2, checker3)(mockArgs)\n\n expect(result).toEqual({\n or: [{ customer: { equals: '123' } }],\n })\n })\n\n it('should short-circuit on first true result for performance', async () => {\n let secondCheckerCalled = false\n\n const checker1: Access = async () => true\n const checker2: Access = async () => {\n secondCheckerCalled = true\n return false\n }\n\n await accessOR(checker1, checker2)(mockArgs)\n\n expect(secondCheckerCalled).toBe(false)\n })\n\n it('should handle empty checkers array', async () => {\n const result = await accessOR()(mockArgs)\n\n expect(result).toBe(false)\n })\n\n it('should handle complex nested Where queries', async () => {\n const checker1: Access = async () =>\n ({\n and: [{ customer: { equals: '123' } }, { status: { equals: 'active' } }],\n }) as Where\n const checker2: Access = async () => ({\n role: { equals: 'admin' },\n })\n\n const result = await accessOR(checker1, checker2)(mockArgs)\n\n expect(result).toEqual({\n or: [\n { and: [{ customer: { equals: '123' } }, { status: { equals: 'active' } }] },\n { role: { equals: 'admin' } },\n ],\n })\n })\n })\n\n describe('and', () => {\n it('should return false when any checker returns false', async () => {\n const checker1: Access = async () => true\n const checker2: Access = async () => false\n\n const result = await accessAND(checker1, checker2)(mockArgs)\n\n expect(result).toBe(false)\n })\n\n it('should return true when all checkers return true', async () => {\n const checker1: Access = async () => true\n const checker2: Access = async () => true\n const checker3: Access = async () => true\n\n const result = await accessAND(checker1, checker2, checker3)(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should combine Where queries with AND logic', async () => {\n const checker1: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker2: Access = async () => ({\n status: { equals: 'published' },\n })\n\n const result = await accessAND(checker1, checker2)(mockArgs)\n\n expect(result).toEqual({\n and: [{ customer: { equals: '123' } }, { status: { equals: 'published' } }],\n })\n })\n\n it('should return false when one checker returns false and others return Where queries', async () => {\n const checker1: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker2: Access = async () => false\n\n const result = await accessAND(checker1, checker2)(mockArgs)\n\n expect(result).toBe(false)\n })\n\n it('should return Where query when all checkers return Where queries except one returns true', async () => {\n const checker1: Access = async () => true\n const checker2: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker3: Access = async () => ({\n status: { equals: 'published' },\n })\n\n const result = await accessAND(checker1, checker2, checker3)(mockArgs)\n\n expect(result).toEqual({\n and: [{ customer: { equals: '123' } }, { status: { equals: 'published' } }],\n })\n })\n\n it('should short-circuit on first false result for performance', async () => {\n let secondCheckerCalled = false\n\n const checker1: Access = async () => false\n const checker2: Access = async () => {\n secondCheckerCalled = true\n return true\n }\n\n await accessAND(checker1, checker2)(mockArgs)\n\n expect(secondCheckerCalled).toBe(false)\n })\n\n it('should handle empty checkers array', async () => {\n const result = await accessAND()(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should return a single Where query when only one checker returns a Where query', async () => {\n const checker1: Access = async () => true\n const checker2: Access = async () => ({\n customer: { equals: '123' },\n })\n const checker3: Access = async () => true\n\n const result = await accessAND(checker1, checker2, checker3)(mockArgs)\n\n expect(result).toEqual({\n and: [{ customer: { equals: '123' } }],\n })\n })\n\n it('should handle complex nested Where queries', async () => {\n const checker1: Access = async () => ({\n or: [{ customer: { equals: '123' } }, { customer: { equals: '456' } }],\n })\n const checker2: Access = async () => ({\n status: { equals: 'active' },\n })\n\n const result = await accessAND(checker1, checker2)(mockArgs)\n\n expect(result).toEqual({\n and: [\n { or: [{ customer: { equals: '123' } }, { customer: { equals: '456' } }] },\n { status: { equals: 'active' } },\n ],\n })\n })\n\n it('should return false immediately when first checker returns false', async () => {\n const checker1: Access = async () => false\n const checker2: Access = async () => {\n throw new Error('Should not be called')\n }\n\n const result = await accessAND(checker1, checker2)(mockArgs)\n\n expect(result).toBe(false)\n })\n })\n\n describe('conditional', () => {\n it('should apply checker when condition is true', async () => {\n const checker: Access = async () => true\n\n const result = await conditional(true, checker)(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should return false when condition is false', async () => {\n const checker: Access = async () => true\n\n const result = await conditional(false, checker)(mockArgs)\n\n expect(result).toBe(false)\n })\n\n it('should apply checker when condition function returns true', async () => {\n const condition = ({ req }: AccessArgs) => !!req.user\n const checker: Access = async () => true\n\n const result = await conditional(condition, checker)(mockArgsWithUser)\n\n expect(result).toBe(true)\n })\n\n it('should return false when condition function returns false', async () => {\n const condition = ({ req }: AccessArgs) => !!req.user\n const checker: Access = async () => true\n\n const result = await conditional(condition, checker)(mockArgs)\n\n expect(result).toBe(false)\n })\n\n it('should pass Where query through when condition is true', async () => {\n const checker: Access = async () => ({\n customer: { equals: '123' },\n })\n\n const result = await conditional(true, checker)(mockArgs)\n\n expect(result).toEqual({\n customer: { equals: '123' },\n })\n })\n\n it('should not call checker when condition is false', async () => {\n let checkerCalled = false\n\n const checker: Access = async () => {\n checkerCalled = true\n return true\n }\n\n await conditional(false, checker)(mockArgs)\n\n expect(checkerCalled).toBe(false)\n })\n\n it('should evaluate condition function each time', async () => {\n const condition = ({ req }: AccessArgs) => !!req.user\n const checker: Access = async () => true\n\n // First call without user\n const result1 = await conditional(condition, checker)(mockArgs)\n expect(result1).toBe(false)\n\n // Second call with user\n const result2 = await conditional(condition, checker)(mockArgsWithUser)\n expect(result2).toBe(true)\n })\n\n it('should work with false checker result when condition is true', async () => {\n const checker: Access = async () => false\n\n const result = await conditional(true, checker)(mockArgs)\n\n expect(result).toBe(false)\n })\n })\n\n describe('combined composition', () => {\n it('should compose or, and, and conditional together', async () => {\n const isAdmin: Access = async ({ req }) => req.user?.role === 'admin'\n const isOwner: Access = async ({ req }) => ({\n customer: { equals: req.user?.id },\n })\n const isGuest: Access = async ({ req }) => !req.user\n\n const allowGuestCarts = true\n\n const access = accessOR(isAdmin, accessAND(isOwner), conditional(allowGuestCarts, isGuest))\n\n // Guest user (no user)\n const guestResult = await access(mockArgs)\n expect(guestResult).toBe(true)\n\n // Admin user\n const adminResult = await access({\n req: {\n user: { id: '123', role: 'admin' },\n headers: new Headers(),\n payload: {} as any,\n context: {},\n } as any,\n })\n expect(adminResult).toBe(true)\n\n // Regular user (owner)\n const ownerResult = await access({\n req: {\n user: { id: '123', role: 'customer' },\n headers: new Headers(),\n payload: {} as any,\n context: {},\n } as any,\n })\n expect(ownerResult).toEqual({\n or: [{ and: [{ customer: { equals: '123' } }] }],\n })\n })\n\n it('should handle complex nested compositions', async () => {\n const checker1: Access = async () => ({\n status: { equals: 'published' },\n })\n const checker2: Access = async () => ({\n visibility: { equals: 'public' },\n })\n const checker3: Access = async ({ req }) => !!req.user\n const checker4: Access = async () => ({\n customer: { equals: '123' },\n })\n\n // ((published AND public) OR (authenticated AND customer=123))\n const access = accessOR(accessAND(checker1, checker2), accessAND(checker3, checker4))\n\n // Without user\n const result1 = await access(mockArgs)\n expect(result1).toEqual({\n or: [\n {\n and: [{ status: { equals: 'published' } }, { visibility: { equals: 'public' } }],\n },\n ],\n })\n\n // With user\n const result2 = await access(mockArgsWithUser)\n expect(result2).toEqual({\n or: [\n {\n and: [{ status: { equals: 'published' } }, { visibility: { equals: 'public' } }],\n },\n {\n and: [{ customer: { equals: '123' } }],\n },\n ],\n })\n })\n\n it('should handle conditional inside or composition', async () => {\n const isAdmin: Access = async () => false\n const isGuest: Access = async () => true\n const allowGuestAccess = true\n\n const access = accessOR(isAdmin, conditional(allowGuestAccess, isGuest))\n\n const result = await access(mockArgs)\n expect(result).toBe(true)\n })\n\n it('should handle conditional inside and composition', async () => {\n const hasPermission: Access = async () => ({\n permissions: { contains: 'read' },\n })\n const isActiveUser: Access = async () => true\n const featureFlagEnabled = true\n\n const access = accessAND(hasPermission, conditional(featureFlagEnabled, isActiveUser))\n\n const result = await access(mockArgs)\n expect(result).toEqual({\n and: [{ permissions: { contains: 'read' } }],\n })\n })\n\n it('should correctly handle multiple levels of nesting', async () => {\n const a: Access = async () => true\n const b: Access = async () => false\n const c: Access = async () => ({ field1: { equals: 'value1' } })\n const d: Access = async () => ({ field2: { equals: 'value2' } })\n\n // (a AND (b OR (c AND d)))\n const access = accessAND(a, accessOR(b, accessAND(c, d)))\n\n const result = await access(mockArgs)\n expect(result).toEqual({\n and: [\n { or: [{ and: [{ field1: { equals: 'value1' } }, { field2: { equals: 'value2' } }] }] },\n ],\n })\n })\n })\n\n describe('edge cases and failure scenarios', () => {\n it('should handle checker that throws an error', async () => {\n const checker1: Access = async () => {\n throw new Error('Access check failed')\n }\n const checker2: Access = async () => true\n\n await expect(accessOR(checker1, checker2)(mockArgs)).rejects.toThrow('Access check failed')\n })\n\n it('should handle null or undefined returns gracefully', async () => {\n const checker1: Access = async () => null as any\n const checker2: Access = async () => undefined as any\n const checker3: Access = async () => true\n\n const result = await accessOR(checker1, checker2, checker3)(mockArgs)\n expect(result).toBe(true)\n })\n\n it('should handle deeply nested Where queries', async () => {\n const checker: Access = async () =>\n ({\n and: [\n {\n or: [\n { field1: { equals: 'value1' } },\n {\n and: [{ field2: { equals: 'value2' } }, { field3: { equals: 'value3' } }],\n },\n ],\n },\n { field4: { not_equals: 'value4' } },\n ],\n }) as Where\n\n const result = await accessOR(checker)(mockArgs)\n\n expect(result).toEqual({\n or: [\n {\n and: [\n {\n or: [\n { field1: { equals: 'value1' } },\n {\n and: [{ field2: { equals: 'value2' } }, { field3: { equals: 'value3' } }],\n },\n ],\n },\n { field4: { not_equals: 'value4' } },\n ],\n },\n ],\n })\n })\n\n it('should handle async checker that takes time', async () => {\n const checker1: Access = async () => {\n await new Promise((resolve) => setTimeout(resolve, 10))\n return false\n }\n const checker2: Access = async () => {\n await new Promise((resolve) => setTimeout(resolve, 10))\n return true\n }\n\n const start = Date.now()\n const result = await accessOR(checker1, checker2)(mockArgs)\n const duration = Date.now() - start\n\n expect(result).toBe(true)\n expect(duration).toBeGreaterThanOrEqual(20)\n })\n\n it('should handle all checkers returning null/undefined', async () => {\n const checker1: Access = async () => null as any\n const checker2: Access = async () => undefined as any\n\n const result = await accessOR(checker1, checker2)(mockArgs)\n\n // null and undefined should be treated as false\n expect(result).toBe(false)\n })\n\n it('should handle Where query with empty object', async () => {\n const checker: Access = async () => ({}) as Where\n\n const result = await accessOR(checker)(mockArgs)\n\n expect(result).toEqual({})\n })\n\n it('should handle conditional with complex condition function', async () => {\n const condition = ({ req }: AccessArgs): boolean => {\n return !!(req.user && req.user.email && req.user.email.endsWith('@admin.com'))\n }\n\n const checker: Access = async () => true\n\n // Non-admin email\n const result1 = await conditional(\n condition,\n checker,\n )({\n req: {\n user: { id: '123', email: 'user@example.com' },\n headers: new Headers(),\n payload: {} as any,\n context: {},\n } as any,\n })\n expect(result1).toBe(false)\n\n // Admin email\n const result2 = await conditional(\n condition,\n checker,\n )({\n req: {\n user: { id: '123', email: 'admin@admin.com' },\n headers: new Headers(),\n payload: {} as any,\n context: {},\n } as any,\n })\n expect(result2).toBe(true)\n })\n\n it('should handle very large number of checkers in or', async () => {\n const checkers: Access[] = Array.from({ length: 100 }, (_, i) => async () => ({\n field: { equals: `value${i}` },\n }))\n\n const result = await accessOR(...checkers)(mockArgs)\n\n expect(result).toHaveProperty('or')\n expect((result as any).or).toHaveLength(100)\n })\n\n it('should handle very large number of checkers in and', async () => {\n const checkers: Access[] = Array.from({ length: 100 }, (_, i) => async () => ({\n field: { equals: `value${i}` },\n }))\n\n const result = await accessAND(...checkers)(mockArgs)\n\n expect(result).toHaveProperty('and')\n expect((result as any).and).toHaveLength(100)\n })\n\n it('should handle alternating true/false in or correctly', async () => {\n const checkers: Access[] = [\n async () => false,\n async () => false,\n async () => false,\n async () => true, // This should cause short-circuit\n async () => {\n throw new Error('Should not be called')\n },\n ]\n\n const result = await accessOR(...checkers)(mockArgs)\n\n expect(result).toBe(true)\n })\n\n it('should handle alternating true/false in and correctly', async () => {\n const checkers: Access[] = [\n async () => true,\n async () => true,\n async () => false, // This should cause short-circuit\n async () => {\n throw new Error('Should not be called')\n },\n ]\n\n const result = await accessAND(...checkers)(mockArgs)\n\n expect(result).toBe(false)\n })\n })\n})\n"],"names":["describe","it","expect","accessAND","conditional","accessOR","mockArgs","req","user","headers","Headers","payload","context","mockArgsWithUser","id","email","checker1","checker2","result","toBe","checker3","customer","equals","status","toEqual","or","checker4","secondCheckerCalled","and","role","Error","checker","condition","checkerCalled","result1","result2","isAdmin","isOwner","isGuest","allowGuestCarts","access","guestResult","adminResult","ownerResult","visibility","allowGuestAccess","hasPermission","permissions","contains","isActiveUser","featureFlagEnabled","a","b","c","field1","d","field2","rejects","toThrow","undefined","field3","field4","not_equals","Promise","resolve","setTimeout","start","Date","now","duration","toBeGreaterThanOrEqual","endsWith","checkers","Array","from","length","_","i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gBAClB;aACD;YAED,MAAMZ,SAAS,MAAMb,YAAYmE,UAAUlE;YAE3CJ,OAAOgB,QAAQC,IAAI,CAAC;QACtB;QAEAlB,GAAG,yDAAyD;YAC1D,MAAMuE,WAAqB;gBACzB,UAAY;gBACZ,UAAY;gBACZ,UAAY;gBACZ;oBACE,MAAM,IAAI1C,MAAM;gBAClB;aACD;YAED,MAAMZ,SAAS,MAAMf,aAAaqE,UAAUlE;YAE5CJ,OAAOgB,QAAQC,IAAI,CAAC;QACtB;IACF;AACF"}
@@ -1,3 +1,4 @@
1
+ import { describe, it, expect } from 'vitest';
1
2
  import { EUR, USD } from '../currencies/index.js';
2
3
  import { defaultProductsValidation } from './defaultProductsValidation';
3
4
  import { MissingPrice, OutOfStock } from './errorCodes';
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/defaultProductsValidation.spec.ts"],"sourcesContent":["import type { CurrenciesConfig } from '../types/index.js'\n\nimport { EUR, USD } from '../currencies/index.js'\nimport { defaultProductsValidation } from './defaultProductsValidation'\nimport { MissingPrice, OutOfStock } from './errorCodes'\n\ndescribe('defaultProductsValidation', () => {\n const currenciesConfig: CurrenciesConfig = {\n defaultCurrency: 'USD',\n supportedCurrencies: [USD, EUR],\n }\n\n describe('currency validation', () => {\n it('should throw error when currency is not provided', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: '',\n product: product as any,\n quantity: 1,\n })\n }).toThrow('Currency must be provided for product validation.')\n })\n\n it('should throw error when currency is undefined', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: undefined as any,\n product: product as any,\n quantity: 1,\n })\n }).toThrow('Currency must be provided for product validation.')\n })\n })\n\n describe('variant validation', () => {\n it('should validate variant price exists', () => {\n const variant = {\n id: 'variant-1',\n priceInEUR: 900,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 1,\n variant: variant as any,\n })\n }).toThrow('Variant with ID variant-1 does not have a price in usd.')\n })\n\n it('should pass when variant has price in requested currency', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 1,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n\n it('should handle case-insensitive currency codes', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'USD',\n product: {} as any,\n quantity: 1,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n\n it('should throw error when variant inventory is 0', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 0,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 1,\n variant: variant as any,\n })\n }).toThrow('Variant with ID variant-1 is out of stock or does not have enough inventory.')\n })\n\n it('should throw error when variant inventory is less than quantity', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 5,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 10,\n variant: variant as any,\n })\n }).toThrow('Variant with ID variant-1 is out of stock or does not have enough inventory.')\n })\n\n it('should pass when variant inventory equals quantity', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 5,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 5,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n\n it('should pass when variant inventory is greater than quantity', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 5,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n\n it('should pass when variant has no inventory field (unlimited stock)', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 100,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n })\n\n describe('product validation', () => {\n it('should validate product price exists', () => {\n const product = {\n id: 'product-1',\n priceInEUR: 900,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n })\n }).toThrow('Product does not have a price in.')\n })\n\n it('should include error cause with MissingPrice code', () => {\n const product = {\n id: 'product-1',\n priceInEUR: 900,\n inventory: 10,\n }\n\n try {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n })\n } catch (error: any) {\n expect(error.cause).toEqual({\n code: MissingPrice,\n codes: ['product-1', 'usd'],\n })\n }\n })\n\n it('should pass when product has price in requested currency', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n })\n }).not.toThrow()\n })\n\n it('should throw error when product inventory is 0', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 0,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n })\n }).toThrow('Product is out of stock or does not have enough inventory.')\n })\n\n it('should include error cause with OutOfStock code', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 0,\n }\n\n try {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n })\n } catch (error: any) {\n expect(error.cause).toEqual({\n code: OutOfStock,\n codes: ['product-1'],\n })\n }\n })\n\n it('should throw error when product inventory is less than quantity', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 5,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 10,\n })\n }).toThrow('Product is out of stock or does not have enough inventory.')\n })\n\n it('should pass when product inventory equals quantity', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 5,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 5,\n })\n }).not.toThrow()\n })\n\n it('should pass when product inventory is greater than quantity', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 5,\n })\n }).not.toThrow()\n })\n\n it('should pass when product has no inventory field (unlimited stock)', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 100,\n })\n }).not.toThrow()\n })\n\n it('should default quantity to 1 when not provided', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 1,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n })\n }).not.toThrow()\n })\n })\n\n describe('variant priority over product', () => {\n it('should only validate variant when both product and variant are provided', () => {\n const product = {\n id: 'product-1',\n priceInEUR: 900, // Missing USD price\n inventory: 0, // Out of stock\n }\n\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 10,\n }\n\n // Should not throw because variant validation takes priority\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n\n it('should not validate product inventory when variant is provided', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 0, // Product out of stock\n }\n\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 10, // But variant has stock\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n })\n})\n"],"names":["EUR","USD","defaultProductsValidation","MissingPrice","OutOfStock","describe","currenciesConfig","defaultCurrency","supportedCurrencies","it","product","id","priceInUSD","expect","currency","quantity","toThrow","undefined","variant","priceInEUR","inventory","not","error","cause","toEqual","code","codes"],"mappings":"AAEA,SAASA,GAAG,EAAEC,GAAG,QAAQ,yBAAwB;AACjD,SAASC,yBAAyB,QAAQ,8BAA6B;AACvE,SAASC,YAAY,EAAEC,UAAU,QAAQ,eAAc;AAEvDC,SAAS,6BAA6B;IACpC,MAAMC,mBAAqC;QACzCC,iBAAiB;QACjBC,qBAAqB;YAACP;YAAKD;SAAI;IACjC;IAEAK,SAAS,uBAAuB;QAC9BI,GAAG,oDAAoD;YACrD,MAAMC,UAAU;gBACdC,IAAI;gBACJC,YAAY;YACd;YAEAC,OAAO;gBACLX,0BAA0B;oBACxBI;oBACAQ,UAAU;oBACVJ,SAASA;oBACTK,UAAU;gBACZ;YACF,GAAGC,OAAO,CAAC;QACb;QAEAP,GAAG,iDAAiD;YAClD,MAAMC,UAAU;gBACdC,IAAI;gBACJC,YAAY;YACd;YAEAC,OAAO;gBACLX,0BAA0B;oBACxBI;oBACAQ,UAAUG;oBACVP,SAASA;oBACTK,UAAU;gBACZ;YACF,GAAGC,OAAO,CAAC;QACb;IACF;IAEAX,SAAS,sBAAsB;QAC7BI,GAAG,wCAAwC;YACzC,MAAMS,UAAU;gBACdP,IAAI;gBACJQ,YAAY;gBACZC,WAAW;YACb;YAEAP,OAAO;gBACLX,0BAA0B;oBACxBI;oBACAQ,UAAU;oBACVJ,SAAS,CAAC;oBACVK,UAAU;oBACVG,SAASA;gBACX;YACF,GAAGF,OAAO,CAAC;QACb;QAEAP,GAAG,4DAA4D;YAC7D,MAAMS,UAAU;g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AEAP,OAAO;gBACLX,0BAA0B;oBACxBI;oBACAQ,UAAU;oBACVJ,SAASA;gBACX;YACF,GAAGW,GAAG,CAACL,OAAO;QAChB;IACF;IAEAX,SAAS,iCAAiC;QACxCI,GAAG,2EAA2E;YAC5E,MAAMC,UAAU;gBACdC,IAAI;gBACJQ,YAAY;gBACZC,WAAW;YACb;YAEA,MAAMF,UAAU;gBACdP,IAAI;gBACJC,YAAY;gBACZQ,WAAW;YACb;YAEA,6DAA6D;YAC7DP,OAAO;gBACLX,0BAA0B;oBACxBI;oBACAQ,UAAU;oBACVJ,SAASA;oBACTK,UAAU;oBACVG,SAASA;gBACX;YACF,GAAGG,GAAG,CAACL,OAAO;QAChB;QAEAP,GAAG,kEAAkE;YACnE,MAAMC,UAAU;gBACdC,IAAI;gBACJC,YAAY;gBACZQ,WAAW;YACb;YAEA,MAAMF,UAAU;gBACdP,IAAI;gBACJC,YAAY;gBACZQ,WAAW;YACb;YAEAP,OAAO;gBACLX,0BAA0B;oBACxBI;oBACAQ,UAAU;oBACVJ,SAASA;oBACTK,UAAU;oBACVG,SAASA;gBACX;YACF,GAAGG,GAAG,CAACL,OAAO;QAChB;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/utilities/defaultProductsValidation.spec.ts"],"sourcesContent":["import { describe, it, expect } from 'vitest'\nimport type { CurrenciesConfig } from '../types/index.js'\n\nimport { EUR, USD } from '../currencies/index.js'\nimport { defaultProductsValidation } from './defaultProductsValidation'\nimport { MissingPrice, OutOfStock } from './errorCodes'\n\ndescribe('defaultProductsValidation', () => {\n const currenciesConfig: CurrenciesConfig = {\n defaultCurrency: 'USD',\n supportedCurrencies: [USD, EUR],\n }\n\n describe('currency validation', () => {\n it('should throw error when currency is not provided', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: '',\n product: product as any,\n quantity: 1,\n })\n }).toThrow('Currency must be provided for product validation.')\n })\n\n it('should throw error when currency is undefined', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: undefined as any,\n product: product as any,\n quantity: 1,\n })\n }).toThrow('Currency must be provided for product validation.')\n })\n })\n\n describe('variant validation', () => {\n it('should validate variant price exists', () => {\n const variant = {\n id: 'variant-1',\n priceInEUR: 900,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 1,\n variant: variant as any,\n })\n }).toThrow('Variant with ID variant-1 does not have a price in usd.')\n })\n\n it('should pass when variant has price in requested currency', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 1,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n\n it('should handle case-insensitive currency codes', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'USD',\n product: {} as any,\n quantity: 1,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n\n it('should throw error when variant inventory is 0', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 0,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 1,\n variant: variant as any,\n })\n }).toThrow('Variant with ID variant-1 is out of stock or does not have enough inventory.')\n })\n\n it('should throw error when variant inventory is less than quantity', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 5,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 10,\n variant: variant as any,\n })\n }).toThrow('Variant with ID variant-1 is out of stock or does not have enough inventory.')\n })\n\n it('should pass when variant inventory equals quantity', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 5,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 5,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n\n it('should pass when variant inventory is greater than quantity', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 5,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n\n it('should pass when variant has no inventory field (unlimited stock)', () => {\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: {} as any,\n quantity: 100,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n })\n\n describe('product validation', () => {\n it('should validate product price exists', () => {\n const product = {\n id: 'product-1',\n priceInEUR: 900,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n })\n }).toThrow('Product does not have a price in.')\n })\n\n it('should include error cause with MissingPrice code', () => {\n const product = {\n id: 'product-1',\n priceInEUR: 900,\n inventory: 10,\n }\n\n try {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n })\n } catch (error: any) {\n expect(error.cause).toEqual({\n code: MissingPrice,\n codes: ['product-1', 'usd'],\n })\n }\n })\n\n it('should pass when product has price in requested currency', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n })\n }).not.toThrow()\n })\n\n it('should throw error when product inventory is 0', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 0,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n })\n }).toThrow('Product is out of stock or does not have enough inventory.')\n })\n\n it('should include error cause with OutOfStock code', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 0,\n }\n\n try {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n })\n } catch (error: any) {\n expect(error.cause).toEqual({\n code: OutOfStock,\n codes: ['product-1'],\n })\n }\n })\n\n it('should throw error when product inventory is less than quantity', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 5,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 10,\n })\n }).toThrow('Product is out of stock or does not have enough inventory.')\n })\n\n it('should pass when product inventory equals quantity', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 5,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 5,\n })\n }).not.toThrow()\n })\n\n it('should pass when product inventory is greater than quantity', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 10,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 5,\n })\n }).not.toThrow()\n })\n\n it('should pass when product has no inventory field (unlimited stock)', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 100,\n })\n }).not.toThrow()\n })\n\n it('should default quantity to 1 when not provided', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 1,\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n })\n }).not.toThrow()\n })\n })\n\n describe('variant priority over product', () => {\n it('should only validate variant when both product and variant are provided', () => {\n const product = {\n id: 'product-1',\n priceInEUR: 900, // Missing USD price\n inventory: 0, // Out of stock\n }\n\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 10,\n }\n\n // Should not throw because variant validation takes priority\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n\n it('should not validate product inventory when variant is provided', () => {\n const product = {\n id: 'product-1',\n priceInUSD: 1000,\n inventory: 0, // Product out of stock\n }\n\n const variant = {\n id: 'variant-1',\n priceInUSD: 1000,\n inventory: 10, // But variant has stock\n }\n\n expect(() => {\n defaultProductsValidation({\n currenciesConfig,\n currency: 'usd',\n product: product as any,\n quantity: 1,\n variant: variant as any,\n })\n }).not.toThrow()\n })\n })\n})\n"],"names":["describe","it","expect","EUR","USD","defaultProductsValidation","MissingPrice","OutOfStock","currenciesConfig","defaultCurrency","supportedCurrencies","product","id","priceInUSD","currency","quantity","toThrow","undefined","variant","priceInEUR","inventory","not","error","cause","toEqual","code","codes"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,EAAE,EAAEC,MAAM,QAAQ,SAAQ;AAG7C,SAASC,GAAG,EAAEC,GAAG,QAAQ,yBAAwB;AACjD,SAASC,yBAAyB,QAAQ,8BAA6B;AACvE,SAASC,YAAY,EAAEC,UAAU,QAAQ,eAAc;AAEvDP,SAAS,6BAA6B;IACpC,MAAMQ,mBAAqC;QACzCC,iBAAiB;QACjBC,qBAAqB;YAACN;YAAKD;SAAI;IACjC;IAEAH,SAAS,uBAAuB;QAC9BC,GAAG,oDAAoD;YACrD,MAAMU,UAAU;gBACdC,IAAI;gBACJC,YAAY;YACd;YAEAX,OAAO;gBACLG,0BAA0B;oBACxBG;oBACAM,UAAU;oBACVH,SAASA;oBACTI,UAAU;gBACZ;YACF,GAAGC,OAAO,CAAC;QACb;QAEAf,GAAG,iDAAiD;YAClD,MAAMU,UAAU;gBACdC,IAAI;gBACJC,YAAY;YACd;YAEAX,OAAO;gBACLG,0BAA0B;oBACxBG;oBACAM,UAAUG;oBACVN,SAASA;oBACTI,UAAU;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CAACL,OAAO;QAChB;QAEAf,GAAG,qEAAqE;YACtE,MAAMU,UAAU;gBACdC,IAAI;gBACJC,YAAY;YACd;YAEAX,OAAO;gBACLG,0BAA0B;oBACxBG;oBACAM,UAAU;oBACVH,SAASA;oBACTI,UAAU;gBACZ;YACF,GAAGM,GAAG,CAACL,OAAO;QAChB;QAEAf,GAAG,kDAAkD;YACnD,MAAMU,UAAU;gBACdC,IAAI;gBACJC,YAAY;gBACZO,WAAW;YACb;YAEAlB,OAAO;gBACLG,0BAA0B;oBACxBG;oBACAM,UAAU;oBACVH,SAASA;gBACX;YACF,GAAGU,GAAG,CAACL,OAAO;QAChB;IACF;IAEAhB,SAAS,iCAAiC;QACxCC,GAAG,2EAA2E;YAC5E,MAAMU,UAAU;gBACdC,IAAI;gBACJO,YAAY;gBACZC,WAAW;YACb;YAEA,MAAMF,UAAU;gBACdN,IAAI;gBACJC,YAAY;gBACZO,WAAW;YACb;YAEA,6DAA6D;YAC7DlB,OAAO;gBACLG,0BAA0B;oBACxBG;oBACAM,UAAU;oBACVH,SAASA;oBACTI,UAAU;oBACVG,SAASA;gBACX;YACF,GAAGG,GAAG,CAACL,OAAO;QAChB;QAEAf,GAAG,kEAAkE;YACnE,MAAMU,UAAU;gBACdC,IAAI;gBACJC,YAAY;gBACZO,WAAW;YACb;YAEA,MAAMF,UAAU;gBACdN,IAAI;gBACJC,YAAY;gBACZO,WAAW;YACb;YAEAlB,OAAO;gBACLG,0BAA0B;oBACxBG;oBACAM,UAAU;oBACVH,SAASA;oBACTI,UAAU;oBACVG,SAASA;gBACX;YACF,GAAGG,GAAG,CAACL,OAAO;QAChB;IACF;AACF"}
@@ -1,14 +1,15 @@
1
+ import { describe, it, expect, vitest } from 'vitest';
1
2
  import { USD } from '../currencies/index.js';
2
3
  import { getCollectionSlugMap } from './getCollectionSlugMap';
3
4
  describe('getCollectionSlugMap', ()=>{
4
5
  const mockAccessConfig = {
5
- adminOnlyFieldAccess: jest.fn(),
6
- adminOrPublishedStatus: jest.fn(),
7
- customerOnlyFieldAccess: jest.fn(),
8
- isAdmin: jest.fn(),
9
- isAuthenticated: jest.fn(),
10
- isDocumentOwner: jest.fn(),
11
- publicAccess: jest.fn()
6
+ adminOnlyFieldAccess: vitest.fn(),
7
+ adminOrPublishedStatus: vitest.fn(),
8
+ customerOnlyFieldAccess: vitest.fn(),
9
+ isAdmin: vitest.fn(),
10
+ isAuthenticated: vitest.fn(),
11
+ isDocumentOwner: vitest.fn(),
12
+ publicAccess: vitest.fn()
12
13
  };
13
14
  const baseConfig = {
14
15
  access: mockAccessConfig,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/getCollectionSlugMap.spec.ts"],"sourcesContent":["import type { SanitizedEcommercePluginConfig } from '../types/index.js'\n\nimport { USD } from '../currencies/index.js'\nimport { getCollectionSlugMap } from './getCollectionSlugMap'\n\ndescribe('getCollectionSlugMap', () => {\n const mockAccessConfig = {\n adminOnlyFieldAccess: jest.fn(),\n adminOrPublishedStatus: jest.fn(),\n customerOnlyFieldAccess: jest.fn(),\n isAdmin: jest.fn(),\n isAuthenticated: jest.fn(),\n isDocumentOwner: jest.fn(),\n publicAccess: jest.fn(),\n }\n\n const baseConfig: SanitizedEcommercePluginConfig = {\n access: mockAccessConfig,\n addresses: {\n addressFields: [],\n },\n carts: true,\n currencies: {\n defaultCurrency: 'USD',\n supportedCurrencies: [USD],\n },\n customers: {\n slug: 'users',\n },\n orders: true,\n payments: {\n paymentMethods: [],\n },\n products: true,\n transactions: true,\n }\n\n it('should return default slug map when no overrides are provided', () => {\n const result = getCollectionSlugMap({ sanitizedPluginConfig: baseConfig })\n\n expect(result).toEqual({\n addresses: 'addresses',\n carts: 'carts',\n customers: 'users',\n orders: 'orders',\n products: 'products',\n transactions: 'transactions',\n variantOptions: 'variantOptions',\n variants: 'variants',\n variantTypes: 'variantTypes',\n })\n })\n\n it('should use custom customers slug when provided', () => {\n const config: SanitizedEcommercePluginConfig = {\n ...baseConfig,\n customers: {\n slug: 'custom-users',\n },\n }\n\n const result = getCollectionSlugMap({ sanitizedPluginConfig: config })\n\n expect(result.customers).toBe('custom-users')\n })\n\n it('should apply slugMap overrides', () => {\n const config: SanitizedEcommercePluginConfig = {\n ...baseConfig,\n slugMap: {\n products: 'custom-products',\n variants: 'custom-variants',\n orders: 'custom-orders',\n },\n }\n\n const result = getCollectionSlugMap({ sanitizedPluginConfig: config })\n\n expect(result.products).toBe('custom-products')\n expect(result.variants).toBe('custom-variants')\n expect(result.orders).toBe('custom-orders')\n // Other slugs should remain default\n expect(result.addresses).toBe('addresses')\n expect(result.carts).toBe('carts')\n })\n\n it('should prioritize slugMap overrides over customers slug', () => {\n const config: SanitizedEcommercePluginConfig = {\n ...baseConfig,\n customers: {\n slug: 'my-users',\n },\n slugMap: {\n customers: 'overridden-users',\n },\n }\n\n const result = getCollectionSlugMap({ sanitizedPluginConfig: config })\n\n expect(result.customers).toBe('overridden-users')\n })\n\n it('should handle partial slugMap overrides', () => {\n const config: SanitizedEcommercePluginConfig = {\n ...baseConfig,\n slugMap: {\n products: 'items',\n },\n }\n\n const result = getCollectionSlugMap({ sanitizedPluginConfig: config })\n\n expect(result.products).toBe('items')\n expect(result.addresses).toBe('addresses')\n expect(result.carts).toBe('carts')\n expect(result.customers).toBe('users')\n expect(result.orders).toBe('orders')\n expect(result.transactions).toBe('transactions')\n expect(result.variants).toBe('variants')\n expect(result.variantOptions).toBe('variantOptions')\n expect(result.variantTypes).toBe('variantTypes')\n })\n\n it('should handle empty slugMap', () => {\n const config: SanitizedEcommercePluginConfig = {\n ...baseConfig,\n slugMap: {},\n }\n\n const result = getCollectionSlugMap({ sanitizedPluginConfig: config })\n\n expect(result).toEqual({\n addresses: 'addresses',\n carts: 'carts',\n customers: 'users',\n orders: 'orders',\n products: 'products',\n transactions: 'transactions',\n variantOptions: 'variantOptions',\n variants: 'variants',\n variantTypes: 'variantTypes',\n })\n })\n\n it('should handle undefined slugMap', () => {\n const config: SanitizedEcommercePluginConfig = {\n ...baseConfig,\n slugMap: undefined,\n }\n\n const result = getCollectionSlugMap({ sanitizedPluginConfig: config })\n\n expect(result).toEqual({\n addresses: 'addresses',\n carts: 'carts',\n customers: 'users',\n orders: 'orders',\n products: 'products',\n transactions: 'transactions',\n variantOptions: 'variantOptions',\n variants: 'variants',\n variantTypes: 'variantTypes',\n })\n })\n})\n"],"names":["USD","getCollectionSlugMap","describe","mockAccessConfig","adminOnlyFieldAccess","jest","fn","adminOrPublishedStatus","customerOnlyFieldAccess","isAdmin","isAuthenticated","isDocumentOwner","publicAccess","baseConfig","access","addresses","addressFields","carts","currencies","defaultCurrency","supportedCurrencies","customers","slug","orders","payments","paymentMethods","products","transactions","it","result","sanitizedPluginConfig","expect","toEqual","variantOptions","variants","variantTypes","config","toBe","slugMap","undefined"],"mappings":"AAEA,SAASA,GAAG,QAAQ,yBAAwB;AAC5C,SAASC,oBAAoB,QAAQ,yBAAwB;AAE7DC,SAAS,wBAAwB;IAC/B,MAAMC,mBAAmB;QACvBC,sBAAsBC,KAAKC,EAAE;QAC7BC,wBAAwBF,KAAKC,EAAE;QAC/BE,yBAAyBH,KAAKC,EAAE;QAChCG,SAASJ,KAAKC,EAAE;QAChBI,iBAAiBL,KAAKC,EAAE;QACxBK,iBAAiBN,KAAKC,EAAE;QACxBM,cAAcP,KAAKC,EAAE;IACvB;IAEA,MAAMO,aAA6C;QACjDC,QAAQX;QACRY,WAAW;YACTC,eAAe,EAAE;QACnB;QACAC,OAAO;QACPC,YAAY;YACVC,iBAAiB;YACjBC,qBAAqB;gBAACpB;aAAI;QAC5B;QACAqB,WAAW;YACTC,MAAM;QACR;QACAC,QAAQ;QACRC,UAAU;YACRC,gBAAgB,EAAE;QACpB;QACAC,UAAU;QACVC,cAAc;IAChB;IAEAC,GAAG,iEAAiE;QAClE,MAAMC,SAAS5B,qBAAqB;YAAE6B,uBAAuBjB;QAAW;QAExEkB,OAAOF,QAAQG,OAAO,CAAC;YACrBjB,WAAW;YACXE,OAAO;Y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AAOd,SAAS,EAAEsB,IAAI,CAAC;QAC9BN,OAAOF,OAAOZ,KAAK,EAAEoB,IAAI,CAAC;QAC1BN,OAAOF,OAAOR,SAAS,EAAEgB,IAAI,CAAC;QAC9BN,OAAOF,OAAON,MAAM,EAAEc,IAAI,CAAC;QAC3BN,OAAOF,OAAOF,YAAY,EAAEU,IAAI,CAAC;QACjCN,OAAOF,OAAOK,QAAQ,EAAEG,IAAI,CAAC;QAC7BN,OAAOF,OAAOI,cAAc,EAAEI,IAAI,CAAC;QACnCN,OAAOF,OAAOM,YAAY,EAAEE,IAAI,CAAC;IACnC;IAEAT,GAAG,+BAA+B;QAChC,MAAMQ,SAAyC;YAC7C,GAAGvB,UAAU;YACbyB,SAAS,CAAC;QACZ;QAEA,MAAMT,SAAS5B,qBAAqB;YAAE6B,uBAAuBM;QAAO;QAEpEL,OAAOF,QAAQG,OAAO,CAAC;YACrBjB,WAAW;YACXE,OAAO;YACPI,WAAW;YACXE,QAAQ;YACRG,UAAU;YACVC,cAAc;YACdM,gBAAgB;YAChBC,UAAU;YACVC,cAAc;QAChB;IACF;IAEAP,GAAG,mCAAmC;QACpC,MAAMQ,SAAyC;YAC7C,GAAGvB,UAAU;YACbyB,SAASC;QACX;QAEA,MAAMV,SAAS5B,qBAAqB;YAAE6B,uBAAuBM;QAAO;QAEpEL,OAAOF,QAAQG,OAAO,CAAC;YACrBjB,WAAW;YACXE,OAAO;YACPI,WAAW;YACXE,QAAQ;YACRG,UAAU;YACVC,cAAc;YACdM,gBAAgB;YAChBC,UAAU;YACVC,cAAc;QAChB;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/utilities/getCollectionSlugMap.spec.ts"],"sourcesContent":["import { describe, it, expect, vitest } from 'vitest'\nimport type { SanitizedEcommercePluginConfig } from '../types/index.js'\n\nimport { USD } from '../currencies/index.js'\nimport { getCollectionSlugMap } from './getCollectionSlugMap'\n\ndescribe('getCollectionSlugMap', () => {\n const mockAccessConfig = {\n adminOnlyFieldAccess: vitest.fn(),\n adminOrPublishedStatus: vitest.fn(),\n customerOnlyFieldAccess: vitest.fn(),\n isAdmin: vitest.fn(),\n isAuthenticated: vitest.fn(),\n isDocumentOwner: vitest.fn(),\n publicAccess: vitest.fn(),\n }\n\n const baseConfig: SanitizedEcommercePluginConfig = {\n access: mockAccessConfig,\n addresses: {\n addressFields: [],\n },\n carts: true,\n currencies: {\n defaultCurrency: 'USD',\n supportedCurrencies: [USD],\n },\n customers: {\n slug: 'users',\n },\n orders: true,\n payments: {\n paymentMethods: [],\n },\n products: true,\n transactions: true,\n }\n\n it('should return default slug map when no overrides are provided', () => {\n const result = getCollectionSlugMap({ sanitizedPluginConfig: baseConfig })\n\n expect(result).toEqual({\n addresses: 'addresses',\n carts: 'carts',\n customers: 'users',\n orders: 'orders',\n products: 'products',\n transactions: 'transactions',\n variantOptions: 'variantOptions',\n variants: 'variants',\n variantTypes: 'variantTypes',\n })\n })\n\n it('should use custom customers slug when provided', () => {\n const config: SanitizedEcommercePluginConfig = {\n ...baseConfig,\n customers: {\n slug: 'custom-users',\n },\n }\n\n const result = getCollectionSlugMap({ sanitizedPluginConfig: config })\n\n expect(result.customers).toBe('custom-users')\n })\n\n it('should apply slugMap overrides', () => {\n const config: SanitizedEcommercePluginConfig = {\n ...baseConfig,\n slugMap: {\n products: 'custom-products',\n variants: 'custom-variants',\n orders: 'custom-orders',\n },\n }\n\n const result = getCollectionSlugMap({ sanitizedPluginConfig: config })\n\n expect(result.products).toBe('custom-products')\n expect(result.variants).toBe('custom-variants')\n expect(result.orders).toBe('custom-orders')\n // Other slugs should remain default\n expect(result.addresses).toBe('addresses')\n expect(result.carts).toBe('carts')\n })\n\n it('should prioritize slugMap overrides over customers slug', () => {\n const config: SanitizedEcommercePluginConfig = {\n ...baseConfig,\n customers: {\n slug: 'my-users',\n },\n slugMap: {\n customers: 'overridden-users',\n },\n }\n\n const result = getCollectionSlugMap({ sanitizedPluginConfig: config })\n\n expect(result.customers).toBe('overridden-users')\n })\n\n it('should handle partial slugMap overrides', () => {\n const config: SanitizedEcommercePluginConfig = {\n ...baseConfig,\n slugMap: {\n products: 'items',\n },\n }\n\n const result = getCollectionSlugMap({ sanitizedPluginConfig: config })\n\n expect(result.products).toBe('items')\n expect(result.addresses).toBe('addresses')\n expect(result.carts).toBe('carts')\n expect(result.customers).toBe('users')\n expect(result.orders).toBe('orders')\n expect(result.transactions).toBe('transactions')\n expect(result.variants).toBe('variants')\n expect(result.variantOptions).toBe('variantOptions')\n expect(result.variantTypes).toBe('variantTypes')\n })\n\n it('should handle empty slugMap', () => {\n const config: SanitizedEcommercePluginConfig = {\n ...baseConfig,\n slugMap: {},\n }\n\n const result = getCollectionSlugMap({ sanitizedPluginConfig: config })\n\n expect(result).toEqual({\n addresses: 'addresses',\n carts: 'carts',\n customers: 'users',\n orders: 'orders',\n products: 'products',\n transactions: 'transactions',\n variantOptions: 'variantOptions',\n variants: 'variants',\n variantTypes: 'variantTypes',\n })\n })\n\n it('should handle undefined slugMap', () => {\n const config: SanitizedEcommercePluginConfig = {\n ...baseConfig,\n slugMap: undefined,\n }\n\n const result = getCollectionSlugMap({ sanitizedPluginConfig: config })\n\n expect(result).toEqual({\n addresses: 'addresses',\n carts: 'carts',\n customers: 'users',\n orders: 'orders',\n products: 'products',\n transactions: 'transactions',\n variantOptions: 'variantOptions',\n variants: 'variants',\n variantTypes: 'variantTypes',\n })\n })\n})\n"],"names":["describe","it","expect","vitest","USD","getCollectionSlugMap","mockAccessConfig","adminOnlyFieldAccess","fn","adminOrPublishedStatus","customerOnlyFieldAccess","isAdmin","isAuthenticated","isDocumentOwner","publicAccess","baseConfig","access","addresses","addressFields","carts","currencies","defaultCurrency","supportedCurrencies","customers","slug","orders","payments","paymentMethods","products","transactions","result","sanitizedPluginConfig","toEqual","variantOptions","variants","variantTypes","config","toBe","slugMap","undefined"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,EAAE,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAQ;AAGrD,S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qB;YAAE0B,uBAAuBK;QAAO;QAEpElC,OAAO4B,QAAQE,OAAO,CAAC;YACrBf,WAAW;YACXE,OAAO;YACPI,WAAW;YACXE,QAAQ;YACRG,UAAU;YACVC,cAAc;YACdI,gBAAgB;YAChBC,UAAU;YACVC,cAAc;QAChB;IACF;IAEAlC,GAAG,mCAAmC;QACpC,MAAMmC,SAAyC;YAC7C,GAAGrB,UAAU;YACbuB,SAASC;QACX;QAEA,MAAMT,SAASzB,qBAAqB;YAAE0B,uBAAuBK;QAAO;QAEpElC,OAAO4B,QAAQE,OAAO,CAAC;YACrBf,WAAW;YACXE,OAAO;YACPI,WAAW;YACXE,QAAQ;YACRG,UAAU;YACVC,cAAc;YACdI,gBAAgB;YAChBC,UAAU;YACVC,cAAc;QAChB;IACF;AACF"}
@@ -1,13 +1,14 @@
1
+ import { describe, it, expect, vitest } from 'vitest';
1
2
  import { EUR, USD } from '../currencies/index.js';
2
3
  import { sanitizePluginConfig } from './sanitizePluginConfig';
3
4
  describe('sanitizePluginConfig', ()=>{
4
5
  const mockAccessConfig = {
5
- adminOnlyFieldAccess: jest.fn(),
6
- adminOrPublishedStatus: jest.fn(),
7
- customerOnlyFieldAccess: jest.fn(),
8
- isAdmin: jest.fn(),
9
- isAuthenticated: jest.fn(),
10
- isDocumentOwner: jest.fn()
6
+ adminOnlyFieldAccess: vitest.fn(),
7
+ adminOrPublishedStatus: vitest.fn(),
8
+ customerOnlyFieldAccess: vitest.fn(),
9
+ isAdmin: vitest.fn(),
10
+ isAuthenticated: vitest.fn(),
11
+ isDocumentOwner: vitest.fn()
11
12
  };
12
13
  const minimalConfig = {
13
14
  access: mockAccessConfig,
@@ -259,7 +260,7 @@ describe('sanitizePluginConfig', ()=>{
259
260
  ...minimalConfig,
260
261
  carts: {
261
262
  allowGuestCarts: false,
262
- cartsCollectionOverride: jest.fn()
263
+ cartsCollectionOverride: vitest.fn()
263
264
  }
264
265
  };
265
266
  const result = sanitizePluginConfig({
@@ -409,8 +410,8 @@ describe('sanitizePluginConfig', ()=>{
409
410
  expect(typeof result.access.publicAccess).toBe('function');
410
411
  });
411
412
  it('should allow user-provided access functions to override defaults', ()=>{
412
- const customIsAuthenticated = jest.fn();
413
- const customPublicAccess = jest.fn();
413
+ const customIsAuthenticated = vitest.fn();
414
+ const customPublicAccess = vitest.fn();
414
415
  const config = {
415
416
  ...minimalConfig,
416
417
  access: {
@@ -1 +1 @@
1
- {"version":3,"sources":["../../src/utilities/sanitizePluginConfig.spec.ts"],"sourcesContent":["import type { EcommercePluginConfig } from '../types/index.js'\n\nimport { EUR, USD } from '../currencies/index.js'\nimport { sanitizePluginConfig } from './sanitizePluginConfig'\n\ndescribe('sanitizePluginConfig', () => {\n const mockAccessConfig = {\n adminOnlyFieldAccess: jest.fn(),\n adminOrPublishedStatus: jest.fn(),\n customerOnlyFieldAccess: jest.fn(),\n isAdmin: jest.fn(),\n isAuthenticated: jest.fn(),\n isDocumentOwner: jest.fn(),\n }\n\n const minimalConfig: EcommercePluginConfig = {\n access: mockAccessConfig,\n customers: {\n slug: 'users',\n },\n }\n\n describe('customers', () => {\n it('should default customers slug to \"users\" when undefined', () => {\n const config: EcommercePluginConfig = {\n access: mockAccessConfig,\n customers: undefined as any,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.customers).toEqual({\n slug: 'users',\n })\n })\n\n it('should preserve custom customers slug', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n customers: {\n slug: 'custom-users',\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.customers.slug).toBe('custom-users')\n })\n })\n\n describe('addresses', () => {\n it('should create default addresses config when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.addresses).toBeDefined()\n expect(result.addresses.addressFields).toBeDefined()\n expect(Array.isArray(result.addresses.addressFields)).toBe(true)\n expect(result.addresses.addressFields.length).toBeGreaterThan(0)\n })\n\n it('should create default addresses config when set to true', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n addresses: true,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.addresses).toBeDefined()\n expect(result.addresses.addressFields).toBeDefined()\n expect(Array.isArray(result.addresses.addressFields)).toBe(true)\n })\n\n it('should use custom addressFields function', () => {\n const customField = {\n name: 'customField',\n type: 'text' as const,\n }\n\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n addresses: {\n addressFields: ({ defaultFields }) => [...defaultFields, customField],\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.addresses.addressFields).toBeDefined()\n const lastField = result.addresses.addressFields[result.addresses.addressFields.length - 1]\n expect(lastField).toEqual(customField)\n })\n\n it('should preserve other address config properties', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n addresses: {\n addressFields: ({ defaultFields }) => defaultFields,\n supportedCountries: [\n { label: 'United States', value: 'US' },\n { label: 'Canada', value: 'CA' },\n ],\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.addresses.supportedCountries).toEqual([\n { label: 'United States', value: 'US' },\n { label: 'Canada', value: 'CA' },\n ])\n })\n })\n\n describe('currencies', () => {\n it('should default to USD when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.currencies).toEqual({\n defaultCurrency: 'USD',\n supportedCurrencies: [USD],\n })\n })\n\n it('should preserve custom currencies config', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n currencies: {\n defaultCurrency: 'EUR',\n supportedCurrencies: [USD, EUR],\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.currencies).toEqual({\n defaultCurrency: 'EUR',\n supportedCurrencies: [USD, EUR],\n })\n })\n })\n\n describe('inventory', () => {\n it('should default inventory config when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.inventory).toEqual({\n fieldName: 'inventory',\n })\n })\n\n it('should default inventory config when set to true', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n inventory: true,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.inventory).toEqual({\n fieldName: 'inventory',\n })\n })\n\n it('should preserve custom inventory config', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n inventory: {\n fieldName: 'stock',\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.inventory).toEqual({\n fieldName: 'stock',\n })\n })\n\n it('should allow disabling inventory with false', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n inventory: false,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.inventory).toBe(false)\n })\n })\n\n describe('carts', () => {\n it('should default carts to object with allowGuestCarts true when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.carts).toEqual({\n allowGuestCarts: true,\n })\n })\n\n it('should convert carts true to object with allowGuestCarts true', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n carts: true,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.carts).toEqual({\n allowGuestCarts: true,\n })\n })\n\n it('should preserve carts false', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n carts: false,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.carts).toBe(false)\n })\n\n it('should default allowGuestCarts to true when carts is object without it', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n carts: {} as any,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.carts).toEqual({\n allowGuestCarts: true,\n })\n })\n\n it('should preserve explicit allowGuestCarts false', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n carts: {\n allowGuestCarts: false,\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.carts).toEqual({\n allowGuestCarts: false,\n })\n })\n\n it('should preserve other carts config properties', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n carts: {\n allowGuestCarts: false,\n cartsCollectionOverride: jest.fn() as any,\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.carts).toHaveProperty('allowGuestCarts', false)\n expect(result.carts).toHaveProperty('cartsCollectionOverride')\n })\n })\n\n describe('orders', () => {\n it('should default orders to true when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.orders).toBe(true)\n })\n\n it('should preserve orders config', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n orders: false,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.orders).toBe(false)\n })\n })\n\n describe('transactions', () => {\n it('should default transactions to true when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.transactions).toBe(true)\n })\n\n it('should preserve transactions config', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n transactions: false,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.transactions).toBe(false)\n })\n })\n\n describe('payments', () => {\n it('should default payments to empty array when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.payments).toEqual({\n paymentMethods: [],\n })\n })\n\n it('should default paymentMethods to empty array when not provided', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n payments: {} as any,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.payments.paymentMethods).toEqual([])\n })\n\n it('should preserve payment methods', () => {\n const mockAdapter = {\n name: 'stripe',\n label: 'Stripe',\n } as any\n\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n payments: {\n paymentMethods: [mockAdapter],\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.payments.paymentMethods).toEqual([mockAdapter])\n })\n })\n\n describe('products', () => {\n it('should default variants to true when products is object and variants is undefined', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n products: {},\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.products).toEqual({\n variants: true,\n })\n })\n\n it('should preserve variants config when provided', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n products: {\n variants: false,\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.products).toEqual({\n variants: false,\n })\n })\n\n it('should not modify products when set to true', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n products: true,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.products).toBe(true)\n })\n\n it('should not modify products when set to false', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n products: false,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.products).toBe(false)\n })\n })\n\n describe('access', () => {\n it('should provide default isAuthenticated function', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.access.isAuthenticated).toBeDefined()\n expect(typeof result.access.isAuthenticated).toBe('function')\n })\n\n it('should provide default publicAccess function', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.access.publicAccess).toBeDefined()\n expect(typeof result.access.publicAccess).toBe('function')\n })\n\n it('should allow user-provided access functions to override defaults', () => {\n const customIsAuthenticated = jest.fn()\n const customPublicAccess = jest.fn()\n\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n access: {\n ...mockAccessConfig,\n isAuthenticated: customIsAuthenticated,\n publicAccess: customPublicAccess,\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.access.isAuthenticated).toBe(customIsAuthenticated)\n expect(result.access.publicAccess).toBe(customPublicAccess)\n })\n\n it('should preserve all user-provided access functions', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.access.adminOnlyFieldAccess).toBe(mockAccessConfig.adminOnlyFieldAccess)\n expect(result.access.adminOrPublishedStatus).toBe(mockAccessConfig.adminOrPublishedStatus)\n expect(result.access.customerOnlyFieldAccess).toBe(mockAccessConfig.customerOnlyFieldAccess)\n expect(result.access.isAdmin).toBe(mockAccessConfig.isAdmin)\n expect(result.access.isDocumentOwner).toBe(mockAccessConfig.isDocumentOwner)\n })\n\n it('default publicAccess should always return true', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n // @ts-expect-error - ignoring for test\n expect(result.access.publicAccess()).toBe(true)\n })\n\n it('default isAuthenticated should be provided', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.access.isAuthenticated).toBeDefined()\n expect(typeof result.access.isAuthenticated).toBe('function')\n })\n })\n\n describe('complete config', () => {\n it('should handle a fully configured plugin', () => {\n const fullConfig: EcommercePluginConfig = {\n access: mockAccessConfig,\n addresses: {\n addressFields: ({ defaultFields }) => defaultFields,\n supportedCountries: [{ label: 'US', value: 'US' }],\n },\n carts: {\n allowGuestCarts: true,\n },\n currencies: {\n defaultCurrency: 'EUR',\n supportedCurrencies: [USD, EUR],\n },\n customers: {\n slug: 'customers',\n },\n inventory: {\n fieldName: 'stock',\n },\n orders: true,\n payments: {\n paymentMethods: [],\n },\n products: {\n variants: true,\n },\n slugMap: {\n products: 'items',\n },\n transactions: true,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: fullConfig })\n\n expect(result.customers.slug).toBe('customers')\n expect(result.currencies.defaultCurrency).toBe('EUR')\n expect(result.inventory).toEqual({ fieldName: 'stock' })\n expect(result.carts).toHaveProperty('allowGuestCarts', true)\n expect(result.orders).toBe(true)\n expect(result.transactions).toBe(true)\n expect(result.products).toEqual({ variants: true })\n expect(result.slugMap).toEqual({ products: 'items' })\n })\n })\n})\n"],"names":["EUR","USD","sanitizePluginConfig","describe","mockAccessConfig","adminOnlyFieldAccess","jest","fn","adminOrPublishedStatus","customerOnlyFieldAccess","isAdmin","isAuthenticated","isDocumentOwner","minimalConfig","access","customers","slug","it","config","undefined","result","pluginConfig","expect","toEqual","toBe","addresses","toBeDefined","addressFields","Array","isArray","length","toBeGreaterThan","customField","name","type","defaultFields","lastField","supportedCountries","label","value","currencies","defaultCurrency","supportedCurrencies","inventory","fieldName","carts","allowGuestCarts","cartsCollectionOverride","toHaveProperty","orders","transactions","payments","paymentMethods","mockAdapter","products","variants","publicAccess","customIsAuthenticated","customPublicAccess","fullConfig","slugMap"],"mappings":"AAEA,SAASA,GAAG,EAAEC,GAAG,QAAQ,yBAAwB;AACjD,SAASC,oBAAoB,QAAQ,yBAAwB;AAE7DC,SAAS,wBAAwB;IAC/B,MAAMC,mBAAmB;QACvBC,sBAAsBC,KAAKC,EAAE;QAC7BC,wBAAwBF,KAAKC,EAAE;QAC/BE,yBAAyBH,KAAKC,EAAE;QAChCG,SAASJ,KAAKC,EAAE;QAChBI,iBAAiBL,KAAKC,EAAE;QACxBK,iBAAiBN,KAAKC,EAAE;IAC1B;IAEA,MAAMM,gBAAuC;QAC3CC,QAAQV;QACRW,WAAW;YACTC,MAAM;QACR;IACF;IAEAb,SAAS,aAAa;QACpBc,GAAG,2DAA2D;YAC5D,MAAMC,SAAgC;gBACpCJ,QAAQV;gBACRW,WAAWI;YACb;YAEA,MAAMC,SAASlB,qBAAqB;gBAAEmB,cAAcH;YAAO;YAE3DI,OAAOF,OAAOL,SAAS,EAAEQ,OAAO,CAAC;gBAC/BP,MAAM;YACR;QACF;QAEAC,GAAG,yCAAyC;YAC1C,MAAMC,SAAgC;gBACpC,GAAGL,aAAa;gBAChBE,WAAW;oBACTC,MAAM;gBACR;YACF;YAEA,MAAMI,SAASlB,qBAAqB;gBAAEmB,cAAcH;YAAO;YAE3DI,OAAOF,OAAOL,SAAS,CAACC,IAAI,EAAEQ,IAAI,CAAC;QACrC;IACF;IAEArB,SAAS,aAAa;QACpBc,GAAG,yDAAyD;YAC1D,MAAMG,SAASlB,qBAAqB;gBAAEmB,cAAcR;YAAc;YAElES,OAAOF,OAAOK,SAAS,EAAEC,WAAW;YACpCJ,OAAOF,OAAOK,SAAS,CAACE,aAAa,EAAED,WAAW;YAClDJ,OAAOM,MAAMC,OAAO,CAACT,OAAOK,SAAS,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L,SAAS,CAACC,IAAI,EAAEQ,IAAI,CAAC;YACnCF,OAAOF,OAAOoB,UAAU,CAACC,eAAe,EAAEjB,IAAI,CAAC;YAC/CF,OAAOF,OAAOuB,SAAS,EAAEpB,OAAO,CAAC;gBAAEqB,WAAW;YAAQ;YACtDtB,OAAOF,OAAOyB,KAAK,EAAEG,cAAc,CAAC,mBAAmB;YACvD1B,OAAOF,OAAO6B,MAAM,EAAEzB,IAAI,CAAC;YAC3BF,OAAOF,OAAO8B,YAAY,EAAE1B,IAAI,CAAC;YACjCF,OAAOF,OAAOkC,QAAQ,EAAE/B,OAAO,CAAC;gBAAEgC,UAAU;YAAK;YACjDjC,OAAOF,OAAOwC,OAAO,EAAErC,OAAO,CAAC;gBAAE+B,UAAU;YAAQ;QACrD;IACF;AACF"}
1
+ {"version":3,"sources":["../../src/utilities/sanitizePluginConfig.spec.ts"],"sourcesContent":["import { describe, it, expect, vitest } from 'vitest'\nimport type { EcommercePluginConfig } from '../types/index.js'\n\nimport { EUR, USD } from '../currencies/index.js'\nimport { sanitizePluginConfig } from './sanitizePluginConfig'\n\ndescribe('sanitizePluginConfig', () => {\n const mockAccessConfig = {\n adminOnlyFieldAccess: vitest.fn(),\n adminOrPublishedStatus: vitest.fn(),\n customerOnlyFieldAccess: vitest.fn(),\n isAdmin: vitest.fn(),\n isAuthenticated: vitest.fn(),\n isDocumentOwner: vitest.fn(),\n }\n\n const minimalConfig: EcommercePluginConfig = {\n access: mockAccessConfig,\n customers: {\n slug: 'users',\n },\n }\n\n describe('customers', () => {\n it('should default customers slug to \"users\" when undefined', () => {\n const config: EcommercePluginConfig = {\n access: mockAccessConfig,\n customers: undefined as any,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.customers).toEqual({\n slug: 'users',\n })\n })\n\n it('should preserve custom customers slug', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n customers: {\n slug: 'custom-users',\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.customers.slug).toBe('custom-users')\n })\n })\n\n describe('addresses', () => {\n it('should create default addresses config when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.addresses).toBeDefined()\n expect(result.addresses.addressFields).toBeDefined()\n expect(Array.isArray(result.addresses.addressFields)).toBe(true)\n expect(result.addresses.addressFields.length).toBeGreaterThan(0)\n })\n\n it('should create default addresses config when set to true', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n addresses: true,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.addresses).toBeDefined()\n expect(result.addresses.addressFields).toBeDefined()\n expect(Array.isArray(result.addresses.addressFields)).toBe(true)\n })\n\n it('should use custom addressFields function', () => {\n const customField = {\n name: 'customField',\n type: 'text' as const,\n }\n\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n addresses: {\n addressFields: ({ defaultFields }) => [...defaultFields, customField],\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.addresses.addressFields).toBeDefined()\n const lastField = result.addresses.addressFields[result.addresses.addressFields.length - 1]\n expect(lastField).toEqual(customField)\n })\n\n it('should preserve other address config properties', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n addresses: {\n addressFields: ({ defaultFields }) => defaultFields,\n supportedCountries: [\n { label: 'United States', value: 'US' },\n { label: 'Canada', value: 'CA' },\n ],\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.addresses.supportedCountries).toEqual([\n { label: 'United States', value: 'US' },\n { label: 'Canada', value: 'CA' },\n ])\n })\n })\n\n describe('currencies', () => {\n it('should default to USD when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.currencies).toEqual({\n defaultCurrency: 'USD',\n supportedCurrencies: [USD],\n })\n })\n\n it('should preserve custom currencies config', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n currencies: {\n defaultCurrency: 'EUR',\n supportedCurrencies: [USD, EUR],\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.currencies).toEqual({\n defaultCurrency: 'EUR',\n supportedCurrencies: [USD, EUR],\n })\n })\n })\n\n describe('inventory', () => {\n it('should default inventory config when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.inventory).toEqual({\n fieldName: 'inventory',\n })\n })\n\n it('should default inventory config when set to true', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n inventory: true,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.inventory).toEqual({\n fieldName: 'inventory',\n })\n })\n\n it('should preserve custom inventory config', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n inventory: {\n fieldName: 'stock',\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.inventory).toEqual({\n fieldName: 'stock',\n })\n })\n\n it('should allow disabling inventory with false', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n inventory: false,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.inventory).toBe(false)\n })\n })\n\n describe('carts', () => {\n it('should default carts to object with allowGuestCarts true when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.carts).toEqual({\n allowGuestCarts: true,\n })\n })\n\n it('should convert carts true to object with allowGuestCarts true', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n carts: true,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.carts).toEqual({\n allowGuestCarts: true,\n })\n })\n\n it('should preserve carts false', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n carts: false,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.carts).toBe(false)\n })\n\n it('should default allowGuestCarts to true when carts is object without it', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n carts: {} as any,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.carts).toEqual({\n allowGuestCarts: true,\n })\n })\n\n it('should preserve explicit allowGuestCarts false', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n carts: {\n allowGuestCarts: false,\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.carts).toEqual({\n allowGuestCarts: false,\n })\n })\n\n it('should preserve other carts config properties', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n carts: {\n allowGuestCarts: false,\n cartsCollectionOverride: vitest.fn() as any,\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.carts).toHaveProperty('allowGuestCarts', false)\n expect(result.carts).toHaveProperty('cartsCollectionOverride')\n })\n })\n\n describe('orders', () => {\n it('should default orders to true when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.orders).toBe(true)\n })\n\n it('should preserve orders config', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n orders: false,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.orders).toBe(false)\n })\n })\n\n describe('transactions', () => {\n it('should default transactions to true when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.transactions).toBe(true)\n })\n\n it('should preserve transactions config', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n transactions: false,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.transactions).toBe(false)\n })\n })\n\n describe('payments', () => {\n it('should default payments to empty array when undefined', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.payments).toEqual({\n paymentMethods: [],\n })\n })\n\n it('should default paymentMethods to empty array when not provided', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n payments: {} as any,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.payments.paymentMethods).toEqual([])\n })\n\n it('should preserve payment methods', () => {\n const mockAdapter = {\n name: 'stripe',\n label: 'Stripe',\n } as any\n\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n payments: {\n paymentMethods: [mockAdapter],\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.payments.paymentMethods).toEqual([mockAdapter])\n })\n })\n\n describe('products', () => {\n it('should default variants to true when products is object and variants is undefined', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n products: {},\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.products).toEqual({\n variants: true,\n })\n })\n\n it('should preserve variants config when provided', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n products: {\n variants: false,\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.products).toEqual({\n variants: false,\n })\n })\n\n it('should not modify products when set to true', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n products: true,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.products).toBe(true)\n })\n\n it('should not modify products when set to false', () => {\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n products: false,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.products).toBe(false)\n })\n })\n\n describe('access', () => {\n it('should provide default isAuthenticated function', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.access.isAuthenticated).toBeDefined()\n expect(typeof result.access.isAuthenticated).toBe('function')\n })\n\n it('should provide default publicAccess function', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.access.publicAccess).toBeDefined()\n expect(typeof result.access.publicAccess).toBe('function')\n })\n\n it('should allow user-provided access functions to override defaults', () => {\n const customIsAuthenticated = vitest.fn()\n const customPublicAccess = vitest.fn()\n\n const config: EcommercePluginConfig = {\n ...minimalConfig,\n access: {\n ...mockAccessConfig,\n isAuthenticated: customIsAuthenticated,\n publicAccess: customPublicAccess,\n },\n }\n\n const result = sanitizePluginConfig({ pluginConfig: config })\n\n expect(result.access.isAuthenticated).toBe(customIsAuthenticated)\n expect(result.access.publicAccess).toBe(customPublicAccess)\n })\n\n it('should preserve all user-provided access functions', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.access.adminOnlyFieldAccess).toBe(mockAccessConfig.adminOnlyFieldAccess)\n expect(result.access.adminOrPublishedStatus).toBe(mockAccessConfig.adminOrPublishedStatus)\n expect(result.access.customerOnlyFieldAccess).toBe(mockAccessConfig.customerOnlyFieldAccess)\n expect(result.access.isAdmin).toBe(mockAccessConfig.isAdmin)\n expect(result.access.isDocumentOwner).toBe(mockAccessConfig.isDocumentOwner)\n })\n\n it('default publicAccess should always return true', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n // @ts-expect-error - ignoring for test\n expect(result.access.publicAccess()).toBe(true)\n })\n\n it('default isAuthenticated should be provided', () => {\n const result = sanitizePluginConfig({ pluginConfig: minimalConfig })\n\n expect(result.access.isAuthenticated).toBeDefined()\n expect(typeof result.access.isAuthenticated).toBe('function')\n })\n })\n\n describe('complete config', () => {\n it('should handle a fully configured plugin', () => {\n const fullConfig: EcommercePluginConfig = {\n access: mockAccessConfig,\n addresses: {\n addressFields: ({ defaultFields }) => defaultFields,\n supportedCountries: [{ label: 'US', value: 'US' }],\n },\n carts: {\n allowGuestCarts: true,\n },\n currencies: {\n defaultCurrency: 'EUR',\n supportedCurrencies: [USD, EUR],\n },\n customers: {\n slug: 'customers',\n },\n inventory: {\n fieldName: 'stock',\n },\n orders: true,\n payments: {\n paymentMethods: [],\n },\n products: {\n variants: true,\n },\n slugMap: {\n products: 'items',\n },\n transactions: true,\n }\n\n const result = sanitizePluginConfig({ pluginConfig: fullConfig })\n\n expect(result.customers.slug).toBe('customers')\n expect(result.currencies.defaultCurrency).toBe('EUR')\n expect(result.inventory).toEqual({ fieldName: 'stock' })\n expect(result.carts).toHaveProperty('allowGuestCarts', true)\n expect(result.orders).toBe(true)\n expect(result.transactions).toBe(true)\n expect(result.products).toEqual({ variants: true })\n expect(result.slugMap).toEqual({ products: 'items' })\n })\n })\n})\n"],"names":["describe","it","expect","vitest","EUR","USD","sanitizePluginConfig","mockAccessConfig","adminOnlyFieldAccess","fn","adminOrPublishedStatus","customerOnlyFieldAccess","isAdmin","isAuthenticated","isDocumentOwner","minimalConfig","access","customers","slug","config","undefined","result","pluginConfig","toEqual","toBe","addresses","toBeDefined","addressFields","Array","isArray","length","toBeGreaterThan","customField","name","type","defaultFields","lastField","supportedCountries","label","value","currencies","defaultCurrency","supportedCurrencies","inventory","fieldName","carts","allowGuestCarts","cartsCollectionOverride","toHaveProperty","orders","transactions","payments","paymentMethods","mockAdapter","products","variants","publicAccess","customIsAuthenticated","customPublicAccess","fullConfig","slugMap"],"mappings":"AAAA,SAASA,QAAQ,EAAEC,EAAE,EAAEC,MAAM,EAAEC,MAAM,QAAQ,SAAQ;AAGrD,SAASC,GAAG,EAAEC,GAAG,QAAQ,yBAAwB;AACjD,SAASC,oBAAoB,QAAQ,yBAAwB;AAE7DN,SAAS,wBAAwB;IAC/B,MAAMO,mBAAmB;QACvBC,sBAAsBL,OAAOM,EAAE;QAC/BC,wBAAwBP,OAAOM,EAAE;QACjCE,yBAAyBR,OAAOM,EAAE;QAClCG,SAAST,OAAOM,EAAE;QAClBI,iBAAiBV,OAAOM,EAAE;QAC1BK,iBAAiBX,OAAOM,EAAE;IAC5B;IAEA,MAAMM,gBAAuC;QAC3CC,QAAQT;QACRU,WAAW;YACTC,MAAM;QACR;IACF;IAEAlB,SAAS,aAAa;QACpBC,GAAG,2DAA2D;YAC5D,MAAMkB,SAAgC;gBACpCH,QAAQT;gBACRU,WAAWG;YACb;YAEA,MAAMC,SAASf,qBAAqB;gBAAEgB,cAAcH;YAAO;YAE3DjB,OAAOmB,OAAOJ,SAAS,EAAEM,OAAO,CAAC;gBAC/BL,MAAM;YACR;QACF;QAEAjB,GAAG,yCAAyC;YAC1C,MAAMkB,SAAgC;gBACpC,GAAGJ,aAAa;gBAChBE,WAAW;oBACTC,MAAM;gBACR;YACF;YA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e,CAAC,EAAEQ,aAAa,EAAE,GAAKA;oBACtCE,oBAAoB;wBAAC;4BAAEC,OAAO;4BAAMC,OAAO;wBAAK;qBAAE;gBACpD;gBACAM,OAAO;oBACLC,iBAAiB;gBACnB;gBACAN,YAAY;oBACVC,iBAAiB;oBACjBC,qBAAqB;wBAACrC;wBAAKD;qBAAI;gBACjC;gBACAa,WAAW;oBACTC,MAAM;gBACR;gBACAyB,WAAW;oBACTC,WAAW;gBACb;gBACAK,QAAQ;gBACRE,UAAU;oBACRC,gBAAgB,EAAE;gBACpB;gBACAE,UAAU;oBACRC,UAAU;gBACZ;gBACAK,SAAS;oBACPN,UAAU;gBACZ;gBACAJ,cAAc;YAChB;YAEA,MAAM7B,SAASf,qBAAqB;gBAAEgB,cAAcqC;YAAW;YAE/DzD,OAAOmB,OAAOJ,SAAS,CAACC,IAAI,EAAEM,IAAI,CAAC;YACnCtB,OAAOmB,OAAOmB,UAAU,CAACC,eAAe,EAAEjB,IAAI,CAAC;YAC/CtB,OAAOmB,OAAOsB,SAAS,EAAEpB,OAAO,CAAC;gBAAEqB,WAAW;YAAQ;YACtD1C,OAAOmB,OAAOwB,KAAK,EAAEG,cAAc,CAAC,mBAAmB;YACvD9C,OAAOmB,OAAO4B,MAAM,EAAEzB,IAAI,CAAC;YAC3BtB,OAAOmB,OAAO6B,YAAY,EAAE1B,IAAI,CAAC;YACjCtB,OAAOmB,OAAOiC,QAAQ,EAAE/B,OAAO,CAAC;gBAAEgC,UAAU;YAAK;YACjDrD,OAAOmB,OAAOuC,OAAO,EAAErC,OAAO,CAAC;gBAAE+B,UAAU;YAAQ;QACrD;IACF;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@payloadcms/plugin-ecommerce",
3
- "version": "3.69.0-internal.424436e",
3
+ "version": "3.69.0",
4
4
  "description": "Ecommerce plugin for Payload",
5
5
  "keywords": [
6
6
  "payload",
@@ -69,22 +69,22 @@
69
69
  ],
70
70
  "dependencies": {
71
71
  "qs-esm": "7.0.2",
72
- "@payloadcms/translations": "3.69.0-internal.424436e",
73
- "@payloadcms/ui": "3.69.0-internal.424436e"
72
+ "@payloadcms/ui": "3.69.0",
73
+ "@payloadcms/translations": "3.69.0"
74
74
  },
75
75
  "devDependencies": {
76
76
  "@types/json-schema": "7.0.15",
77
77
  "@types/react": "19.2.1",
78
78
  "@types/react-dom": "19.2.1",
79
79
  "stripe": "18.3.0",
80
+ "@payloadcms/next": "3.69.0",
80
81
  "@payloadcms/eslint-config": "3.28.0",
81
- "@payloadcms/next": "3.69.0-internal.424436e",
82
- "payload": "3.69.0-internal.424436e"
82
+ "payload": "3.69.0"
83
83
  },
84
84
  "peerDependencies": {
85
85
  "react": "^19.0.1 || ^19.1.2 || ^19.2.1",
86
86
  "react-dom": "^19.0.1 || ^19.1.2 || ^19.2.1",
87
- "payload": "3.69.0-internal.424436e"
87
+ "payload": "3.69.0"
88
88
  },
89
89
  "publishConfig": {
90
90
  "registry": "https://registry.npmjs.org/"