@liquidcommerce/cloud-sdk 1.2.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -117,6 +117,9 @@ const searchResults = await client.catalog.search({
117
117
  The `cart` method allows you to manage shopping carts.
118
118
 
119
119
  ```javascript
120
+ // New Cart
121
+ const existingCart = await client.cart.get();
122
+
120
123
  // Get an existing cart
121
124
  const existingCart = await client.cart.get('existing_cart_id');
122
125
 
@@ -154,8 +157,8 @@ const userSession = await client.user.session({
154
157
  firstName: "John"
155
158
  });
156
159
 
157
- // Update user address
158
- const updatedAddress = await client.user.updateAddress({
160
+ // Add a new address for a user
161
+ const newAddress = await client.user.addAddress({
159
162
  customerId: 'c1fbd454-a540-4f42-86e9-f87a98bf1812',
160
163
  one: '100 Madison St',
161
164
  city: 'New York',
@@ -165,11 +168,38 @@ const updatedAddress = await client.user.updateAddress({
165
168
  isDefault: true
166
169
  });
167
170
 
168
- // Purge user data
171
+ // Update an existing address
172
+ const updatedAddress = await client.user.updateAddress({
173
+ customerId: 'c1fbd454-a540-4f42-86e9-f87a98bf1812',
174
+ one: '101 Madison St',
175
+ city: 'New York',
176
+ state: 'NY',
177
+ zip: '10004',
178
+ type: 'shipping',
179
+ isDefault: true
180
+ });
181
+
182
+ // Add a new payment method
183
+ const newPayment = await client.user.addPayment({
184
+ customerId: 'c1fbd454-a540-4f42-86e9-f87a98bf1812',
185
+ paymentMethodId: 'pm_1234567890abcdef',
186
+ isDefault: true
187
+ });
188
+
189
+ // Purge user data (by EMAIL)
169
190
  const purgeResponse = await client.user.purge('user@example.com');
170
191
 
192
+ // Purge user data (by ID)
193
+ const purgeResponse = await client.user.purge('c1fbd454-a540-4f42-86e9-f87a98bf1812');
194
+
171
195
  // Purge user address
172
196
  const addressPurgeResponse = await client.user.purgeAddress('26af8958-0deb-44ec-b9fd-ca150b198e45');
197
+
198
+ // Purge user payment method
199
+ const paymentPurgeResponse = await client.user.purgePayment(
200
+ 'c1fbd454-a540-4f42-86e9-f87a98bf1812',
201
+ 'pm_1234567890abcdef'
202
+ );
173
203
  ```
174
204
 
175
205
  ### Payment
@@ -195,6 +225,15 @@ client.payment.subscribe('change', (event) => {
195
225
 
196
226
  // Unsubscribe from payment events
197
227
  client.payment.unsubscribe('change');
228
+
229
+ // Collapse the payment element
230
+ client.payment.collapse();
231
+
232
+ // Unmount the payment element
233
+ client.payment.unmount();
234
+
235
+ // Destroy the payment element
236
+ client.payment.destroy();
198
237
  ```
199
238
 
200
239
  ### Checkout
package/dist/index.cjs CHANGED
@@ -1 +1 @@
1
- "use strict";var e,t,r,i,s,a,n,o,c,E,l,I,d,h,A,S,u,p,R,N=require("@stripe/stripe-js");exports.LIQUID_COMMERCE_ENV=void 0,(e=exports.LIQUID_COMMERCE_ENV||(exports.LIQUID_COMMERCE_ENV={})).LOC="loc",e.STAGE="stage",e.PROD="prod",e.DEV="dev",exports.ENUM_MODALITIES=void 0,(t=exports.ENUM_MODALITIES||(exports.ENUM_MODALITIES={})).ON_DEMAND="onDemand",t.SHIPPING="shipping",exports.DAYS_OF_WEEK=void 0,(r=exports.DAYS_OF_WEEK||(exports.DAYS_OF_WEEK={})).MONDAY="monday",r.TUESDAY="tuesday",r.WEDNESDAY="wednesday",r.THURSDAY="thursday",r.FRIDAY="friday",r.SATURDAY="saturday",r.SUNDAY="sunday",exports.STATES_CODE=void 0,(i=exports.STATES_CODE||(exports.STATES_CODE={})).AL="AL",i.AK="AK",i.AR="AR",i.CA="CA",i.CO="CO",i.CT="CT",i.DE="DE",i.DC="DC",i.FL="FL",i.GA="GA",i.HI="HI",i.ID="ID",i.IL="IL",i.IN="IN",i.IA="IA",i.KS="KS",i.KY="KY",i.LA="LA",i.ME="ME",i.MD="MD",i.MA="MA",i.MI="MI",i.MN="MN",i.MS="MS",i.MO="MO",i.MT="MT",i.NE="NE",i.NV="NV",i.NH="NH",i.NJ="NJ",i.NM="NM",i.NY="NY",i.NC="NC",i.ND="ND",i.OH="OH",i.OK="OK",i.OR="OR",i.PA="PA",i.RI="RI",i.SC="SC",i.SD="SD",i.TN="TN",i.TX="TX",i.UT="UT",i.VT="VT",i.VA="VA",i.WA="WA",i.WV="WV",i.WI="WI",i.WY="WY",exports.STATES_NAME=void 0,(s=exports.STATES_NAME||(exports.STATES_NAME={})).ALABAMA="AL",s.ALASKA="AK",s.ARKANSAS="AR",s.CALIFORNIA="CA",s.COLORADO="CO",s.CONNECTICUT="CT",s.DELAWARE="DE",s.DISTRICT_OF_COLUMBIA="DC",s.FLORIDA="FL",s.GEORGIA="GA",s.HAWAII="HI",s.IDAHO="ID",s.ILLINOIS="IL",s.INDIANA="IN",s.IOWA="IA",s.KANSAS="KS",s.KENTUCKY="KY",s.LOUISIANA="LA",s.MAINE="ME",s.MARYLAND="MD",s.MASSACHUSETTS="MA",s.MICHIGAN="MI",s.MINNESOTA="MN",s.MISSISSIPPI="MS",s.MISSOURI="MO",s.MONTANA="MT",s.NEBRASKA="NE",s.NEVADA="NV",s.NEW_HAMPSHIRE="NH",s.NEW_JERSEY="NJ",s.NEW_MEXICO="NM",s.NEW_YORK="NY",s.NORTH_CAROLINA="NC",s.NORTH_DAKOTA="ND",s.OHIO="OH",s.OKLAHOMA="OK",s.OREGON="OR",s.PENNSYLVANIA="PA",s.RHODE_ISLAND="RI",s.SOUTH_CAROLINA="SC",s.SOUTH_DAKOTA="SD",s.TENNESSEE="TN",s.TEXAS="TX",s.UTAH="UT",s.VERMONT="VT",s.VIRGINIA="VA",s.WASHINGTON="WA",s.WEST_VIRGINIA="WV",s.WISCONSIN="WI",s.WYOMING="WY",exports.ENUM_BEER=void 0,(a=exports.ENUM_BEER||(exports.ENUM_BEER={})).ALE="BEER > ALE",a.LAGER="BEER > LAGER",a.MAIN="BEER",a.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",a.OTHER_BEER="BEER > OTHER BEER",exports.ENUM_FOOD=void 0,(n=exports.ENUM_FOOD||(exports.ENUM_FOOD={})).BASE="FOOD",n.PANTRY_OTHER="FOOD > PANTRY > OTHER",exports.ENUM_MERCHANDISE=void 0,(o=exports.ENUM_MERCHANDISE||(exports.ENUM_MERCHANDISE={})).BASE="MERCHANDISE",o.GLASSWARE="MERCHANDISE > GLASSWARE",o.HUMIDOR="MERCHANDISE > HUMIDOR",exports.ENUM_MISCELLANEOUS=void 0,(c=exports.ENUM_MISCELLANEOUS||(exports.ENUM_MISCELLANEOUS={})).BASE="MISCELLANEOUS",c.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",c.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",c.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP",exports.ENUM_NON_ALCOHOLIC=void 0,(E=exports.ENUM_NON_ALCOHOLIC||(exports.ENUM_NON_ALCOHOLIC={})).BASE="NON ALCOHOLIC",E.BITTERS="NON ALCOHOLIC > BITTERS",E.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",E.COFFEE="NON ALCOHOLIC > COFFEE",E.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",E.JUICE="NON ALCOHOLIC > JUICE",E.SODA="NON ALCOHOLIC > SODA",E.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",E.SPIRITS="NON ALCOHOLIC > SPIRITS",E.TEA="NON ALCOHOLIC > TEA",E.WATER="NON ALCOHOLIC > WATER",E.WINE="NON ALCOHOLIC > WINE",exports.ENUM_READY_TO_DRINK=void 0,(l=exports.ENUM_READY_TO_DRINK||(exports.ENUM_READY_TO_DRINK={})).BASE="READY TO DRINK",l.HARD_CIDER="READY TO DRINK > HARD CIDER",l.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",l.HARD_TEA="READY TO DRINK > HARD TEA",l.MALT_BASED="READY TO DRINK > MALT BASED",l.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",l.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",l.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",l.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",l.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",l.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS",exports.ENUM_SPIRITS=void 0,(I=exports.ENUM_SPIRITS||(exports.ENUM_SPIRITS={})).BASE="SPIRITS",I.BAIJIU="SPIRITS > BAIJIU",I.BITTERS="SPIRITS > BITTERS",I.BRANDY="SPIRITS > BRANDY",I.CACHACA="SPIRITS > CACHACA",I.GIN="SPIRITS > GIN",I.LAGER="SPIRITS > LAGER",I.LIQUEUR="SPIRITS > LIQUEUR",I.MEZCAL="SPIRITS > MEZCAL",I.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",I.RUM="SPIRITS > RUM",I.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",I.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",I.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",I.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",I.RUM_OTHER="SPIRITS > RUM > OTHER",I.RUM_SPICED="SPIRITS > RUM > SPICED",I.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",I.SOJU="SPIRITS > SOJU",I.TEQUILA="SPIRITS > TEQUILA",I.VODKA="SPIRITS > VODKA",I.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",I.WHISKEY="SPIRITS > WHISKEY",I.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",I.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",I.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",I.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",I.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH",exports.ENUM_WINE=void 0,(d=exports.ENUM_WINE||(exports.ENUM_WINE={})).BASE="WINE",d.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",d.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",d.COOKING="WINE > COOKING",d.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",d.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",d.RED_WINE="WINE > RED WINE",d.ROSE_WINE="WINE > ROSE WINE",d.SAKE="WINE > SAKE",d.WHITE_WINE="WINE > WHITE WINE",exports.ENUM_FILTER_KEYS=void 0,(h=exports.ENUM_FILTER_KEYS||(exports.ENUM_FILTER_KEYS={})).BRANDS="brands",h.FLAVOR="flavor",h.REGION="region",h.VARIETY="variety",h.PRICE="price",h.AVAILABILITY="availability",h.CATEGORIES="categories",h.SIZES="sizes",h.COLORS="colors",h.APPELLATION="appellation",h.COUNTRY="country",h.VINTAGE="vintage",h.MATERIALS="materials",exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE=void 0,(A=exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE||(exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE={})).ASC="asc",A.DESC="desc",exports.ENUM_ORDER_BY=void 0,(exports.ENUM_ORDER_BY||(exports.ENUM_ORDER_BY={})).PRICE="price",exports.ENUM_AVAILABILITY_VALUE=void 0,(S=exports.ENUM_AVAILABILITY_VALUE||(exports.ENUM_AVAILABILITY_VALUE={})).UNSPECIFIED="AVAILABILITY_UNSPECIFIED",S.IN_STOCK="IN_STOCK",S.OUT_OF_STOCK="OUT_OF_STOCK",S.PREORDER="PREORDER",S.BACKORDER="BACKORDER",exports.CART_PARAM_ERROR_ENUM=void 0,(u=exports.CART_PARAM_ERROR_ENUM||(exports.CART_PARAM_ERROR_ENUM={})).INVALID_ITEMS_TYPE="Items must be a non-empty array",u.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",u.INVALID_PART_NUMBER="The partnerNumber provided is invalid",u.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid",exports.CART_EVENT_ENUM=void 0,(p=exports.CART_EVENT_ENUM||(exports.CART_EVENT_ENUM={})).OOS="OutOfStock",p.ITEMS_NOT_ADDED="ItemsNotAdded",p.ITEMS_REQUESTED_NOT_ADDED="ItemsRequestedNotAdded",p.ITEM_NOT_ENGRAVED="ItemEngravingError",p.ADDRESS_CHANGE="AddressChange",p.LOCATION_AVAILABILITY="LocationAvailability",p.REMOVED_EXISTING_ITEMS="RemovedExistingCartItems",p.RETAILER_MIN="RetailerMinNotMet",p.NO_ITEMS_IN_CART="NoItemsInCart",p.INVALID_ID="InvalidId",p.NO_ID="NoId",p.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",p.NEW_CART="NewCart",p.DEFAULT="CartError",p.ITEM_QTY_CHANGE="ItemQuantityChange",exports.ENUM_ADDRESS_TYPE=void 0,(R=exports.ENUM_ADDRESS_TYPE||(exports.ENUM_ADDRESS_TYPE={})).SHIPPING="shipping",R.BILLING="billing";const O={[exports.LIQUID_COMMERCE_ENV.LOC]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.DEV]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.STAGE]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.PROD]:"https://staging.cloud.liquidcommerce.co/api"};class T{constructor(e){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(e,t)=>new Promise(((r,i)=>{const s=new XMLHttpRequest;s.open(t.method||"GET",e),Object.entries(t.headers).forEach((([e,t])=>{s.setRequestHeader(e,t)})),s.onload=()=>{r({ok:s.status>=200&&s.status<300,status:s.status,statusText:s.statusText,headers:s.getAllResponseHeaders().split("\r\n").reduce(((e,t)=>{const[r,i]=t.split(": ");return r&&(e[r]=i),e}),{}),json:()=>Promise.resolve(JSON.parse(s.responseText)),text:()=>Promise.resolve(s.responseText)})},s.onerror=()=>{i(new TypeError("Network request failed"))},s.send(t.body)})),this.apiKey=e.apiKey,this.baseURL=e.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(e){return T.instance||(T.instance=new T(e)),T.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):"undefined"!=typeof window&&window.fetch?this.fetchAdapter(window.fetch):this.xhrFetch}fetchAdapter(e){return async(t,r)=>{var i;const s=await e(t,r);let a;return"function"==typeof(null===(i=s.headers)||void 0===i?void 0:i.entries)?a=Object.fromEntries(s.headers.entries()):(a={},s.headers.forEach(((e,t)=>{a[t]=e}))),{ok:s.ok,status:s.status,statusText:s.statusText,headers:a,json:()=>s.json(),text:()=>s.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var e,t;if(this.isAuthenticating)await new Promise((e=>{const t=()=>{this.isAuthenticating?setTimeout(t,100):e(void 0)};t()}));else{this.isAuthenticating=!0;try{const r=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(e=null==r?void 0:r.data)||void 0===e?void 0:e.token,this.tokenExpiration=Date.now()+1e3*(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.exp)}catch(e){throw console.error("Authentication failed:",e),new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(e,t){const r=new URL(`api${e}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...t.headers},s={method:t.method,headers:i,body:t.body?JSON.stringify(t.body):void 0},a=await this.httpClient(r.toString(),s);if(!a.ok)throw new Error(`HTTP error! status: ${a.status}`);return a.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(e,t){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const r=new URL(`api${e}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...t.headers},s={method:t.method,headers:i,body:t.body?JSON.stringify(t.body):void 0},a=await this.httpClient(r.toString(),s);if(!a.ok)throw new Error(`HTTP error! status: ${a.status}`);return a.json()}async get(e,t){return this.request(e,{method:"GET",headers:t})}async post(e,t,r){return this.request(e,{method:"POST",body:t,headers:r})}async put(e,t,r){return this.request(e,{method:"PUT",body:t,headers:r})}async delete(e,t){return this.request(e,{method:"DELETE",headers:t})}}T.instance=null;class v{constructor(e){this.locationHelperService=e}validateAndNormalizeParams(e){const t={...e};return t.id=this.validateId(t.id),t.items=this.validateAndNormalizeItems(t.items),this.locationHelperService.validateAndNormalizeLocation(t.loc),t.refresh=Boolean(t.refresh),t}validateId(e){return e&&"string"==typeof e&&0!==e.trim().length?e.trim():""}validateAndNormalizeItems(e){if(!Array.isArray(e)||0===e.length)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_ITEMS_TYPE);if(e.length>25)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_ITEMS_MAX);return e.map((e=>this.validateAndNormalizeItem(e)))}validateAndNormalizeItem(e){const t={...e};if(!this.validatePartNumber(t.partNumber))throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_PART_NUMBER);if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId||0===t.fulfillmentId.trim().length)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_FULFILLMENT_ID);return t.quantity=Math.max(0,Math.floor(t.quantity)),t.engravingLines&&(t.engravingLines=t.engravingLines.map((e=>e.trim())).filter((e=>e.length>0))),t}validatePartNumber(e){if(!e||"string"!=typeof e)return!1;const t=e.split("_");return 2===t.length&&14===t[0].length&&t[1].length>0}}class C{constructor(e){this.locationServiceHelper=e,this.taxonomyValues=new Set([...Object.values(exports.ENUM_BEER),...Object.values(exports.ENUM_FOOD),...Object.values(exports.ENUM_MERCHANDISE),...Object.values(exports.ENUM_NON_ALCOHOLIC),...Object.values(exports.ENUM_READY_TO_DRINK),...Object.values(exports.ENUM_SPIRITS),...Object.values(exports.ENUM_WINE)])}validateAndNormalizeParams(e){const t={...e};return this.validateUPCs(t.upcs),this.locationServiceHelper.validateAndNormalizeLocation(t.loc),t}validateAndNormalizeSearchParams(e){const t=[],r={...e};return this.validateOrderBy(r.orderBy,t),this.validateOrderDirection(r.orderDirection,t),this.validateFilters(r.filters,t),this.validatePagination(r.page,r.perPage,t),this.locationServiceHelper.validateAndNormalizeLocation(r.loc),t.length>0?{...r,error:t.join(". ")}:r}validateUPCs(e){if(!Array.isArray(e)||0===e.length)throw new Error("UPCs must be a non-empty array of strings");if(!e.every((e=>"string"==typeof e&&e.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(e,t){e&&!Object.values(exports.ENUM_ORDER_BY).includes(e)&&t.push(`Invalid orderBy value: ${e}`)}validateOrderDirection(e,t){e&&!Object.values(exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE).includes(e)&&t.push(`Invalid orderDirection value: ${e}`)}validateFilters(e,t){e&&(e.length>10&&t.push("Maximum of 10 filters allowed"),e.forEach((e=>{switch(Object.values(exports.ENUM_FILTER_KEYS).includes(e.key)||t.push(`Invalid filter key: ${e.key}`),e.key){case exports.ENUM_FILTER_KEYS.AVAILABILITY:this.validateAvailabilityFilter(e.values,t);break;case exports.ENUM_FILTER_KEYS.BRANDS:this.validateArrayFilter(e.values,30,"brands",t);break;case exports.ENUM_FILTER_KEYS.CATEGORIES:this.validateCategoriesFilter(e.values,t);break;case exports.ENUM_FILTER_KEYS.COLORS:this.validateArrayFilter(e.values,75,"colors",t)}})))}validateAvailabilityFilter(e,t){Object.values(exports.ENUM_AVAILABILITY_VALUE).includes(e)||t.push(`Invalid availability value: ${e}`)}validateArrayFilter(e,t,r,i){Array.isArray(e)?e.length>t&&i.push(`${r} filter can have a maximum of ${t} values`):i.push(`${r} filter must be an array`)}validateCategoriesFilter(e,t){Array.isArray(e)?e.every((e=>this.taxonomyValues.has(e)))||t.push("Invalid category value(s) in categories filter"):t.push("Categories filter must be an array")}validatePagination(e,t,r){void 0!==e&&("number"!=typeof e||e<0)&&r.push("Page must be a non-negative number"),void 0!==t&&("number"!=typeof t||t<=0)&&r.push("PerPage must be a positive number")}}class _{constructor(e){this.locationHelperService=e}validateAndNormalizePrepareParams(e){const t={...e};if(!t.cartId||"string"!=typeof t.cartId)throw new Error("Invalid cartId");return this.validateRecipient(t.recipient),t.billingAddress&&this.validateAddress(t.billingAddress),t.hasSubstitutionPolicy=Boolean(t.hasSubstitutionPolicy),t.isGift=Boolean(t.isGift),t.billingSameAsShipping=Boolean(t.billingSameAsShipping),t.isGift&&this.validateGiftOptions(t.giftOptions),this.validateMarketingPreferences(t.marketingPreferences),t.deliveryTips&&this.validateDeliveryTips(t.deliveryTips),t.refresh=Boolean(t.refresh),t}validateAndNormalizeCompleteParams(e){const t={...e};if(!t.token||"string"!=typeof t.token)throw new Error("Invalid token");if(!t.payment||"string"!=typeof t.payment)throw new Error("Invalid payment token");return void 0!==t.refresh&&(t.refresh=Boolean(t.refresh)),t}validateRecipient(e){if(!e||"object"!=typeof e)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid recipient ${t}`)})),e.hasAgeVerify=Boolean(e.hasAgeVerify)}validateAddress(e){if(!e||"object"!=typeof e)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid address ${t}`)})),this.locationHelperService.validateAndNormalizeLocation({address:e})}validateGiftOptions(e){if(!e||"object"!=typeof e)throw new Error("Invalid giftOptions");if(e.message&&"string"!=typeof e.message)throw new Error("Invalid gift message");if(e.recipient){const{name:t,phone:r,email:i}=e.recipient;if(t&&"string"!=typeof t)throw new Error("Invalid gift recipient name");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient phone");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(e){if(!e||"object"!=typeof e)throw new Error("Invalid marketingPreferences");e.canEmail=Boolean(e.canEmail),e.canSms=Boolean(e.canSms)}validateDeliveryTips(e){if(!Array.isArray(e))throw new Error("Invalid deliveryTips");e.forEach((e=>{if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof e.tip||e.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class m{validateAndNormalizeLocation(e){if(!e||"object"!=typeof e)throw new Error("Location must be a valid object");if(e.coords)this.validateCoordinates(e.coords);else{if(!e.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(e.address)}}validateCoordinates(e){if("number"!=typeof e.lat||"number"!=typeof e.long)throw new Error("Coordinates must be valid numbers");if(e.lat<-90||e.lat>90||e.long<-180||e.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(e){if(!e.state||"string"!=typeof e.state)throw new Error("State is required and must be a string");if(e.state=this.normalizeState(e.state),!e.city||"string"!=typeof e.city)throw new Error("City is required and must be a string");if(!e.zip||"string"!=typeof e.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(e){const t=e.toUpperCase();if(exports.STATES_CODE[t])return exports.STATES_CODE[t];const r=e.toUpperCase();if(exports.STATES_NAME[r])return exports.STATES_NAME[r];throw new Error(`Invalid state: ${e}`)}}class y{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)"}async mount(e){if(!document.getElementById(e.elementId))throw new Error(`Element with id "${e.elementId}" not found`);try{this.stripe=await N.loadStripe(e.key)}catch(e){throw console.error("Failed to load Stripe:",e),new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");const t={clientSecret:e.clientSecret,appearance:this.mapAppearance(e.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(t);const r=this.mapElementOptions(e.elementOptions);this.paymentElement=this.elements.create("payment",r),this.paymentElement.mount(`#${e.elementId}`)}async generateToken(){var e,t,r,i,s,a,n,o;if(!this.stripe||!this.elements)return{type:"client_error",message:"Payment form has not been initialized"};const{error:c}=await this.elements.submit();if(c)return{type:"validation_error",message:c.message,code:c.code};const{error:E,paymentMethod:l}=await this.stripe.createPaymentMethod({elements:this.elements});return E?{type:"validation_error"===E.type?"validation_error":"api_error",message:E.message,code:E.code,param:E.param}:l?{id:l.id,type:l.type,card:(null==l?void 0:l.card)?{brand:null!==(t=null===(e=l.card)||void 0===e?void 0:e.brand)&&void 0!==t?t:"",country:null!==(r=l.card.country)&&void 0!==r?r:"",expMonth:null!==(i=l.card.exp_month)&&void 0!==i?i:0,expYear:null!==(s=l.card.exp_year)&&void 0!==s?s:0,last4:null!==(a=l.card.last4)&&void 0!==a?a:"",funding:null!==(n=l.card.funding)&&void 0!==n?n:""}:void 0,created:null!==(o=null==l?void 0:l.created)&&void 0!==o?o:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.on(e,t)}unsubscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.off(e,t)}mapAppearance(e){if(e)return{theme:"night"===e.theme?"night":"stripe"}}mapElementOptions(e){return{layout:null==e?void 0:e.layout,wallets:{applePay:"auto",googlePay:"auto"}}}}class M{constructor(e){this.client=e}async autocomplete(e,t){try{return await this.client.post("/address/autocomplete",{...e,key:t})}catch(e){throw console.error("Address autocomplete request failed:",e),e}}async details(e,t){try{return await this.client.post("/address/details",{...e,key:t})}catch(e){throw console.error("Address details request failed:",e),e}}}class D{constructor(e,t){this.client=e,this.cartHelperService=t,this.servicePath="/cart/update"}async get(e,t){try{let r=this.cartHelperService.validateId(e);if(r=""!==r&&r,r){const e={id:r};return"boolean"==typeof t&&(e.refresh=t),await this.client.post(this.servicePath,e)}return await this.client.post(this.servicePath)}catch(e){throw console.error("Cart update request failed:",e),e}}async update(e){try{const t=this.cartHelperService.validateAndNormalizeParams(e);return await this.client.post(this.servicePath,t)}catch(e){throw console.error("Cart update request failed:",e),e}}}class g{constructor(e,t){this.client=e,this.catalogHelperService=t,this.servicePath="/catalog/"}async availability(e){try{const t=this.catalogHelperService.validateAndNormalizeParams(e);return await this.client.post(`${this.servicePath}availability`,t)}catch(e){throw console.error("Catalog availability request failed:",e),e}}async search(e){try{const t=this.catalogHelperService.validateAndNormalizeSearchParams(e);if(null==t?void 0:t.error)throw new Error(null==t?void 0:t.error);return await this.client.post(`${this.servicePath}search`,t)}catch(e){throw console.error("Catalog search request failed:",e),e}}}class L{constructor(e,t){this.client=e,this.checkoutHelperService=t,this.servicePath="/checkout"}async prepare(e){try{const t=this.checkoutHelperService.validateAndNormalizePrepareParams(e);return await this.client.post(`${this.servicePath}/prepare`,t)}catch(e){throw console.error("Checkout prepare request failed:",e),e}}async complete(e){try{const t=this.checkoutHelperService.validateAndNormalizeCompleteParams(e);return await this.client.post(`${this.servicePath}/complete`,t)}catch(e){throw console.error("Checkout complete request failed:",e),e}}}class f{constructor(e){this.paymentProvider=e}async mount(e){try{await this.paymentProvider.mount(e)}catch(e){throw console.error("Failed to inject payment element:",e),e}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(e,t){this.paymentProvider.subscribe(e,t)}unsubscribe(e,t){this.paymentProvider.unsubscribe(e,t)}}class U{constructor(e){this.client=e,this.servicePath="/users"}async createOrUpdateSession(e){try{if(!(null==e?void 0:e.id)&&!(null==e?void 0:e.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,e)}catch(e){throw console.error("User session creation/update request failed:",e),e}}async purge(e){try{if(!e)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${e}`)}catch(e){throw console.error("User purge request failed:",e),e}}async updateAddress(e){try{if(!(e.customerId&&e.one&&e.city&&e.state&&e.zip&&e.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,e)}catch(e){throw console.error("User address update request failed:",e),e}}async purgeAddress(e){try{if(!e)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${e}`)}catch(e){throw console.error("Address purge request failed:",e),e}}}class P{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return P.instance||(P.instance=new P),P.instance}setLiquidCommerceClientConstructor(e){this.liquidCommerceClientConstructor=e}async getLiquidCommerceClient(e,t){const r=`LiquidCommerceClient_${e}_${JSON.stringify(t)}`;if(!this.services.has(r)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const i=new this.liquidCommerceClientConstructor(e,t);await i.init(),this.services.set(r,i)}return this.services.get(r)}getOrCreateService(e,t,...r){if(!this.services.has(e)){const i="getInstance"in t?t.getInstance(...r):new t(...r);this.services.set(e,i)}return this.services.get(e)}getAuthenticatedClient(e){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(e)}`,T,e)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",m)}getAddressService(e){return this.getOrCreateService(`AddressService_${e.getUniqueKey()}`,M,e)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",C,this.getLocationHelperService())}getCatalogService(e){return this.getOrCreateService(`CatalogService_${e.getUniqueKey()}`,g,e,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",v,this.getLocationHelperService())}getCartService(e){return this.getOrCreateService(`CartService_${e.getUniqueKey()}`,D,e,this.getCartHelperService())}getUserService(e){return this.getOrCreateService(`UserService_${e.getUniqueKey()}`,U,e)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",y)}getPaymentService(){return this.getOrCreateService("PaymentService",f,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",_,this.getLocationHelperService())}getCheckoutService(e){return this.getOrCreateService(`CheckoutService_${e.getUniqueKey()}`,L,e,this.getCheckoutHelperService())}}P.instance=null;class w{constructor(e,t){this.address={autocomplete:async e=>(await this.ensureAuthenticated(),this.addressService.autocomplete(e,this.config.googlePlacesApiKey)),details:async e=>(await this.ensureAuthenticated(),this.addressService.details(e,this.config.googlePlacesApiKey))},this.catalog={availability:async e=>(await this.ensureAuthenticated(),this.catalogService.availability(e)),search:async e=>(await this.ensureAuthenticated(),this.catalogService.search(e))},this.cart={get:async(e,t)=>(await this.ensureAuthenticated(),this.cartService.get(e,t)),update:async e=>(await this.ensureAuthenticated(),this.cartService.update(e))},this.user={session:async e=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(e)),purge:async e=>(await this.ensureAuthenticated(),this.userService.purge(e)),updateAddress:async e=>(await this.ensureAuthenticated(),this.userService.updateAddress(e)),purgeAddress:async e=>(await this.ensureAuthenticated(),this.userService.purgeAddress(e))},this.payment={mount:async e=>(await this.ensureAuthenticated(),this.paymentService.mount(e)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(e,t)=>{this.paymentService.subscribe(e,t)},unsubscribe:(e,t)=>{this.paymentService.unsubscribe(e,t)}},this.checkout={prepare:async e=>(await this.ensureAuthenticated(),this.checkoutService.prepare(e)),complete:async e=>(await this.ensureAuthenticated(),this.checkoutService.complete(e))},this.config=t,this.singletonManager=P.getInstance();const r=this.determineBaseURL(t);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:e,baseURL:r}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(e){const t=e.env||exports.LIQUID_COMMERCE_ENV.STAGE;return O[t]}async init(){try{await this.authenticatedClient.authenticate()}catch(e){throw console.error("Failed to initialize LiquidCommerceClient:",e),new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}exports.LiquidCommerce=async function(e,t){const r=P.getInstance();return r.setLiquidCommerceClientConstructor(w),await r.getLiquidCommerceClient(e,t)};
1
+ "use strict";var e,t,r,i,s,a,n,o,c,l,E,d,h,I,A,u,S,p,R,N=require("@stripe/stripe-js");exports.LIQUID_COMMERCE_ENV=void 0,(e=exports.LIQUID_COMMERCE_ENV||(exports.LIQUID_COMMERCE_ENV={})).LOC="loc",e.STAGE="stage",e.PROD="prod",e.DEV="dev",exports.ENUM_MODALITIES=void 0,(t=exports.ENUM_MODALITIES||(exports.ENUM_MODALITIES={})).ON_DEMAND="onDemand",t.SHIPPING="shipping",exports.DAYS_OF_WEEK=void 0,(r=exports.DAYS_OF_WEEK||(exports.DAYS_OF_WEEK={})).MONDAY="monday",r.TUESDAY="tuesday",r.WEDNESDAY="wednesday",r.THURSDAY="thursday",r.FRIDAY="friday",r.SATURDAY="saturday",r.SUNDAY="sunday",exports.STATES_CODE=void 0,(i=exports.STATES_CODE||(exports.STATES_CODE={})).AL="AL",i.AK="AK",i.AR="AR",i.CA="CA",i.CO="CO",i.CT="CT",i.DE="DE",i.DC="DC",i.FL="FL",i.GA="GA",i.HI="HI",i.ID="ID",i.IL="IL",i.IN="IN",i.IA="IA",i.KS="KS",i.KY="KY",i.LA="LA",i.ME="ME",i.MD="MD",i.MA="MA",i.MI="MI",i.MN="MN",i.MS="MS",i.MO="MO",i.MT="MT",i.NE="NE",i.NV="NV",i.NH="NH",i.NJ="NJ",i.NM="NM",i.NY="NY",i.NC="NC",i.ND="ND",i.OH="OH",i.OK="OK",i.OR="OR",i.PA="PA",i.RI="RI",i.SC="SC",i.SD="SD",i.TN="TN",i.TX="TX",i.UT="UT",i.VT="VT",i.VA="VA",i.WA="WA",i.WV="WV",i.WI="WI",i.WY="WY",exports.STATES_NAME=void 0,(s=exports.STATES_NAME||(exports.STATES_NAME={})).ALABAMA="AL",s.ALASKA="AK",s.ARKANSAS="AR",s.CALIFORNIA="CA",s.COLORADO="CO",s.CONNECTICUT="CT",s.DELAWARE="DE",s.DISTRICT_OF_COLUMBIA="DC",s.FLORIDA="FL",s.GEORGIA="GA",s.HAWAII="HI",s.IDAHO="ID",s.ILLINOIS="IL",s.INDIANA="IN",s.IOWA="IA",s.KANSAS="KS",s.KENTUCKY="KY",s.LOUISIANA="LA",s.MAINE="ME",s.MARYLAND="MD",s.MASSACHUSETTS="MA",s.MICHIGAN="MI",s.MINNESOTA="MN",s.MISSISSIPPI="MS",s.MISSOURI="MO",s.MONTANA="MT",s.NEBRASKA="NE",s.NEVADA="NV",s.NEW_HAMPSHIRE="NH",s.NEW_JERSEY="NJ",s.NEW_MEXICO="NM",s.NEW_YORK="NY",s.NORTH_CAROLINA="NC",s.NORTH_DAKOTA="ND",s.OHIO="OH",s.OKLAHOMA="OK",s.OREGON="OR",s.PENNSYLVANIA="PA",s.RHODE_ISLAND="RI",s.SOUTH_CAROLINA="SC",s.SOUTH_DAKOTA="SD",s.TENNESSEE="TN",s.TEXAS="TX",s.UTAH="UT",s.VERMONT="VT",s.VIRGINIA="VA",s.WASHINGTON="WA",s.WEST_VIRGINIA="WV",s.WISCONSIN="WI",s.WYOMING="WY",exports.ENUM_BEER=void 0,(a=exports.ENUM_BEER||(exports.ENUM_BEER={})).ALE="BEER > ALE",a.LAGER="BEER > LAGER",a.MAIN="BEER",a.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",a.OTHER_BEER="BEER > OTHER BEER",exports.ENUM_FOOD=void 0,(n=exports.ENUM_FOOD||(exports.ENUM_FOOD={})).BASE="FOOD",n.PANTRY_OTHER="FOOD > PANTRY > OTHER",exports.ENUM_MERCHANDISE=void 0,(o=exports.ENUM_MERCHANDISE||(exports.ENUM_MERCHANDISE={})).BASE="MERCHANDISE",o.GLASSWARE="MERCHANDISE > GLASSWARE",o.HUMIDOR="MERCHANDISE > HUMIDOR",exports.ENUM_MISCELLANEOUS=void 0,(c=exports.ENUM_MISCELLANEOUS||(exports.ENUM_MISCELLANEOUS={})).BASE="MISCELLANEOUS",c.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",c.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",c.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP",exports.ENUM_NON_ALCOHOLIC=void 0,(l=exports.ENUM_NON_ALCOHOLIC||(exports.ENUM_NON_ALCOHOLIC={})).BASE="NON ALCOHOLIC",l.BITTERS="NON ALCOHOLIC > BITTERS",l.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",l.COFFEE="NON ALCOHOLIC > COFFEE",l.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",l.JUICE="NON ALCOHOLIC > JUICE",l.SODA="NON ALCOHOLIC > SODA",l.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",l.SPIRITS="NON ALCOHOLIC > SPIRITS",l.TEA="NON ALCOHOLIC > TEA",l.WATER="NON ALCOHOLIC > WATER",l.WINE="NON ALCOHOLIC > WINE",exports.ENUM_READY_TO_DRINK=void 0,(E=exports.ENUM_READY_TO_DRINK||(exports.ENUM_READY_TO_DRINK={})).BASE="READY TO DRINK",E.HARD_CIDER="READY TO DRINK > HARD CIDER",E.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",E.HARD_TEA="READY TO DRINK > HARD TEA",E.MALT_BASED="READY TO DRINK > MALT BASED",E.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",E.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",E.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",E.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",E.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",E.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS",exports.ENUM_SPIRITS=void 0,(d=exports.ENUM_SPIRITS||(exports.ENUM_SPIRITS={})).BASE="SPIRITS",d.BAIJIU="SPIRITS > BAIJIU",d.BITTERS="SPIRITS > BITTERS",d.BRANDY="SPIRITS > BRANDY",d.CACHACA="SPIRITS > CACHACA",d.GIN="SPIRITS > GIN",d.LAGER="SPIRITS > LAGER",d.LIQUEUR="SPIRITS > LIQUEUR",d.MEZCAL="SPIRITS > MEZCAL",d.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",d.RUM="SPIRITS > RUM",d.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",d.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",d.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",d.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",d.RUM_OTHER="SPIRITS > RUM > OTHER",d.RUM_SPICED="SPIRITS > RUM > SPICED",d.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",d.SOJU="SPIRITS > SOJU",d.TEQUILA="SPIRITS > TEQUILA",d.VODKA="SPIRITS > VODKA",d.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",d.WHISKEY="SPIRITS > WHISKEY",d.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",d.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",d.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",d.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",d.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH",exports.ENUM_WINE=void 0,(h=exports.ENUM_WINE||(exports.ENUM_WINE={})).BASE="WINE",h.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",h.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",h.COOKING="WINE > COOKING",h.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",h.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",h.RED_WINE="WINE > RED WINE",h.ROSE_WINE="WINE > ROSE WINE",h.SAKE="WINE > SAKE",h.WHITE_WINE="WINE > WHITE WINE",exports.ENUM_FILTER_KEYS=void 0,(I=exports.ENUM_FILTER_KEYS||(exports.ENUM_FILTER_KEYS={})).BRANDS="brands",I.FLAVOR="flavor",I.REGION="region",I.VARIETY="variety",I.PRICE="price",I.AVAILABILITY="availability",I.CATEGORIES="categories",I.SIZES="sizes",I.COLORS="colors",I.APPELLATION="appellation",I.COUNTRY="country",I.VINTAGE="vintage",I.MATERIALS="materials",exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE=void 0,(A=exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE||(exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE={})).ASC="asc",A.DESC="desc",exports.ENUM_ORDER_BY=void 0,(exports.ENUM_ORDER_BY||(exports.ENUM_ORDER_BY={})).PRICE="price",exports.ENUM_AVAILABILITY_VALUE=void 0,(u=exports.ENUM_AVAILABILITY_VALUE||(exports.ENUM_AVAILABILITY_VALUE={})).UNSPECIFIED="AVAILABILITY_UNSPECIFIED",u.IN_STOCK="IN_STOCK",u.OUT_OF_STOCK="OUT_OF_STOCK",u.PREORDER="PREORDER",u.BACKORDER="BACKORDER",exports.CART_PARAM_ERROR_ENUM=void 0,(S=exports.CART_PARAM_ERROR_ENUM||(exports.CART_PARAM_ERROR_ENUM={})).INVALID_ITEMS_TYPE="Items must be a non-empty array",S.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",S.INVALID_PART_NUMBER="The partnerNumber provided is invalid",S.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid",exports.CART_EVENT_ENUM=void 0,(p=exports.CART_EVENT_ENUM||(exports.CART_EVENT_ENUM={})).OOS="OutOfStock",p.ITEMS_NOT_ADDED="ItemsNotAdded",p.ITEMS_REQUESTED_NOT_ADDED="ItemsRequestedNotAdded",p.ITEM_NOT_ENGRAVED="ItemEngravingError",p.ADDRESS_CHANGE="AddressChange",p.LOCATION_AVAILABILITY="LocationAvailability",p.REMOVED_EXISTING_ITEMS="RemovedExistingCartItems",p.RETAILER_MIN="RetailerMinNotMet",p.NO_ITEMS_IN_CART="NoItemsInCart",p.INVALID_ID="InvalidId",p.NO_ID="NoId",p.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",p.NEW_CART="NewCart",p.DEFAULT="CartError",p.ITEM_QTY_CHANGE="ItemQuantityChange",exports.ENUM_ADDRESS_TYPE=void 0,(R=exports.ENUM_ADDRESS_TYPE||(exports.ENUM_ADDRESS_TYPE={})).SHIPPING="shipping",R.BILLING="billing";const v={[exports.LIQUID_COMMERCE_ENV.LOC]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.DEV]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.STAGE]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.PROD]:"https://staging.cloud.liquidcommerce.co/api"};class m{constructor(e){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(e,t)=>new Promise(((r,i)=>{const s=new XMLHttpRequest;s.open(t.method||"GET",e),Object.entries(t.headers).forEach((([e,t])=>{s.setRequestHeader(e,t)})),s.onload=()=>{r({ok:s.status>=200&&s.status<300,status:s.status,statusText:s.statusText,headers:s.getAllResponseHeaders().split("\r\n").reduce(((e,t)=>{const[r,i]=t.split(": ");return r&&(e[r]=i),e}),{}),json:()=>Promise.resolve(JSON.parse(s.responseText)),text:()=>Promise.resolve(s.responseText)})},s.onerror=()=>{i(new TypeError("Network request failed"))},s.send(t.body)})),this.apiKey=e.apiKey,this.baseURL=e.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(e){return m.instance||(m.instance=new m(e)),m.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):"undefined"!=typeof window&&window.fetch?this.fetchAdapter(window.fetch):this.xhrFetch}fetchAdapter(e){return async(t,r)=>{var i;const s=await e(t,r);let a;return"function"==typeof(null===(i=s.headers)||void 0===i?void 0:i.entries)?a=Object.fromEntries(s.headers.entries()):(a={},s.headers.forEach(((e,t)=>{a[t]=e}))),{ok:s.ok,status:s.status,statusText:s.statusText,headers:a,json:()=>s.json(),text:()=>s.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var e,t;if(this.isAuthenticating)await new Promise((e=>{const t=()=>{this.isAuthenticating?setTimeout(t,100):e(void 0)};t()}));else{this.isAuthenticating=!0;try{const r=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(e=null==r?void 0:r.data)||void 0===e?void 0:e.token,this.tokenExpiration=Date.now()+1e3*(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.exp)}catch(e){throw console.error("Authentication failed:",e),new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(e,t){const r=new URL(`api${e}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...t.headers},s={method:t.method,headers:i,body:t.body?JSON.stringify(t.body):void 0},a=await this.httpClient(r.toString(),s);if(!a.ok)throw new Error(`HTTP error! status: ${a.status}`);return a.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(e,t){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const r=new URL(`api${e}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...t.headers},s={method:t.method,headers:i,body:t.body?JSON.stringify(t.body):void 0},a=await this.httpClient(r.toString(),s);if(!a.ok)throw new Error(`HTTP error! status: ${a.status}`);return a.json()}async get(e,t){return this.request(e,{method:"GET",headers:t})}async post(e,t,r){return this.request(e,{method:"POST",body:t,headers:r})}async put(e,t,r){return this.request(e,{method:"PUT",body:t,headers:r})}async delete(e,t){return this.request(e,{method:"DELETE",headers:t})}}m.instance=null;class O{constructor(e){this.locationHelperService=e}validateAndNormalizeParams(e){const t={...e};return t.id=this.validateId(t.id),t.items=this.validateAndNormalizeItems(t.items),this.locationHelperService.validateAndNormalizeLocation(t.loc),t.refresh=Boolean(t.refresh),t}validateId(e){return e&&"string"==typeof e&&0!==e.trim().length?e.trim():""}validateAndNormalizeItems(e){if(!Array.isArray(e)||0===e.length)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_ITEMS_TYPE);if(e.length>25)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_ITEMS_MAX);return e.map((e=>this.validateAndNormalizeItem(e)))}validateAndNormalizeItem(e){const t={...e};if(!this.validatePartNumber(t.partNumber))throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_PART_NUMBER);if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId||0===t.fulfillmentId.trim().length)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_FULFILLMENT_ID);return t.quantity=Math.max(0,Math.floor(t.quantity)),t.engravingLines&&(t.engravingLines=t.engravingLines.map((e=>e.trim())).filter((e=>e.length>0))),t}validatePartNumber(e){if(!e||"string"!=typeof e)return!1;const t=e.split("_");return 2===t.length&&14===t[0].length&&t[1].length>0}}class T{constructor(e){this.locationServiceHelper=e,this.taxonomyValues=new Set([...Object.values(exports.ENUM_BEER),...Object.values(exports.ENUM_FOOD),...Object.values(exports.ENUM_MERCHANDISE),...Object.values(exports.ENUM_NON_ALCOHOLIC),...Object.values(exports.ENUM_READY_TO_DRINK),...Object.values(exports.ENUM_SPIRITS),...Object.values(exports.ENUM_WINE)])}validateAndNormalizeParams(e){const t={...e};return this.validateUPCs(t.upcs),this.locationServiceHelper.validateAndNormalizeLocation(t.loc),t}validateAndNormalizeSearchParams(e){const t=[],r={...e};return this.validateOrderBy(r.orderBy,t),this.validateOrderDirection(r.orderDirection,t),this.validateFilters(r.filters,t),this.validatePagination(r.page,r.perPage,t),this.locationServiceHelper.validateAndNormalizeLocation(r.loc),t.length>0?{...r,error:t.join(". ")}:r}validateUPCs(e){if(!Array.isArray(e)||0===e.length)throw new Error("UPCs must be a non-empty array of strings");if(!e.every((e=>"string"==typeof e&&e.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(e,t){e&&!Object.values(exports.ENUM_ORDER_BY).includes(e)&&t.push(`Invalid orderBy value: ${e}`)}validateOrderDirection(e,t){e&&!Object.values(exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE).includes(e)&&t.push(`Invalid orderDirection value: ${e}`)}validateFilters(e,t){e&&(e.length>10&&t.push("Maximum of 10 filters allowed"),e.forEach((e=>{switch(Object.values(exports.ENUM_FILTER_KEYS).includes(e.key)||t.push(`Invalid filter key: ${e.key}`),e.key){case exports.ENUM_FILTER_KEYS.AVAILABILITY:this.validateAvailabilityFilter(e.values,t);break;case exports.ENUM_FILTER_KEYS.BRANDS:this.validateArrayFilter(e.values,30,"brands",t);break;case exports.ENUM_FILTER_KEYS.CATEGORIES:this.validateCategoriesFilter(e.values,t);break;case exports.ENUM_FILTER_KEYS.COLORS:this.validateArrayFilter(e.values,75,"colors",t)}})))}validateAvailabilityFilter(e,t){Object.values(exports.ENUM_AVAILABILITY_VALUE).includes(e)||t.push(`Invalid availability value: ${e}`)}validateArrayFilter(e,t,r,i){Array.isArray(e)?e.length>t&&i.push(`${r} filter can have a maximum of ${t} values`):i.push(`${r} filter must be an array`)}validateCategoriesFilter(e,t){Array.isArray(e)?e.every((e=>this.taxonomyValues.has(e)))||t.push("Invalid category value(s) in categories filter"):t.push("Categories filter must be an array")}validatePagination(e,t,r){void 0!==e&&("number"!=typeof e||e<0)&&r.push("Page must be a non-negative number"),void 0!==t&&("number"!=typeof t||t<=0)&&r.push("PerPage must be a positive number")}}class C{constructor(e){this.locationHelperService=e}validateAndNormalizePrepareParams(e){const t={...e};if(!t.cartId||"string"!=typeof t.cartId)throw new Error("Invalid cartId");return this.validateRecipient(t.recipient),t.billingAddress&&this.validateAddress(t.billingAddress),t.hasSubstitutionPolicy=Boolean(t.hasSubstitutionPolicy),t.isGift=Boolean(t.isGift),t.billingSameAsShipping=Boolean(t.billingSameAsShipping),t.isGift&&this.validateGiftOptions(t.giftOptions),this.validateMarketingPreferences(t.marketingPreferences),t.deliveryTips&&this.validateDeliveryTips(t.deliveryTips),t.refresh=Boolean(t.refresh),t}validateAndNormalizeCompleteParams(e){const t={...e};if(!t.token||"string"!=typeof t.token)throw new Error("Invalid token");if(!t.payment||"string"!=typeof t.payment)throw new Error("Invalid payment token");return void 0!==t.refresh&&(t.refresh=Boolean(t.refresh)),t}validateRecipient(e){if(!e||"object"!=typeof e)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid recipient ${t}`)})),e.hasAgeVerify=Boolean(e.hasAgeVerify)}validateAddress(e){if(!e||"object"!=typeof e)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid address ${t}`)})),this.locationHelperService.validateAndNormalizeLocation({address:e})}validateGiftOptions(e){if(!e||"object"!=typeof e)throw new Error("Invalid giftOptions");if(e.message&&"string"!=typeof e.message)throw new Error("Invalid gift message");if(e.recipient){const{name:t,phone:r,email:i}=e.recipient;if(t&&"string"!=typeof t)throw new Error("Invalid gift recipient name");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient phone");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(e){if(!e||"object"!=typeof e)throw new Error("Invalid marketingPreferences");e.canEmail=Boolean(e.canEmail),e.canSms=Boolean(e.canSms)}validateDeliveryTips(e){if(!Array.isArray(e))throw new Error("Invalid deliveryTips");e.forEach((e=>{if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof e.tip||e.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class y{validateAndNormalizeLocation(e){if(!e||"object"!=typeof e)throw new Error("Location must be a valid object");if(e.coords)this.validateCoordinates(e.coords);else{if(!e.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(e.address)}}validateCoordinates(e){if("number"!=typeof e.lat||"number"!=typeof e.long)throw new Error("Coordinates must be valid numbers");if(e.lat<-90||e.lat>90||e.long<-180||e.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(e){if(!e.state||"string"!=typeof e.state)throw new Error("State is required and must be a string");if(e.state=this.normalizeState(e.state),!e.city||"string"!=typeof e.city)throw new Error("City is required and must be a string");if(!e.zip||"string"!=typeof e.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(e){const t=e.toUpperCase();if(exports.STATES_CODE[t])return exports.STATES_CODE[t];const r=e.toUpperCase();if(exports.STATES_NAME[r])return exports.STATES_NAME[r];throw new Error(`Invalid state: ${e}`)}}class _{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)",this.clientSecret=null}async mount(e){if(!document.getElementById(e.elementId))throw new Error(`Element with id "${e.elementId}" not found`);try{this.stripe=await N.loadStripe(e.key)}catch(e){throw new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");this.clientSecret=e.clientSecret;try{const{setupIntent:e}=await this.stripe.retrieveSetupIntent(this.clientSecret);if("succeeded"===(null==e?void 0:e.status))throw new Error(`The client secret (${this.clientSecret}) has already been used previously. Generate a new one through a use session.`)}catch(e){throw e}const t={clientSecret:e.clientSecret,appearance:this.mapAppearance(e.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(t);const r=this.mapElementOptions(e.elementOptions);this.paymentElement=this.elements.create("payment",r),this.paymentElement.mount(`#${e.elementId}`)}async generateToken(){var e,t,r,i,s,a,n,o,c,l,E,d;if(!this.stripe||!this.elements||!this.clientSecret)return{type:"client_error",message:"Payment form has not been initialized"};const{error:h}=await this.elements.submit();if(h)return{type:"validation_error",message:h.message,code:h.code};const{error:I,paymentMethod:A}=await this.stripe.createPaymentMethod({elements:this.elements}),u=await this.stripe.confirmSetup({elements:this.elements,redirect:"if_required"});return u.error?{type:"confirm_error",message:null!==(t=null===(e=null==u?void 0:u.error)||void 0===e?void 0:e.message)&&void 0!==t?t:"",code:null!==(i=null===(r=null==u?void 0:u.error)||void 0===r?void 0:r.code)&&void 0!==i?i:""}:I?{type:"validation_error"===I.type?"validation_error":"api_error",message:I.message,code:I.code,param:I.param}:A?{id:A.id,type:A.type,card:(null==A?void 0:A.card)?{brand:null!==(a=null===(s=A.card)||void 0===s?void 0:s.brand)&&void 0!==a?a:"",country:null!==(n=A.card.country)&&void 0!==n?n:"",expMonth:null!==(o=A.card.exp_month)&&void 0!==o?o:0,expYear:null!==(c=A.card.exp_year)&&void 0!==c?c:0,last4:null!==(l=A.card.last4)&&void 0!==l?l:"",funding:null!==(E=A.card.funding)&&void 0!==E?E:""}:void 0,created:null!==(d=null==A?void 0:A.created)&&void 0!==d?d:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.on(e,t)}unsubscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.off(e,t)}mapAppearance(e){if(e)return{theme:"night"===e.theme?"night":"stripe"}}mapElementOptions(e){return{layout:null==e?void 0:e.layout,wallets:{applePay:"auto",googlePay:"auto"}}}unmount(){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");this.paymentElement.unmount()}collapse(){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");this.paymentElement.collapse()}destroy(){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");this.paymentElement.destroy()}}class g{constructor(e){this.client=e}async autocomplete(e,t){try{return await this.client.post("/address/autocomplete",{...e,key:t})}catch(e){throw console.error("Address autocomplete request failed:",e),e}}async details(e,t){try{return await this.client.post("/address/details",{...e,key:t})}catch(e){throw console.error("Address details request failed:",e),e}}}class M{constructor(e,t){this.client=e,this.cartHelperService=t,this.servicePath="/cart/update"}async get(e,t){try{let r=this.cartHelperService.validateId(e);if(r=""!==r&&r,r){const e={id:r};return"boolean"==typeof t&&(e.refresh=t),await this.client.post(this.servicePath,e)}return await this.client.post(this.servicePath)}catch(e){throw console.error("Cart update request failed:",e),e}}async update(e){try{const t=this.cartHelperService.validateAndNormalizeParams(e);return await this.client.post(this.servicePath,t)}catch(e){throw console.error("Cart update request failed:",e),e}}}class D{constructor(e,t){this.client=e,this.catalogHelperService=t,this.servicePath="/catalog/"}async availability(e){try{const t=this.catalogHelperService.validateAndNormalizeParams(e);return await this.client.post(`${this.servicePath}availability`,t)}catch(e){throw console.error("Catalog availability request failed:",e),e}}async search(e){try{const t=this.catalogHelperService.validateAndNormalizeSearchParams(e);if(null==t?void 0:t.error)throw new Error(null==t?void 0:t.error);return await this.client.post(`${this.servicePath}search`,t)}catch(e){throw console.error("Catalog search request failed:",e),e}}}class L{constructor(e,t){this.client=e,this.checkoutHelperService=t,this.servicePath="/checkout"}async prepare(e){try{const t=this.checkoutHelperService.validateAndNormalizePrepareParams(e);return await this.client.post(`${this.servicePath}/prepare`,t)}catch(e){throw console.error("Checkout prepare request failed:",e),e}}async complete(e){try{const t=this.checkoutHelperService.validateAndNormalizeCompleteParams(e);return await this.client.post(`${this.servicePath}/complete`,t)}catch(e){throw console.error("Checkout complete request failed:",e),e}}}class f{constructor(e){this.paymentProvider=e,this.collapse=()=>this.paymentProvider.collapse(),this.unmount=()=>this.paymentProvider.unmount(),this.destroy=()=>this.paymentProvider.destroy()}async mount(e){try{await this.paymentProvider.mount(e)}catch(e){throw console.error("Failed to inject payment element:",e),e}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(e,t){this.paymentProvider.subscribe(e,t)}unsubscribe(e,t){this.paymentProvider.unsubscribe(e,t)}}class P{constructor(e){this.client=e,this.servicePath="/users"}async createOrUpdateSession(e){try{if(!(null==e?void 0:e.id)&&!(null==e?void 0:e.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,e)}catch(e){throw console.error("User session creation/update request failed:",e),e}}async purge(e){try{if(!e)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${e}`)}catch(e){throw console.error("User purge request failed:",e),e}}async addAddress(e){try{if(!(e.customerId&&e.one&&e.city&&e.state&&e.zip&&e.type))throw new Error("Missing required parameters to add address");return await this.client.post(`${this.servicePath}/addresses/add`,e)}catch(e){throw console.error("User address add request failed:",e),e}}async updateAddress(e){try{if(!(e.customerId&&e.one&&e.city&&e.state&&e.zip&&e.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,e)}catch(e){throw console.error("User address update request failed:",e),e}}async purgeAddress(e){try{if(!e)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${e}`)}catch(e){throw console.error("Address purge request failed:",e),e}}async addPayment(e){try{if(!e.customerId||!e.paymentMethodId)throw new Error("Missing required parameters to add payment");return void 0===(null==e?void 0:e.isDefault)&&(null==e||delete e.isDefault),await this.client.post(`${this.servicePath}/payments/add`,e)}catch(e){throw console.error("User add payment request failed:",e),e}}async updatePayment(e){try{if(!e.customerId||!e.paymentMethodId||void 0===(null==e?void 0:e.isDefault)||"boolean"!=typeof(null==e?void 0:e.isDefault))throw new Error("Missing required parameters to add payment");return await this.client.post(`${this.servicePath}/payments/update`,e)}catch(e){throw console.error("User add payment request failed:",e),e}}async purgePayment(e,t){try{if(!e||!t)throw new Error("Missing required parameters for payment purge");return await this.client.delete(`${this.servicePath}/payments/purge/${e}/${t}`)}catch(e){throw console.error("Address purge request failed:",e),e}}}class w{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return w.instance||(w.instance=new w),w.instance}setLiquidCommerceClientConstructor(e){this.liquidCommerceClientConstructor=e}async getLiquidCommerceClient(e,t){const r=`LiquidCommerceClient_${e}_${JSON.stringify(t)}`;if(!this.services.has(r)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const i=new this.liquidCommerceClientConstructor(e,t);await i.init(),this.services.set(r,i)}return this.services.get(r)}getOrCreateService(e,t,...r){if(!this.services.has(e)){const i="getInstance"in t?t.getInstance(...r):new t(...r);this.services.set(e,i)}return this.services.get(e)}getAuthenticatedClient(e){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(e)}`,m,e)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",y)}getAddressService(e){return this.getOrCreateService(`AddressService_${e.getUniqueKey()}`,g,e)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",T,this.getLocationHelperService())}getCatalogService(e){return this.getOrCreateService(`CatalogService_${e.getUniqueKey()}`,D,e,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",O,this.getLocationHelperService())}getCartService(e){return this.getOrCreateService(`CartService_${e.getUniqueKey()}`,M,e,this.getCartHelperService())}getUserService(e){return this.getOrCreateService(`UserService_${e.getUniqueKey()}`,P,e)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",_)}getPaymentService(){return this.getOrCreateService("PaymentService",f,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",C,this.getLocationHelperService())}getCheckoutService(e){return this.getOrCreateService(`CheckoutService_${e.getUniqueKey()}`,L,e,this.getCheckoutHelperService())}}w.instance=null;class U{constructor(e,t){this.address={autocomplete:async e=>(await this.ensureAuthenticated(),this.addressService.autocomplete(e,this.config.googlePlacesApiKey)),details:async e=>(await this.ensureAuthenticated(),this.addressService.details(e,this.config.googlePlacesApiKey))},this.catalog={availability:async e=>(await this.ensureAuthenticated(),this.catalogService.availability(e)),search:async e=>(await this.ensureAuthenticated(),this.catalogService.search(e))},this.cart={get:async(e,t)=>(await this.ensureAuthenticated(),this.cartService.get(e,t)),update:async e=>(await this.ensureAuthenticated(),this.cartService.update(e))},this.user={session:async e=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(e)),purge:async e=>(await this.ensureAuthenticated(),this.userService.purge(e)),addAddress:async e=>(await this.ensureAuthenticated(),this.userService.addAddress(e)),updateAddress:async e=>(await this.ensureAuthenticated(),this.userService.updateAddress(e)),purgeAddress:async e=>(await this.ensureAuthenticated(),this.userService.purgeAddress(e)),addPayment:async e=>(await this.ensureAuthenticated(),this.userService.addPayment(e)),updatePayment:async e=>(await this.ensureAuthenticated(),this.userService.updatePayment(e)),purgePayment:async(e,t)=>(await this.ensureAuthenticated(),this.userService.purgePayment(e,t))},this.payment={mount:async e=>(await this.ensureAuthenticated(),this.paymentService.mount(e)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(e,t)=>{this.paymentService.subscribe(e,t)},unsubscribe:(e,t)=>{this.paymentService.unsubscribe(e,t)},collapse:()=>{this.paymentService.collapse()},unmount:()=>{this.paymentService.unmount()},destroy:()=>{this.paymentService.destroy()}},this.checkout={prepare:async e=>(await this.ensureAuthenticated(),this.checkoutService.prepare(e)),complete:async e=>(await this.ensureAuthenticated(),this.checkoutService.complete(e))},this.config=t,this.singletonManager=w.getInstance();const r=this.determineBaseURL(t);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:e,baseURL:r}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(e){const t=e.env||exports.LIQUID_COMMERCE_ENV.STAGE;return v[t]}async init(){try{await this.authenticatedClient.authenticate()}catch(e){throw console.error("Failed to initialize LiquidCommerceClient:",e),new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}exports.LiquidCommerce=async function(e,t){const r=w.getInstance();return r.setLiquidCommerceClientConstructor(U),await r.getLiquidCommerceClient(e,t)};
package/dist/index.esm.js CHANGED
@@ -1 +1 @@
1
- import{loadStripe as e}from"@stripe/stripe-js";var t,i,r,a,s,n,o,c,l,h,d,I,u,A,E,S,p,v,R,m;!function(e){e.LOC="loc",e.STAGE="stage",e.PROD="prod",e.DEV="dev"}(t||(t={})),function(e){e.ON_DEMAND="onDemand",e.SHIPPING="shipping"}(i||(i={})),function(e){e.MONDAY="monday",e.TUESDAY="tuesday",e.WEDNESDAY="wednesday",e.THURSDAY="thursday",e.FRIDAY="friday",e.SATURDAY="saturday",e.SUNDAY="sunday"}(r||(r={})),function(e){e.AL="AL",e.AK="AK",e.AR="AR",e.CA="CA",e.CO="CO",e.CT="CT",e.DE="DE",e.DC="DC",e.FL="FL",e.GA="GA",e.HI="HI",e.ID="ID",e.IL="IL",e.IN="IN",e.IA="IA",e.KS="KS",e.KY="KY",e.LA="LA",e.ME="ME",e.MD="MD",e.MA="MA",e.MI="MI",e.MN="MN",e.MS="MS",e.MO="MO",e.MT="MT",e.NE="NE",e.NV="NV",e.NH="NH",e.NJ="NJ",e.NM="NM",e.NY="NY",e.NC="NC",e.ND="ND",e.OH="OH",e.OK="OK",e.OR="OR",e.PA="PA",e.RI="RI",e.SC="SC",e.SD="SD",e.TN="TN",e.TX="TX",e.UT="UT",e.VT="VT",e.VA="VA",e.WA="WA",e.WV="WV",e.WI="WI",e.WY="WY"}(a||(a={})),function(e){e.ALABAMA="AL",e.ALASKA="AK",e.ARKANSAS="AR",e.CALIFORNIA="CA",e.COLORADO="CO",e.CONNECTICUT="CT",e.DELAWARE="DE",e.DISTRICT_OF_COLUMBIA="DC",e.FLORIDA="FL",e.GEORGIA="GA",e.HAWAII="HI",e.IDAHO="ID",e.ILLINOIS="IL",e.INDIANA="IN",e.IOWA="IA",e.KANSAS="KS",e.KENTUCKY="KY",e.LOUISIANA="LA",e.MAINE="ME",e.MARYLAND="MD",e.MASSACHUSETTS="MA",e.MICHIGAN="MI",e.MINNESOTA="MN",e.MISSISSIPPI="MS",e.MISSOURI="MO",e.MONTANA="MT",e.NEBRASKA="NE",e.NEVADA="NV",e.NEW_HAMPSHIRE="NH",e.NEW_JERSEY="NJ",e.NEW_MEXICO="NM",e.NEW_YORK="NY",e.NORTH_CAROLINA="NC",e.NORTH_DAKOTA="ND",e.OHIO="OH",e.OKLAHOMA="OK",e.OREGON="OR",e.PENNSYLVANIA="PA",e.RHODE_ISLAND="RI",e.SOUTH_CAROLINA="SC",e.SOUTH_DAKOTA="SD",e.TENNESSEE="TN",e.TEXAS="TX",e.UTAH="UT",e.VERMONT="VT",e.VIRGINIA="VA",e.WASHINGTON="WA",e.WEST_VIRGINIA="WV",e.WISCONSIN="WI",e.WYOMING="WY"}(s||(s={})),function(e){e.ALE="BEER > ALE",e.LAGER="BEER > LAGER",e.MAIN="BEER",e.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",e.OTHER_BEER="BEER > OTHER BEER"}(n||(n={})),function(e){e.BASE="FOOD",e.PANTRY_OTHER="FOOD > PANTRY > OTHER"}(o||(o={})),function(e){e.BASE="MERCHANDISE",e.GLASSWARE="MERCHANDISE > GLASSWARE",e.HUMIDOR="MERCHANDISE > HUMIDOR"}(c||(c={})),function(e){e.BASE="MISCELLANEOUS",e.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",e.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",e.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP"}(l||(l={})),function(e){e.BASE="NON ALCOHOLIC",e.BITTERS="NON ALCOHOLIC > BITTERS",e.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",e.COFFEE="NON ALCOHOLIC > COFFEE",e.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",e.JUICE="NON ALCOHOLIC > JUICE",e.SODA="NON ALCOHOLIC > SODA",e.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",e.SPIRITS="NON ALCOHOLIC > SPIRITS",e.TEA="NON ALCOHOLIC > TEA",e.WATER="NON ALCOHOLIC > WATER",e.WINE="NON ALCOHOLIC > WINE"}(h||(h={})),function(e){e.BASE="READY TO DRINK",e.HARD_CIDER="READY TO DRINK > HARD CIDER",e.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",e.HARD_TEA="READY TO DRINK > HARD TEA",e.MALT_BASED="READY TO DRINK > MALT BASED",e.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",e.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",e.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",e.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",e.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",e.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS"}(d||(d={})),function(e){e.BASE="SPIRITS",e.BAIJIU="SPIRITS > BAIJIU",e.BITTERS="SPIRITS > BITTERS",e.BRANDY="SPIRITS > BRANDY",e.CACHACA="SPIRITS > CACHACA",e.GIN="SPIRITS > GIN",e.LAGER="SPIRITS > LAGER",e.LIQUEUR="SPIRITS > LIQUEUR",e.MEZCAL="SPIRITS > MEZCAL",e.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",e.RUM="SPIRITS > RUM",e.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",e.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",e.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",e.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",e.RUM_OTHER="SPIRITS > RUM > OTHER",e.RUM_SPICED="SPIRITS > RUM > SPICED",e.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",e.SOJU="SPIRITS > SOJU",e.TEQUILA="SPIRITS > TEQUILA",e.VODKA="SPIRITS > VODKA",e.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",e.WHISKEY="SPIRITS > WHISKEY",e.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",e.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",e.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",e.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",e.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH"}(I||(I={})),function(e){e.BASE="WINE",e.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",e.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",e.COOKING="WINE > COOKING",e.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",e.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",e.RED_WINE="WINE > RED WINE",e.ROSE_WINE="WINE > ROSE WINE",e.SAKE="WINE > SAKE",e.WHITE_WINE="WINE > WHITE WINE"}(u||(u={})),function(e){e.BRANDS="brands",e.FLAVOR="flavor",e.REGION="region",e.VARIETY="variety",e.PRICE="price",e.AVAILABILITY="availability",e.CATEGORIES="categories",e.SIZES="sizes",e.COLORS="colors",e.APPELLATION="appellation",e.COUNTRY="country",e.VINTAGE="vintage",e.MATERIALS="materials"}(A||(A={})),function(e){e.ASC="asc",e.DESC="desc"}(E||(E={})),function(e){e.PRICE="price"}(S||(S={})),function(e){e.UNSPECIFIED="AVAILABILITY_UNSPECIFIED",e.IN_STOCK="IN_STOCK",e.OUT_OF_STOCK="OUT_OF_STOCK",e.PREORDER="PREORDER",e.BACKORDER="BACKORDER"}(p||(p={})),function(e){e.INVALID_ITEMS_TYPE="Items must be a non-empty array",e.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",e.INVALID_PART_NUMBER="The partnerNumber provided is invalid",e.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid"}(v||(v={})),function(e){e.OOS="OutOfStock",e.ITEMS_NOT_ADDED="ItemsNotAdded",e.ITEMS_REQUESTED_NOT_ADDED="ItemsRequestedNotAdded",e.ITEM_NOT_ENGRAVED="ItemEngravingError",e.ADDRESS_CHANGE="AddressChange",e.LOCATION_AVAILABILITY="LocationAvailability",e.REMOVED_EXISTING_ITEMS="RemovedExistingCartItems",e.RETAILER_MIN="RetailerMinNotMet",e.NO_ITEMS_IN_CART="NoItemsInCart",e.INVALID_ID="InvalidId",e.NO_ID="NoId",e.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",e.NEW_CART="NewCart",e.DEFAULT="CartError",e.ITEM_QTY_CHANGE="ItemQuantityChange"}(R||(R={})),function(e){e.SHIPPING="shipping",e.BILLING="billing"}(m||(m={}));const C={[t.LOC]:"https://staging.cloud.liquidcommerce.co/api",[t.DEV]:"https://staging.cloud.liquidcommerce.co/api",[t.STAGE]:"https://staging.cloud.liquidcommerce.co/api",[t.PROD]:"https://staging.cloud.liquidcommerce.co/api"};class N{constructor(e){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(e,t)=>new Promise(((i,r)=>{const a=new XMLHttpRequest;a.open(t.method||"GET",e),Object.entries(t.headers).forEach((([e,t])=>{a.setRequestHeader(e,t)})),a.onload=()=>{i({ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,headers:a.getAllResponseHeaders().split("\r\n").reduce(((e,t)=>{const[i,r]=t.split(": ");return i&&(e[i]=r),e}),{}),json:()=>Promise.resolve(JSON.parse(a.responseText)),text:()=>Promise.resolve(a.responseText)})},a.onerror=()=>{r(new TypeError("Network request failed"))},a.send(t.body)})),this.apiKey=e.apiKey,this.baseURL=e.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(e){return N.instance||(N.instance=new N(e)),N.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):"undefined"!=typeof window&&window.fetch?this.fetchAdapter(window.fetch):this.xhrFetch}fetchAdapter(e){return async(t,i)=>{var r;const a=await e(t,i);let s;return"function"==typeof(null===(r=a.headers)||void 0===r?void 0:r.entries)?s=Object.fromEntries(a.headers.entries()):(s={},a.headers.forEach(((e,t)=>{s[t]=e}))),{ok:a.ok,status:a.status,statusText:a.statusText,headers:s,json:()=>a.json(),text:()=>a.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var e,t;if(this.isAuthenticating)await new Promise((e=>{const t=()=>{this.isAuthenticating?setTimeout(t,100):e(void 0)};t()}));else{this.isAuthenticating=!0;try{const i=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(e=null==i?void 0:i.data)||void 0===e?void 0:e.token,this.tokenExpiration=Date.now()+1e3*(null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.exp)}catch(e){throw console.error("Authentication failed:",e),new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(e,t){const i=new URL(`api${e}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...t.headers},a={method:t.method,headers:r,body:t.body?JSON.stringify(t.body):void 0},s=await this.httpClient(i.toString(),a);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(e,t){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const i=new URL(`api${e}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...t.headers},a={method:t.method,headers:r,body:t.body?JSON.stringify(t.body):void 0},s=await this.httpClient(i.toString(),a);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}async get(e,t){return this.request(e,{method:"GET",headers:t})}async post(e,t,i){return this.request(e,{method:"POST",body:t,headers:i})}async put(e,t,i){return this.request(e,{method:"PUT",body:t,headers:i})}async delete(e,t){return this.request(e,{method:"DELETE",headers:t})}}N.instance=null;class O{constructor(e){this.locationHelperService=e}validateAndNormalizeParams(e){const t={...e};return t.id=this.validateId(t.id),t.items=this.validateAndNormalizeItems(t.items),this.locationHelperService.validateAndNormalizeLocation(t.loc),t.refresh=Boolean(t.refresh),t}validateId(e){return e&&"string"==typeof e&&0!==e.trim().length?e.trim():""}validateAndNormalizeItems(e){if(!Array.isArray(e)||0===e.length)throw new Error(v.INVALID_ITEMS_TYPE);if(e.length>25)throw new Error(v.INVALID_ITEMS_MAX);return e.map((e=>this.validateAndNormalizeItem(e)))}validateAndNormalizeItem(e){const t={...e};if(!this.validatePartNumber(t.partNumber))throw new Error(v.INVALID_PART_NUMBER);if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId||0===t.fulfillmentId.trim().length)throw new Error(v.INVALID_FULFILLMENT_ID);return t.quantity=Math.max(0,Math.floor(t.quantity)),t.engravingLines&&(t.engravingLines=t.engravingLines.map((e=>e.trim())).filter((e=>e.length>0))),t}validatePartNumber(e){if(!e||"string"!=typeof e)return!1;const t=e.split("_");return 2===t.length&&14===t[0].length&&t[1].length>0}}class T{constructor(e){this.locationServiceHelper=e,this.taxonomyValues=new Set([...Object.values(n),...Object.values(o),...Object.values(c),...Object.values(h),...Object.values(d),...Object.values(I),...Object.values(u)])}validateAndNormalizeParams(e){const t={...e};return this.validateUPCs(t.upcs),this.locationServiceHelper.validateAndNormalizeLocation(t.loc),t}validateAndNormalizeSearchParams(e){const t=[],i={...e};return this.validateOrderBy(i.orderBy,t),this.validateOrderDirection(i.orderDirection,t),this.validateFilters(i.filters,t),this.validatePagination(i.page,i.perPage,t),this.locationServiceHelper.validateAndNormalizeLocation(i.loc),t.length>0?{...i,error:t.join(". ")}:i}validateUPCs(e){if(!Array.isArray(e)||0===e.length)throw new Error("UPCs must be a non-empty array of strings");if(!e.every((e=>"string"==typeof e&&e.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(e,t){e&&!Object.values(S).includes(e)&&t.push(`Invalid orderBy value: ${e}`)}validateOrderDirection(e,t){e&&!Object.values(E).includes(e)&&t.push(`Invalid orderDirection value: ${e}`)}validateFilters(e,t){e&&(e.length>10&&t.push("Maximum of 10 filters allowed"),e.forEach((e=>{switch(Object.values(A).includes(e.key)||t.push(`Invalid filter key: ${e.key}`),e.key){case A.AVAILABILITY:this.validateAvailabilityFilter(e.values,t);break;case A.BRANDS:this.validateArrayFilter(e.values,30,"brands",t);break;case A.CATEGORIES:this.validateCategoriesFilter(e.values,t);break;case A.COLORS:this.validateArrayFilter(e.values,75,"colors",t)}})))}validateAvailabilityFilter(e,t){Object.values(p).includes(e)||t.push(`Invalid availability value: ${e}`)}validateArrayFilter(e,t,i,r){Array.isArray(e)?e.length>t&&r.push(`${i} filter can have a maximum of ${t} values`):r.push(`${i} filter must be an array`)}validateCategoriesFilter(e,t){Array.isArray(e)?e.every((e=>this.taxonomyValues.has(e)))||t.push("Invalid category value(s) in categories filter"):t.push("Categories filter must be an array")}validatePagination(e,t,i){void 0!==e&&("number"!=typeof e||e<0)&&i.push("Page must be a non-negative number"),void 0!==t&&("number"!=typeof t||t<=0)&&i.push("PerPage must be a positive number")}}class y{constructor(e){this.locationHelperService=e}validateAndNormalizePrepareParams(e){const t={...e};if(!t.cartId||"string"!=typeof t.cartId)throw new Error("Invalid cartId");return this.validateRecipient(t.recipient),t.billingAddress&&this.validateAddress(t.billingAddress),t.hasSubstitutionPolicy=Boolean(t.hasSubstitutionPolicy),t.isGift=Boolean(t.isGift),t.billingSameAsShipping=Boolean(t.billingSameAsShipping),t.isGift&&this.validateGiftOptions(t.giftOptions),this.validateMarketingPreferences(t.marketingPreferences),t.deliveryTips&&this.validateDeliveryTips(t.deliveryTips),t.refresh=Boolean(t.refresh),t}validateAndNormalizeCompleteParams(e){const t={...e};if(!t.token||"string"!=typeof t.token)throw new Error("Invalid token");if(!t.payment||"string"!=typeof t.payment)throw new Error("Invalid payment token");return void 0!==t.refresh&&(t.refresh=Boolean(t.refresh)),t}validateRecipient(e){if(!e||"object"!=typeof e)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid recipient ${t}`)})),e.hasAgeVerify=Boolean(e.hasAgeVerify)}validateAddress(e){if(!e||"object"!=typeof e)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid address ${t}`)})),this.locationHelperService.validateAndNormalizeLocation({address:e})}validateGiftOptions(e){if(!e||"object"!=typeof e)throw new Error("Invalid giftOptions");if(e.message&&"string"!=typeof e.message)throw new Error("Invalid gift message");if(e.recipient){const{name:t,phone:i,email:r}=e.recipient;if(t&&"string"!=typeof t)throw new Error("Invalid gift recipient name");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient phone");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(e){if(!e||"object"!=typeof e)throw new Error("Invalid marketingPreferences");e.canEmail=Boolean(e.canEmail),e.canSms=Boolean(e.canSms)}validateDeliveryTips(e){if(!Array.isArray(e))throw new Error("Invalid deliveryTips");e.forEach((e=>{if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof e.tip||e.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class g{validateAndNormalizeLocation(e){if(!e||"object"!=typeof e)throw new Error("Location must be a valid object");if(e.coords)this.validateCoordinates(e.coords);else{if(!e.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(e.address)}}validateCoordinates(e){if("number"!=typeof e.lat||"number"!=typeof e.long)throw new Error("Coordinates must be valid numbers");if(e.lat<-90||e.lat>90||e.long<-180||e.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(e){if(!e.state||"string"!=typeof e.state)throw new Error("State is required and must be a string");if(e.state=this.normalizeState(e.state),!e.city||"string"!=typeof e.city)throw new Error("City is required and must be a string");if(!e.zip||"string"!=typeof e.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(e){const t=e.toUpperCase();if(a[t])return a[t];const i=e.toUpperCase();if(s[i])return s[i];throw new Error(`Invalid state: ${e}`)}}class f{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)"}async mount(t){if(!document.getElementById(t.elementId))throw new Error(`Element with id "${t.elementId}" not found`);try{this.stripe=await e(t.key)}catch(e){throw console.error("Failed to load Stripe:",e),new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");const i={clientSecret:t.clientSecret,appearance:this.mapAppearance(t.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(i);const r=this.mapElementOptions(t.elementOptions);this.paymentElement=this.elements.create("payment",r),this.paymentElement.mount(`#${t.elementId}`)}async generateToken(){var e,t,i,r,a,s,n,o;if(!this.stripe||!this.elements)return{type:"client_error",message:"Payment form has not been initialized"};const{error:c}=await this.elements.submit();if(c)return{type:"validation_error",message:c.message,code:c.code};const{error:l,paymentMethod:h}=await this.stripe.createPaymentMethod({elements:this.elements});return l?{type:"validation_error"===l.type?"validation_error":"api_error",message:l.message,code:l.code,param:l.param}:h?{id:h.id,type:h.type,card:(null==h?void 0:h.card)?{brand:null!==(t=null===(e=h.card)||void 0===e?void 0:e.brand)&&void 0!==t?t:"",country:null!==(i=h.card.country)&&void 0!==i?i:"",expMonth:null!==(r=h.card.exp_month)&&void 0!==r?r:0,expYear:null!==(a=h.card.exp_year)&&void 0!==a?a:0,last4:null!==(s=h.card.last4)&&void 0!==s?s:"",funding:null!==(n=h.card.funding)&&void 0!==n?n:""}:void 0,created:null!==(o=null==h?void 0:h.created)&&void 0!==o?o:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.on(e,t)}unsubscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.off(e,t)}mapAppearance(e){if(e)return{theme:"night"===e.theme?"night":"stripe"}}mapElementOptions(e){return{layout:null==e?void 0:e.layout,wallets:{applePay:"auto",googlePay:"auto"}}}}class D{constructor(e){this.client=e}async autocomplete(e,t){try{return await this.client.post("/address/autocomplete",{...e,key:t})}catch(e){throw console.error("Address autocomplete request failed:",e),e}}async details(e,t){try{return await this.client.post("/address/details",{...e,key:t})}catch(e){throw console.error("Address details request failed:",e),e}}}class L{constructor(e,t){this.client=e,this.cartHelperService=t,this.servicePath="/cart/update"}async get(e,t){try{let i=this.cartHelperService.validateId(e);if(i=""!==i&&i,i){const e={id:i};return"boolean"==typeof t&&(e.refresh=t),await this.client.post(this.servicePath,e)}return await this.client.post(this.servicePath)}catch(e){throw console.error("Cart update request failed:",e),e}}async update(e){try{const t=this.cartHelperService.validateAndNormalizeParams(e);return await this.client.post(this.servicePath,t)}catch(e){throw console.error("Cart update request failed:",e),e}}}class w{constructor(e,t){this.client=e,this.catalogHelperService=t,this.servicePath="/catalog/"}async availability(e){try{const t=this.catalogHelperService.validateAndNormalizeParams(e);return await this.client.post(`${this.servicePath}availability`,t)}catch(e){throw console.error("Catalog availability request failed:",e),e}}async search(e){try{const t=this.catalogHelperService.validateAndNormalizeSearchParams(e);if(null==t?void 0:t.error)throw new Error(null==t?void 0:t.error);return await this.client.post(`${this.servicePath}search`,t)}catch(e){throw console.error("Catalog search request failed:",e),e}}}class P{constructor(e,t){this.client=e,this.checkoutHelperService=t,this.servicePath="/checkout"}async prepare(e){try{const t=this.checkoutHelperService.validateAndNormalizePrepareParams(e);return await this.client.post(`${this.servicePath}/prepare`,t)}catch(e){throw console.error("Checkout prepare request failed:",e),e}}async complete(e){try{const t=this.checkoutHelperService.validateAndNormalizeCompleteParams(e);return await this.client.post(`${this.servicePath}/complete`,t)}catch(e){throw console.error("Checkout complete request failed:",e),e}}}class M{constructor(e){this.paymentProvider=e}async mount(e){try{await this.paymentProvider.mount(e)}catch(e){throw console.error("Failed to inject payment element:",e),e}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(e,t){this.paymentProvider.subscribe(e,t)}unsubscribe(e,t){this.paymentProvider.unsubscribe(e,t)}}class _{constructor(e){this.client=e,this.servicePath="/users"}async createOrUpdateSession(e){try{if(!(null==e?void 0:e.id)&&!(null==e?void 0:e.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,e)}catch(e){throw console.error("User session creation/update request failed:",e),e}}async purge(e){try{if(!e)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${e}`)}catch(e){throw console.error("User purge request failed:",e),e}}async updateAddress(e){try{if(!(e.customerId&&e.one&&e.city&&e.state&&e.zip&&e.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,e)}catch(e){throw console.error("User address update request failed:",e),e}}async purgeAddress(e){try{if(!e)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${e}`)}catch(e){throw console.error("Address purge request failed:",e),e}}}class H{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return H.instance||(H.instance=new H),H.instance}setLiquidCommerceClientConstructor(e){this.liquidCommerceClientConstructor=e}async getLiquidCommerceClient(e,t){const i=`LiquidCommerceClient_${e}_${JSON.stringify(t)}`;if(!this.services.has(i)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const r=new this.liquidCommerceClientConstructor(e,t);await r.init(),this.services.set(i,r)}return this.services.get(i)}getOrCreateService(e,t,...i){if(!this.services.has(e)){const r="getInstance"in t?t.getInstance(...i):new t(...i);this.services.set(e,r)}return this.services.get(e)}getAuthenticatedClient(e){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(e)}`,N,e)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",g)}getAddressService(e){return this.getOrCreateService(`AddressService_${e.getUniqueKey()}`,D,e)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",T,this.getLocationHelperService())}getCatalogService(e){return this.getOrCreateService(`CatalogService_${e.getUniqueKey()}`,w,e,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",O,this.getLocationHelperService())}getCartService(e){return this.getOrCreateService(`CartService_${e.getUniqueKey()}`,L,e,this.getCartHelperService())}getUserService(e){return this.getOrCreateService(`UserService_${e.getUniqueKey()}`,_,e)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",f)}getPaymentService(){return this.getOrCreateService("PaymentService",M,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",y,this.getLocationHelperService())}getCheckoutService(e){return this.getOrCreateService(`CheckoutService_${e.getUniqueKey()}`,P,e,this.getCheckoutHelperService())}}H.instance=null;class b{constructor(e,t){this.address={autocomplete:async e=>(await this.ensureAuthenticated(),this.addressService.autocomplete(e,this.config.googlePlacesApiKey)),details:async e=>(await this.ensureAuthenticated(),this.addressService.details(e,this.config.googlePlacesApiKey))},this.catalog={availability:async e=>(await this.ensureAuthenticated(),this.catalogService.availability(e)),search:async e=>(await this.ensureAuthenticated(),this.catalogService.search(e))},this.cart={get:async(e,t)=>(await this.ensureAuthenticated(),this.cartService.get(e,t)),update:async e=>(await this.ensureAuthenticated(),this.cartService.update(e))},this.user={session:async e=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(e)),purge:async e=>(await this.ensureAuthenticated(),this.userService.purge(e)),updateAddress:async e=>(await this.ensureAuthenticated(),this.userService.updateAddress(e)),purgeAddress:async e=>(await this.ensureAuthenticated(),this.userService.purgeAddress(e))},this.payment={mount:async e=>(await this.ensureAuthenticated(),this.paymentService.mount(e)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(e,t)=>{this.paymentService.subscribe(e,t)},unsubscribe:(e,t)=>{this.paymentService.unsubscribe(e,t)}},this.checkout={prepare:async e=>(await this.ensureAuthenticated(),this.checkoutService.prepare(e)),complete:async e=>(await this.ensureAuthenticated(),this.checkoutService.complete(e))},this.config=t,this.singletonManager=H.getInstance();const i=this.determineBaseURL(t);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:e,baseURL:i}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(e){const i=e.env||t.STAGE;return C[i]}async init(){try{await this.authenticatedClient.authenticate()}catch(e){throw console.error("Failed to initialize LiquidCommerceClient:",e),new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}async function U(e,t){const i=H.getInstance();i.setLiquidCommerceClientConstructor(b);return await i.getLiquidCommerceClient(e,t)}export{R as CART_EVENT_ENUM,v as CART_PARAM_ERROR_ENUM,r as DAYS_OF_WEEK,m as ENUM_ADDRESS_TYPE,p as ENUM_AVAILABILITY_VALUE,n as ENUM_BEER,A as ENUM_FILTER_KEYS,o as ENUM_FOOD,c as ENUM_MERCHANDISE,l as ENUM_MISCELLANEOUS,i as ENUM_MODALITIES,E as ENUM_NAVIGATION_ORDER_DIRECTION_TYPE,h as ENUM_NON_ALCOHOLIC,S as ENUM_ORDER_BY,d as ENUM_READY_TO_DRINK,I as ENUM_SPIRITS,u as ENUM_WINE,t as LIQUID_COMMERCE_ENV,U as LiquidCommerce,a as STATES_CODE,s as STATES_NAME};
1
+ import{loadStripe as e}from"@stripe/stripe-js";var t,r,i,a,s,n,o,c,l,d,h,u,I,A,E,S,p,m,v,y;!function(e){e.LOC="loc",e.STAGE="stage",e.PROD="prod",e.DEV="dev"}(t||(t={})),function(e){e.ON_DEMAND="onDemand",e.SHIPPING="shipping"}(r||(r={})),function(e){e.MONDAY="monday",e.TUESDAY="tuesday",e.WEDNESDAY="wednesday",e.THURSDAY="thursday",e.FRIDAY="friday",e.SATURDAY="saturday",e.SUNDAY="sunday"}(i||(i={})),function(e){e.AL="AL",e.AK="AK",e.AR="AR",e.CA="CA",e.CO="CO",e.CT="CT",e.DE="DE",e.DC="DC",e.FL="FL",e.GA="GA",e.HI="HI",e.ID="ID",e.IL="IL",e.IN="IN",e.IA="IA",e.KS="KS",e.KY="KY",e.LA="LA",e.ME="ME",e.MD="MD",e.MA="MA",e.MI="MI",e.MN="MN",e.MS="MS",e.MO="MO",e.MT="MT",e.NE="NE",e.NV="NV",e.NH="NH",e.NJ="NJ",e.NM="NM",e.NY="NY",e.NC="NC",e.ND="ND",e.OH="OH",e.OK="OK",e.OR="OR",e.PA="PA",e.RI="RI",e.SC="SC",e.SD="SD",e.TN="TN",e.TX="TX",e.UT="UT",e.VT="VT",e.VA="VA",e.WA="WA",e.WV="WV",e.WI="WI",e.WY="WY"}(a||(a={})),function(e){e.ALABAMA="AL",e.ALASKA="AK",e.ARKANSAS="AR",e.CALIFORNIA="CA",e.COLORADO="CO",e.CONNECTICUT="CT",e.DELAWARE="DE",e.DISTRICT_OF_COLUMBIA="DC",e.FLORIDA="FL",e.GEORGIA="GA",e.HAWAII="HI",e.IDAHO="ID",e.ILLINOIS="IL",e.INDIANA="IN",e.IOWA="IA",e.KANSAS="KS",e.KENTUCKY="KY",e.LOUISIANA="LA",e.MAINE="ME",e.MARYLAND="MD",e.MASSACHUSETTS="MA",e.MICHIGAN="MI",e.MINNESOTA="MN",e.MISSISSIPPI="MS",e.MISSOURI="MO",e.MONTANA="MT",e.NEBRASKA="NE",e.NEVADA="NV",e.NEW_HAMPSHIRE="NH",e.NEW_JERSEY="NJ",e.NEW_MEXICO="NM",e.NEW_YORK="NY",e.NORTH_CAROLINA="NC",e.NORTH_DAKOTA="ND",e.OHIO="OH",e.OKLAHOMA="OK",e.OREGON="OR",e.PENNSYLVANIA="PA",e.RHODE_ISLAND="RI",e.SOUTH_CAROLINA="SC",e.SOUTH_DAKOTA="SD",e.TENNESSEE="TN",e.TEXAS="TX",e.UTAH="UT",e.VERMONT="VT",e.VIRGINIA="VA",e.WASHINGTON="WA",e.WEST_VIRGINIA="WV",e.WISCONSIN="WI",e.WYOMING="WY"}(s||(s={})),function(e){e.ALE="BEER > ALE",e.LAGER="BEER > LAGER",e.MAIN="BEER",e.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",e.OTHER_BEER="BEER > OTHER BEER"}(n||(n={})),function(e){e.BASE="FOOD",e.PANTRY_OTHER="FOOD > PANTRY > OTHER"}(o||(o={})),function(e){e.BASE="MERCHANDISE",e.GLASSWARE="MERCHANDISE > GLASSWARE",e.HUMIDOR="MERCHANDISE > HUMIDOR"}(c||(c={})),function(e){e.BASE="MISCELLANEOUS",e.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",e.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",e.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP"}(l||(l={})),function(e){e.BASE="NON ALCOHOLIC",e.BITTERS="NON ALCOHOLIC > BITTERS",e.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",e.COFFEE="NON ALCOHOLIC > COFFEE",e.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",e.JUICE="NON ALCOHOLIC > JUICE",e.SODA="NON ALCOHOLIC > SODA",e.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",e.SPIRITS="NON ALCOHOLIC > SPIRITS",e.TEA="NON ALCOHOLIC > TEA",e.WATER="NON ALCOHOLIC > WATER",e.WINE="NON ALCOHOLIC > WINE"}(d||(d={})),function(e){e.BASE="READY TO DRINK",e.HARD_CIDER="READY TO DRINK > HARD CIDER",e.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",e.HARD_TEA="READY TO DRINK > HARD TEA",e.MALT_BASED="READY TO DRINK > MALT BASED",e.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",e.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",e.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",e.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",e.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",e.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS"}(h||(h={})),function(e){e.BASE="SPIRITS",e.BAIJIU="SPIRITS > BAIJIU",e.BITTERS="SPIRITS > BITTERS",e.BRANDY="SPIRITS > BRANDY",e.CACHACA="SPIRITS > CACHACA",e.GIN="SPIRITS > GIN",e.LAGER="SPIRITS > LAGER",e.LIQUEUR="SPIRITS > LIQUEUR",e.MEZCAL="SPIRITS > MEZCAL",e.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",e.RUM="SPIRITS > RUM",e.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",e.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",e.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",e.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",e.RUM_OTHER="SPIRITS > RUM > OTHER",e.RUM_SPICED="SPIRITS > RUM > SPICED",e.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",e.SOJU="SPIRITS > SOJU",e.TEQUILA="SPIRITS > TEQUILA",e.VODKA="SPIRITS > VODKA",e.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",e.WHISKEY="SPIRITS > WHISKEY",e.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",e.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",e.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",e.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",e.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH"}(u||(u={})),function(e){e.BASE="WINE",e.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",e.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",e.COOKING="WINE > COOKING",e.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",e.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",e.RED_WINE="WINE > RED WINE",e.ROSE_WINE="WINE > ROSE WINE",e.SAKE="WINE > SAKE",e.WHITE_WINE="WINE > WHITE WINE"}(I||(I={})),function(e){e.BRANDS="brands",e.FLAVOR="flavor",e.REGION="region",e.VARIETY="variety",e.PRICE="price",e.AVAILABILITY="availability",e.CATEGORIES="categories",e.SIZES="sizes",e.COLORS="colors",e.APPELLATION="appellation",e.COUNTRY="country",e.VINTAGE="vintage",e.MATERIALS="materials"}(A||(A={})),function(e){e.ASC="asc",e.DESC="desc"}(E||(E={})),function(e){e.PRICE="price"}(S||(S={})),function(e){e.UNSPECIFIED="AVAILABILITY_UNSPECIFIED",e.IN_STOCK="IN_STOCK",e.OUT_OF_STOCK="OUT_OF_STOCK",e.PREORDER="PREORDER",e.BACKORDER="BACKORDER"}(p||(p={})),function(e){e.INVALID_ITEMS_TYPE="Items must be a non-empty array",e.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",e.INVALID_PART_NUMBER="The partnerNumber provided is invalid",e.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid"}(m||(m={})),function(e){e.OOS="OutOfStock",e.ITEMS_NOT_ADDED="ItemsNotAdded",e.ITEMS_REQUESTED_NOT_ADDED="ItemsRequestedNotAdded",e.ITEM_NOT_ENGRAVED="ItemEngravingError",e.ADDRESS_CHANGE="AddressChange",e.LOCATION_AVAILABILITY="LocationAvailability",e.REMOVED_EXISTING_ITEMS="RemovedExistingCartItems",e.RETAILER_MIN="RetailerMinNotMet",e.NO_ITEMS_IN_CART="NoItemsInCart",e.INVALID_ID="InvalidId",e.NO_ID="NoId",e.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",e.NEW_CART="NewCart",e.DEFAULT="CartError",e.ITEM_QTY_CHANGE="ItemQuantityChange"}(v||(v={})),function(e){e.SHIPPING="shipping",e.BILLING="billing"}(y||(y={}));const R={[t.LOC]:"https://staging.cloud.liquidcommerce.co/api",[t.DEV]:"https://staging.cloud.liquidcommerce.co/api",[t.STAGE]:"https://staging.cloud.liquidcommerce.co/api",[t.PROD]:"https://staging.cloud.liquidcommerce.co/api"};class C{constructor(e){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(e,t)=>new Promise(((r,i)=>{const a=new XMLHttpRequest;a.open(t.method||"GET",e),Object.entries(t.headers).forEach((([e,t])=>{a.setRequestHeader(e,t)})),a.onload=()=>{r({ok:a.status>=200&&a.status<300,status:a.status,statusText:a.statusText,headers:a.getAllResponseHeaders().split("\r\n").reduce(((e,t)=>{const[r,i]=t.split(": ");return r&&(e[r]=i),e}),{}),json:()=>Promise.resolve(JSON.parse(a.responseText)),text:()=>Promise.resolve(a.responseText)})},a.onerror=()=>{i(new TypeError("Network request failed"))},a.send(t.body)})),this.apiKey=e.apiKey,this.baseURL=e.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(e){return C.instance||(C.instance=new C(e)),C.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):"undefined"!=typeof window&&window.fetch?this.fetchAdapter(window.fetch):this.xhrFetch}fetchAdapter(e){return async(t,r)=>{var i;const a=await e(t,r);let s;return"function"==typeof(null===(i=a.headers)||void 0===i?void 0:i.entries)?s=Object.fromEntries(a.headers.entries()):(s={},a.headers.forEach(((e,t)=>{s[t]=e}))),{ok:a.ok,status:a.status,statusText:a.statusText,headers:s,json:()=>a.json(),text:()=>a.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var e,t;if(this.isAuthenticating)await new Promise((e=>{const t=()=>{this.isAuthenticating?setTimeout(t,100):e(void 0)};t()}));else{this.isAuthenticating=!0;try{const r=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(e=null==r?void 0:r.data)||void 0===e?void 0:e.token,this.tokenExpiration=Date.now()+1e3*(null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.exp)}catch(e){throw console.error("Authentication failed:",e),new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(e,t){const r=new URL(`api${e}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...t.headers},a={method:t.method,headers:i,body:t.body?JSON.stringify(t.body):void 0},s=await this.httpClient(r.toString(),a);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(e,t){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const r=new URL(`api${e}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...t.headers},a={method:t.method,headers:i,body:t.body?JSON.stringify(t.body):void 0},s=await this.httpClient(r.toString(),a);if(!s.ok)throw new Error(`HTTP error! status: ${s.status}`);return s.json()}async get(e,t){return this.request(e,{method:"GET",headers:t})}async post(e,t,r){return this.request(e,{method:"POST",body:t,headers:r})}async put(e,t,r){return this.request(e,{method:"PUT",body:t,headers:r})}async delete(e,t){return this.request(e,{method:"DELETE",headers:t})}}C.instance=null;class N{constructor(e){this.locationHelperService=e}validateAndNormalizeParams(e){const t={...e};return t.id=this.validateId(t.id),t.items=this.validateAndNormalizeItems(t.items),this.locationHelperService.validateAndNormalizeLocation(t.loc),t.refresh=Boolean(t.refresh),t}validateId(e){return e&&"string"==typeof e&&0!==e.trim().length?e.trim():""}validateAndNormalizeItems(e){if(!Array.isArray(e)||0===e.length)throw new Error(m.INVALID_ITEMS_TYPE);if(e.length>25)throw new Error(m.INVALID_ITEMS_MAX);return e.map((e=>this.validateAndNormalizeItem(e)))}validateAndNormalizeItem(e){const t={...e};if(!this.validatePartNumber(t.partNumber))throw new Error(m.INVALID_PART_NUMBER);if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId||0===t.fulfillmentId.trim().length)throw new Error(m.INVALID_FULFILLMENT_ID);return t.quantity=Math.max(0,Math.floor(t.quantity)),t.engravingLines&&(t.engravingLines=t.engravingLines.map((e=>e.trim())).filter((e=>e.length>0))),t}validatePartNumber(e){if(!e||"string"!=typeof e)return!1;const t=e.split("_");return 2===t.length&&14===t[0].length&&t[1].length>0}}class O{constructor(e){this.locationServiceHelper=e,this.taxonomyValues=new Set([...Object.values(n),...Object.values(o),...Object.values(c),...Object.values(d),...Object.values(h),...Object.values(u),...Object.values(I)])}validateAndNormalizeParams(e){const t={...e};return this.validateUPCs(t.upcs),this.locationServiceHelper.validateAndNormalizeLocation(t.loc),t}validateAndNormalizeSearchParams(e){const t=[],r={...e};return this.validateOrderBy(r.orderBy,t),this.validateOrderDirection(r.orderDirection,t),this.validateFilters(r.filters,t),this.validatePagination(r.page,r.perPage,t),this.locationServiceHelper.validateAndNormalizeLocation(r.loc),t.length>0?{...r,error:t.join(". ")}:r}validateUPCs(e){if(!Array.isArray(e)||0===e.length)throw new Error("UPCs must be a non-empty array of strings");if(!e.every((e=>"string"==typeof e&&e.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(e,t){e&&!Object.values(S).includes(e)&&t.push(`Invalid orderBy value: ${e}`)}validateOrderDirection(e,t){e&&!Object.values(E).includes(e)&&t.push(`Invalid orderDirection value: ${e}`)}validateFilters(e,t){e&&(e.length>10&&t.push("Maximum of 10 filters allowed"),e.forEach((e=>{switch(Object.values(A).includes(e.key)||t.push(`Invalid filter key: ${e.key}`),e.key){case A.AVAILABILITY:this.validateAvailabilityFilter(e.values,t);break;case A.BRANDS:this.validateArrayFilter(e.values,30,"brands",t);break;case A.CATEGORIES:this.validateCategoriesFilter(e.values,t);break;case A.COLORS:this.validateArrayFilter(e.values,75,"colors",t)}})))}validateAvailabilityFilter(e,t){Object.values(p).includes(e)||t.push(`Invalid availability value: ${e}`)}validateArrayFilter(e,t,r,i){Array.isArray(e)?e.length>t&&i.push(`${r} filter can have a maximum of ${t} values`):i.push(`${r} filter must be an array`)}validateCategoriesFilter(e,t){Array.isArray(e)?e.every((e=>this.taxonomyValues.has(e)))||t.push("Invalid category value(s) in categories filter"):t.push("Categories filter must be an array")}validatePagination(e,t,r){void 0!==e&&("number"!=typeof e||e<0)&&r.push("Page must be a non-negative number"),void 0!==t&&("number"!=typeof t||t<=0)&&r.push("PerPage must be a positive number")}}class g{constructor(e){this.locationHelperService=e}validateAndNormalizePrepareParams(e){const t={...e};if(!t.cartId||"string"!=typeof t.cartId)throw new Error("Invalid cartId");return this.validateRecipient(t.recipient),t.billingAddress&&this.validateAddress(t.billingAddress),t.hasSubstitutionPolicy=Boolean(t.hasSubstitutionPolicy),t.isGift=Boolean(t.isGift),t.billingSameAsShipping=Boolean(t.billingSameAsShipping),t.isGift&&this.validateGiftOptions(t.giftOptions),this.validateMarketingPreferences(t.marketingPreferences),t.deliveryTips&&this.validateDeliveryTips(t.deliveryTips),t.refresh=Boolean(t.refresh),t}validateAndNormalizeCompleteParams(e){const t={...e};if(!t.token||"string"!=typeof t.token)throw new Error("Invalid token");if(!t.payment||"string"!=typeof t.payment)throw new Error("Invalid payment token");return void 0!==t.refresh&&(t.refresh=Boolean(t.refresh)),t}validateRecipient(e){if(!e||"object"!=typeof e)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid recipient ${t}`)})),e.hasAgeVerify=Boolean(e.hasAgeVerify)}validateAddress(e){if(!e||"object"!=typeof e)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((t=>{if(!e[t]||"string"!=typeof e[t])throw new Error(`Invalid address ${t}`)})),this.locationHelperService.validateAndNormalizeLocation({address:e})}validateGiftOptions(e){if(!e||"object"!=typeof e)throw new Error("Invalid giftOptions");if(e.message&&"string"!=typeof e.message)throw new Error("Invalid gift message");if(e.recipient){const{name:t,phone:r,email:i}=e.recipient;if(t&&"string"!=typeof t)throw new Error("Invalid gift recipient name");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient phone");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(e){if(!e||"object"!=typeof e)throw new Error("Invalid marketingPreferences");e.canEmail=Boolean(e.canEmail),e.canSms=Boolean(e.canSms)}validateDeliveryTips(e){if(!Array.isArray(e))throw new Error("Invalid deliveryTips");e.forEach((e=>{if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof e.tip||e.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class T{validateAndNormalizeLocation(e){if(!e||"object"!=typeof e)throw new Error("Location must be a valid object");if(e.coords)this.validateCoordinates(e.coords);else{if(!e.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(e.address)}}validateCoordinates(e){if("number"!=typeof e.lat||"number"!=typeof e.long)throw new Error("Coordinates must be valid numbers");if(e.lat<-90||e.lat>90||e.long<-180||e.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(e){if(!e.state||"string"!=typeof e.state)throw new Error("State is required and must be a string");if(e.state=this.normalizeState(e.state),!e.city||"string"!=typeof e.city)throw new Error("City is required and must be a string");if(!e.zip||"string"!=typeof e.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(e){const t=e.toUpperCase();if(a[t])return a[t];const r=e.toUpperCase();if(s[r])return s[r];throw new Error(`Invalid state: ${e}`)}}class f{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)",this.clientSecret=null}async mount(t){if(!document.getElementById(t.elementId))throw new Error(`Element with id "${t.elementId}" not found`);try{this.stripe=await e(t.key)}catch(e){throw new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");this.clientSecret=t.clientSecret;try{const{setupIntent:e}=await this.stripe.retrieveSetupIntent(this.clientSecret);if("succeeded"===(null==e?void 0:e.status))throw new Error(`The client secret (${this.clientSecret}) has already been used previously. Generate a new one through a use session.`)}catch(e){throw e}const r={clientSecret:t.clientSecret,appearance:this.mapAppearance(t.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(r);const i=this.mapElementOptions(t.elementOptions);this.paymentElement=this.elements.create("payment",i),this.paymentElement.mount(`#${t.elementId}`)}async generateToken(){var e,t,r,i,a,s,n,o,c,l,d,h;if(!this.stripe||!this.elements||!this.clientSecret)return{type:"client_error",message:"Payment form has not been initialized"};const{error:u}=await this.elements.submit();if(u)return{type:"validation_error",message:u.message,code:u.code};const{error:I,paymentMethod:A}=await this.stripe.createPaymentMethod({elements:this.elements}),E=await this.stripe.confirmSetup({elements:this.elements,redirect:"if_required"});return E.error?{type:"confirm_error",message:null!==(t=null===(e=null==E?void 0:E.error)||void 0===e?void 0:e.message)&&void 0!==t?t:"",code:null!==(i=null===(r=null==E?void 0:E.error)||void 0===r?void 0:r.code)&&void 0!==i?i:""}:I?{type:"validation_error"===I.type?"validation_error":"api_error",message:I.message,code:I.code,param:I.param}:A?{id:A.id,type:A.type,card:(null==A?void 0:A.card)?{brand:null!==(s=null===(a=A.card)||void 0===a?void 0:a.brand)&&void 0!==s?s:"",country:null!==(n=A.card.country)&&void 0!==n?n:"",expMonth:null!==(o=A.card.exp_month)&&void 0!==o?o:0,expYear:null!==(c=A.card.exp_year)&&void 0!==c?c:0,last4:null!==(l=A.card.last4)&&void 0!==l?l:"",funding:null!==(d=A.card.funding)&&void 0!==d?d:""}:void 0,created:null!==(h=null==A?void 0:A.created)&&void 0!==h?h:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.on(e,t)}unsubscribe(e,t){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(e))throw new Error(this.eventsErrorMsg);this.paymentElement.off(e,t)}mapAppearance(e){if(e)return{theme:"night"===e.theme?"night":"stripe"}}mapElementOptions(e){return{layout:null==e?void 0:e.layout,wallets:{applePay:"auto",googlePay:"auto"}}}unmount(){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");this.paymentElement.unmount()}collapse(){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");this.paymentElement.collapse()}destroy(){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");this.paymentElement.destroy()}}class w{constructor(e){this.client=e}async autocomplete(e,t){try{return await this.client.post("/address/autocomplete",{...e,key:t})}catch(e){throw console.error("Address autocomplete request failed:",e),e}}async details(e,t){try{return await this.client.post("/address/details",{...e,key:t})}catch(e){throw console.error("Address details request failed:",e),e}}}class D{constructor(e,t){this.client=e,this.cartHelperService=t,this.servicePath="/cart/update"}async get(e,t){try{let r=this.cartHelperService.validateId(e);if(r=""!==r&&r,r){const e={id:r};return"boolean"==typeof t&&(e.refresh=t),await this.client.post(this.servicePath,e)}return await this.client.post(this.servicePath)}catch(e){throw console.error("Cart update request failed:",e),e}}async update(e){try{const t=this.cartHelperService.validateAndNormalizeParams(e);return await this.client.post(this.servicePath,t)}catch(e){throw console.error("Cart update request failed:",e),e}}}class P{constructor(e,t){this.client=e,this.catalogHelperService=t,this.servicePath="/catalog/"}async availability(e){try{const t=this.catalogHelperService.validateAndNormalizeParams(e);return await this.client.post(`${this.servicePath}availability`,t)}catch(e){throw console.error("Catalog availability request failed:",e),e}}async search(e){try{const t=this.catalogHelperService.validateAndNormalizeSearchParams(e);if(null==t?void 0:t.error)throw new Error(null==t?void 0:t.error);return await this.client.post(`${this.servicePath}search`,t)}catch(e){throw console.error("Catalog search request failed:",e),e}}}class L{constructor(e,t){this.client=e,this.checkoutHelperService=t,this.servicePath="/checkout"}async prepare(e){try{const t=this.checkoutHelperService.validateAndNormalizePrepareParams(e);return await this.client.post(`${this.servicePath}/prepare`,t)}catch(e){throw console.error("Checkout prepare request failed:",e),e}}async complete(e){try{const t=this.checkoutHelperService.validateAndNormalizeCompleteParams(e);return await this.client.post(`${this.servicePath}/complete`,t)}catch(e){throw console.error("Checkout complete request failed:",e),e}}}class M{constructor(e){this.paymentProvider=e,this.collapse=()=>this.paymentProvider.collapse(),this.unmount=()=>this.paymentProvider.unmount(),this.destroy=()=>this.paymentProvider.destroy()}async mount(e){try{await this.paymentProvider.mount(e)}catch(e){throw console.error("Failed to inject payment element:",e),e}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(e,t){this.paymentProvider.subscribe(e,t)}unsubscribe(e,t){this.paymentProvider.unsubscribe(e,t)}}class _{constructor(e){this.client=e,this.servicePath="/users"}async createOrUpdateSession(e){try{if(!(null==e?void 0:e.id)&&!(null==e?void 0:e.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,e)}catch(e){throw console.error("User session creation/update request failed:",e),e}}async purge(e){try{if(!e)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${e}`)}catch(e){throw console.error("User purge request failed:",e),e}}async addAddress(e){try{if(!(e.customerId&&e.one&&e.city&&e.state&&e.zip&&e.type))throw new Error("Missing required parameters to add address");return await this.client.post(`${this.servicePath}/addresses/add`,e)}catch(e){throw console.error("User address add request failed:",e),e}}async updateAddress(e){try{if(!(e.customerId&&e.one&&e.city&&e.state&&e.zip&&e.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,e)}catch(e){throw console.error("User address update request failed:",e),e}}async purgeAddress(e){try{if(!e)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${e}`)}catch(e){throw console.error("Address purge request failed:",e),e}}async addPayment(e){try{if(!e.customerId||!e.paymentMethodId)throw new Error("Missing required parameters to add payment");return void 0===(null==e?void 0:e.isDefault)&&(null==e||delete e.isDefault),await this.client.post(`${this.servicePath}/payments/add`,e)}catch(e){throw console.error("User add payment request failed:",e),e}}async updatePayment(e){try{if(!e.customerId||!e.paymentMethodId||void 0===(null==e?void 0:e.isDefault)||"boolean"!=typeof(null==e?void 0:e.isDefault))throw new Error("Missing required parameters to add payment");return await this.client.post(`${this.servicePath}/payments/update`,e)}catch(e){throw console.error("User add payment request failed:",e),e}}async purgePayment(e,t){try{if(!e||!t)throw new Error("Missing required parameters for payment purge");return await this.client.delete(`${this.servicePath}/payments/purge/${e}/${t}`)}catch(e){throw console.error("Address purge request failed:",e),e}}}class H{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return H.instance||(H.instance=new H),H.instance}setLiquidCommerceClientConstructor(e){this.liquidCommerceClientConstructor=e}async getLiquidCommerceClient(e,t){const r=`LiquidCommerceClient_${e}_${JSON.stringify(t)}`;if(!this.services.has(r)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const i=new this.liquidCommerceClientConstructor(e,t);await i.init(),this.services.set(r,i)}return this.services.get(r)}getOrCreateService(e,t,...r){if(!this.services.has(e)){const i="getInstance"in t?t.getInstance(...r):new t(...r);this.services.set(e,i)}return this.services.get(e)}getAuthenticatedClient(e){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(e)}`,C,e)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",T)}getAddressService(e){return this.getOrCreateService(`AddressService_${e.getUniqueKey()}`,w,e)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",O,this.getLocationHelperService())}getCatalogService(e){return this.getOrCreateService(`CatalogService_${e.getUniqueKey()}`,P,e,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",N,this.getLocationHelperService())}getCartService(e){return this.getOrCreateService(`CartService_${e.getUniqueKey()}`,D,e,this.getCartHelperService())}getUserService(e){return this.getOrCreateService(`UserService_${e.getUniqueKey()}`,_,e)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",f)}getPaymentService(){return this.getOrCreateService("PaymentService",M,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",g,this.getLocationHelperService())}getCheckoutService(e){return this.getOrCreateService(`CheckoutService_${e.getUniqueKey()}`,L,e,this.getCheckoutHelperService())}}H.instance=null;class b{constructor(e,t){this.address={autocomplete:async e=>(await this.ensureAuthenticated(),this.addressService.autocomplete(e,this.config.googlePlacesApiKey)),details:async e=>(await this.ensureAuthenticated(),this.addressService.details(e,this.config.googlePlacesApiKey))},this.catalog={availability:async e=>(await this.ensureAuthenticated(),this.catalogService.availability(e)),search:async e=>(await this.ensureAuthenticated(),this.catalogService.search(e))},this.cart={get:async(e,t)=>(await this.ensureAuthenticated(),this.cartService.get(e,t)),update:async e=>(await this.ensureAuthenticated(),this.cartService.update(e))},this.user={session:async e=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(e)),purge:async e=>(await this.ensureAuthenticated(),this.userService.purge(e)),addAddress:async e=>(await this.ensureAuthenticated(),this.userService.addAddress(e)),updateAddress:async e=>(await this.ensureAuthenticated(),this.userService.updateAddress(e)),purgeAddress:async e=>(await this.ensureAuthenticated(),this.userService.purgeAddress(e)),addPayment:async e=>(await this.ensureAuthenticated(),this.userService.addPayment(e)),updatePayment:async e=>(await this.ensureAuthenticated(),this.userService.updatePayment(e)),purgePayment:async(e,t)=>(await this.ensureAuthenticated(),this.userService.purgePayment(e,t))},this.payment={mount:async e=>(await this.ensureAuthenticated(),this.paymentService.mount(e)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(e,t)=>{this.paymentService.subscribe(e,t)},unsubscribe:(e,t)=>{this.paymentService.unsubscribe(e,t)},collapse:()=>{this.paymentService.collapse()},unmount:()=>{this.paymentService.unmount()},destroy:()=>{this.paymentService.destroy()}},this.checkout={prepare:async e=>(await this.ensureAuthenticated(),this.checkoutService.prepare(e)),complete:async e=>(await this.ensureAuthenticated(),this.checkoutService.complete(e))},this.config=t,this.singletonManager=H.getInstance();const r=this.determineBaseURL(t);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:e,baseURL:r}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(e){const r=e.env||t.STAGE;return R[r]}async init(){try{await this.authenticatedClient.authenticate()}catch(e){throw console.error("Failed to initialize LiquidCommerceClient:",e),new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}async function U(e,t){const r=H.getInstance();r.setLiquidCommerceClientConstructor(b);return await r.getLiquidCommerceClient(e,t)}export{v as CART_EVENT_ENUM,m as CART_PARAM_ERROR_ENUM,i as DAYS_OF_WEEK,y as ENUM_ADDRESS_TYPE,p as ENUM_AVAILABILITY_VALUE,n as ENUM_BEER,A as ENUM_FILTER_KEYS,o as ENUM_FOOD,c as ENUM_MERCHANDISE,l as ENUM_MISCELLANEOUS,r as ENUM_MODALITIES,E as ENUM_NAVIGATION_ORDER_DIRECTION_TYPE,d as ENUM_NON_ALCOHOLIC,S as ENUM_ORDER_BY,h as ENUM_READY_TO_DRINK,u as ENUM_SPIRITS,I as ENUM_WINE,t as LIQUID_COMMERCE_ENV,U as LiquidCommerce,a as STATES_CODE,s as STATES_NAME};
@@ -1 +1 @@
1
- "use strict";var LIQUID_COMMERCE_ENV,t,e,r,i,s,o,a,n,h,c,d,l,p,I,u,E,S,w,v=require("@stripe/stripe-js");exports.LIQUID_COMMERCE_ENV=void 0,(LIQUID_COMMERCE_ENV=exports.LIQUID_COMMERCE_ENV||(exports.LIQUID_COMMERCE_ENV={})).LOC="loc",LIQUID_COMMERCE_ENV.STAGE="stage",LIQUID_COMMERCE_ENV.PROD="prod",LIQUID_COMMERCE_ENV.DEV="dev",exports.ENUM_MODALITIES=void 0,(t=exports.ENUM_MODALITIES||(exports.ENUM_MODALITIES={})).ON_DEMAND="onDemand",t.SHIPPING="shipping",exports.DAYS_OF_WEEK=void 0,(e=exports.DAYS_OF_WEEK||(exports.DAYS_OF_WEEK={})).MONDAY="monday",e.TUESDAY="tuesday",e.WEDNESDAY="wednesday",e.THURSDAY="thursday",e.FRIDAY="friday",e.SATURDAY="saturday",e.SUNDAY="sunday",exports.STATES_CODE=void 0,(r=exports.STATES_CODE||(exports.STATES_CODE={})).AL="AL",r.AK="AK",r.AR="AR",r.CA="CA",r.CO="CO",r.CT="CT",r.DE="DE",r.DC="DC",r.FL="FL",r.GA="GA",r.HI="HI",r.ID="ID",r.IL="IL",r.IN="IN",r.IA="IA",r.KS="KS",r.KY="KY",r.LA="LA",r.ME="ME",r.MD="MD",r.MA="MA",r.MI="MI",r.MN="MN",r.MS="MS",r.MO="MO",r.MT="MT",r.NE="NE",r.NV="NV",r.NH="NH",r.NJ="NJ",r.NM="NM",r.NY="NY",r.NC="NC",r.ND="ND",r.OH="OH",r.OK="OK",r.OR="OR",r.PA="PA",r.RI="RI",r.SC="SC",r.SD="SD",r.TN="TN",r.TX="TX",r.UT="UT",r.VT="VT",r.VA="VA",r.WA="WA",r.WV="WV",r.WI="WI",r.WY="WY",exports.STATES_NAME=void 0,(i=exports.STATES_NAME||(exports.STATES_NAME={})).ALABAMA="AL",i.ALASKA="AK",i.ARKANSAS="AR",i.CALIFORNIA="CA",i.COLORADO="CO",i.CONNECTICUT="CT",i.DELAWARE="DE",i.DISTRICT_OF_COLUMBIA="DC",i.FLORIDA="FL",i.GEORGIA="GA",i.HAWAII="HI",i.IDAHO="ID",i.ILLINOIS="IL",i.INDIANA="IN",i.IOWA="IA",i.KANSAS="KS",i.KENTUCKY="KY",i.LOUISIANA="LA",i.MAINE="ME",i.MARYLAND="MD",i.MASSACHUSETTS="MA",i.MICHIGAN="MI",i.MINNESOTA="MN",i.MISSISSIPPI="MS",i.MISSOURI="MO",i.MONTANA="MT",i.NEBRASKA="NE",i.NEVADA="NV",i.NEW_HAMPSHIRE="NH",i.NEW_JERSEY="NJ",i.NEW_MEXICO="NM",i.NEW_YORK="NY",i.NORTH_CAROLINA="NC",i.NORTH_DAKOTA="ND",i.OHIO="OH",i.OKLAHOMA="OK",i.OREGON="OR",i.PENNSYLVANIA="PA",i.RHODE_ISLAND="RI",i.SOUTH_CAROLINA="SC",i.SOUTH_DAKOTA="SD",i.TENNESSEE="TN",i.TEXAS="TX",i.UTAH="UT",i.VERMONT="VT",i.VIRGINIA="VA",i.WASHINGTON="WA",i.WEST_VIRGINIA="WV",i.WISCONSIN="WI",i.WYOMING="WY",exports.ENUM_BEER=void 0,(s=exports.ENUM_BEER||(exports.ENUM_BEER={})).ALE="BEER > ALE",s.LAGER="BEER > LAGER",s.MAIN="BEER",s.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",s.OTHER_BEER="BEER > OTHER BEER",exports.ENUM_FOOD=void 0,(o=exports.ENUM_FOOD||(exports.ENUM_FOOD={})).BASE="FOOD",o.PANTRY_OTHER="FOOD > PANTRY > OTHER",exports.ENUM_MERCHANDISE=void 0,(a=exports.ENUM_MERCHANDISE||(exports.ENUM_MERCHANDISE={})).BASE="MERCHANDISE",a.GLASSWARE="MERCHANDISE > GLASSWARE",a.HUMIDOR="MERCHANDISE > HUMIDOR",exports.ENUM_MISCELLANEOUS=void 0,(n=exports.ENUM_MISCELLANEOUS||(exports.ENUM_MISCELLANEOUS={})).BASE="MISCELLANEOUS",n.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",n.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",n.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP",exports.ENUM_NON_ALCOHOLIC=void 0,(h=exports.ENUM_NON_ALCOHOLIC||(exports.ENUM_NON_ALCOHOLIC={})).BASE="NON ALCOHOLIC",h.BITTERS="NON ALCOHOLIC > BITTERS",h.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",h.COFFEE="NON ALCOHOLIC > COFFEE",h.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",h.JUICE="NON ALCOHOLIC > JUICE",h.SODA="NON ALCOHOLIC > SODA",h.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",h.SPIRITS="NON ALCOHOLIC > SPIRITS",h.TEA="NON ALCOHOLIC > TEA",h.WATER="NON ALCOHOLIC > WATER",h.WINE="NON ALCOHOLIC > WINE",exports.ENUM_READY_TO_DRINK=void 0,(c=exports.ENUM_READY_TO_DRINK||(exports.ENUM_READY_TO_DRINK={})).BASE="READY TO DRINK",c.HARD_CIDER="READY TO DRINK > HARD CIDER",c.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",c.HARD_TEA="READY TO DRINK > HARD TEA",c.MALT_BASED="READY TO DRINK > MALT BASED",c.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",c.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",c.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",c.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",c.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",c.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS",exports.ENUM_SPIRITS=void 0,(d=exports.ENUM_SPIRITS||(exports.ENUM_SPIRITS={})).BASE="SPIRITS",d.BAIJIU="SPIRITS > BAIJIU",d.BITTERS="SPIRITS > BITTERS",d.BRANDY="SPIRITS > BRANDY",d.CACHACA="SPIRITS > CACHACA",d.GIN="SPIRITS > GIN",d.LAGER="SPIRITS > LAGER",d.LIQUEUR="SPIRITS > LIQUEUR",d.MEZCAL="SPIRITS > MEZCAL",d.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",d.RUM="SPIRITS > RUM",d.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",d.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",d.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",d.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",d.RUM_OTHER="SPIRITS > RUM > OTHER",d.RUM_SPICED="SPIRITS > RUM > SPICED",d.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",d.SOJU="SPIRITS > SOJU",d.TEQUILA="SPIRITS > TEQUILA",d.VODKA="SPIRITS > VODKA",d.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",d.WHISKEY="SPIRITS > WHISKEY",d.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",d.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",d.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",d.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",d.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH",exports.ENUM_WINE=void 0,(l=exports.ENUM_WINE||(exports.ENUM_WINE={})).BASE="WINE",l.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",l.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",l.COOKING="WINE > COOKING",l.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",l.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",l.RED_WINE="WINE > RED WINE",l.ROSE_WINE="WINE > ROSE WINE",l.SAKE="WINE > SAKE",l.WHITE_WINE="WINE > WHITE WINE",exports.ENUM_FILTER_KEYS=void 0,(p=exports.ENUM_FILTER_KEYS||(exports.ENUM_FILTER_KEYS={})).BRANDS="brands",p.FLAVOR="flavor",p.REGION="region",p.VARIETY="variety",p.PRICE="price",p.AVAILABILITY="availability",p.CATEGORIES="categories",p.SIZES="sizes",p.COLORS="colors",p.APPELLATION="appellation",p.COUNTRY="country",p.VINTAGE="vintage",p.MATERIALS="materials",exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE=void 0,(I=exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE||(exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE={})).ASC="asc",I.DESC="desc",exports.ENUM_ORDER_BY=void 0,(exports.ENUM_ORDER_BY||(exports.ENUM_ORDER_BY={})).PRICE="price",exports.ENUM_AVAILABILITY_VALUE=void 0,(u=exports.ENUM_AVAILABILITY_VALUE||(exports.ENUM_AVAILABILITY_VALUE={})).UNSPECIFIED="AVAILABILITY_UNSPECIFIED",u.IN_STOCK="IN_STOCK",u.OUT_OF_STOCK="OUT_OF_STOCK",u.PREORDER="PREORDER",u.BACKORDER="BACKORDER",exports.CART_PARAM_ERROR_ENUM=void 0,(E=exports.CART_PARAM_ERROR_ENUM||(exports.CART_PARAM_ERROR_ENUM={})).INVALID_ITEMS_TYPE="Items must be a non-empty array",E.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",E.INVALID_PART_NUMBER="The partnerNumber provided is invalid",E.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid",exports.CART_EVENT_ENUM=void 0,(S=exports.CART_EVENT_ENUM||(exports.CART_EVENT_ENUM={})).OOS="OutOfStock",S.ITEMS_NOT_ADDED="ItemsNotAdded",S.ITEMS_REQUESTED_NOT_ADDED="ItemsRequestedNotAdded",S.ITEM_NOT_ENGRAVED="ItemEngravingError",S.ADDRESS_CHANGE="AddressChange",S.LOCATION_AVAILABILITY="LocationAvailability",S.REMOVED_EXISTING_ITEMS="RemovedExistingCartItems",S.RETAILER_MIN="RetailerMinNotMet",S.NO_ITEMS_IN_CART="NoItemsInCart",S.INVALID_ID="InvalidId",S.NO_ID="NoId",S.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",S.NEW_CART="NewCart",S.DEFAULT="CartError",S.ITEM_QTY_CHANGE="ItemQuantityChange",exports.ENUM_ADDRESS_TYPE=void 0,(w=exports.ENUM_ADDRESS_TYPE||(exports.ENUM_ADDRESS_TYPE={})).SHIPPING="shipping",w.BILLING="billing";const y={[exports.LIQUID_COMMERCE_ENV.LOC]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.DEV]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.STAGE]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.PROD]:"https://staging.cloud.liquidcommerce.co/api"};class A{constructor(t){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(t,e)=>new Promise(((r,i)=>{const s=new XMLHttpRequest;s.open(e.method||"GET",t),Object.entries(e.headers).forEach((([t,e])=>{s.setRequestHeader(t,e)})),s.onload=()=>{r({ok:s.status>=200&&s.status<300,status:s.status,statusText:s.statusText,headers:s.getAllResponseHeaders().split("\r\n").reduce(((t,e)=>{const[r,i]=e.split(": ");return r&&(t[r]=i),t}),{}),json:()=>Promise.resolve(JSON.parse(s.responseText)),text:()=>Promise.resolve(s.responseText)})},s.onerror=()=>{i(new TypeError("Network request failed"))},s.send(e.body)})),this.apiKey=t.apiKey,this.baseURL=t.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(t){return A.instance||(A.instance=new A(t)),A.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):this.xhrFetch}fetchAdapter(t){return async(e,r)=>{var i;const s=await t(e,r);let o;return"function"==typeof(null===(i=s.headers)||void 0===i?void 0:i.entries)?o=Object.fromEntries(s.headers.entries()):(o={},s.headers.forEach(((t,e)=>{o[e]=t}))),{ok:s.ok,status:s.status,statusText:s.statusText,headers:o,json:()=>s.json(),text:()=>s.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var t,e;if(this.isAuthenticating)await new Promise((t=>{const e=()=>{this.isAuthenticating?setTimeout(e,100):t(void 0)};e()}));else{this.isAuthenticating=!0;try{const r=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.token,this.tokenExpiration=Date.now()+1e3*(null===(e=null==r?void 0:r.data)||void 0===e?void 0:e.exp)}catch(t){throw new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(t,e){const r=new URL(`api${t}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...e.headers},s={method:e.method,headers:i,body:e.body?JSON.stringify(e.body):void 0},o=await this.httpClient(r.toString(),s);if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return o.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(t,e){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const r=new URL(`api${t}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...e.headers},s={method:e.method,headers:i,body:e.body?JSON.stringify(e.body):void 0},o=await this.httpClient(r.toString(),s);if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return o.json()}async get(t,e){return this.request(t,{method:"GET",headers:e})}async post(t,e,r){return this.request(t,{method:"POST",body:e,headers:r})}async put(t,e,r){return this.request(t,{method:"PUT",body:e,headers:r})}async delete(t,e){return this.request(t,{method:"DELETE",headers:e})}}A.instance=null;class m{constructor(t){this.locationHelperService=t}validateAndNormalizeParams(t){const e={...t};return e.id=this.validateId(e.id),e.items=this.validateAndNormalizeItems(e.items),this.locationHelperService.validateAndNormalizeLocation(e.loc),e.refresh=Boolean(e.refresh),e}validateId(t){return t&&"string"==typeof t&&0!==t.trim().length?t.trim():""}validateAndNormalizeItems(t){if(!Array.isArray(t)||0===t.length)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_ITEMS_TYPE);if(t.length>25)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_ITEMS_MAX);return t.map((t=>this.validateAndNormalizeItem(t)))}validateAndNormalizeItem(t){const e={...t};if(!this.validatePartNumber(e.partNumber))throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_PART_NUMBER);if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId||0===e.fulfillmentId.trim().length)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_FULFILLMENT_ID);return e.quantity=Math.max(0,Math.floor(e.quantity)),e.engravingLines&&(e.engravingLines=e.engravingLines.map((t=>t.trim())).filter((t=>t.length>0))),e}validatePartNumber(t){if(!t||"string"!=typeof t)return!1;const e=t.split("_");return 2===e.length&&14===e[0].length&&e[1].length>0}}class R{constructor(t){this.locationServiceHelper=t,this.taxonomyValues=new Set([...Object.values(exports.ENUM_BEER),...Object.values(exports.ENUM_FOOD),...Object.values(exports.ENUM_MERCHANDISE),...Object.values(exports.ENUM_NON_ALCOHOLIC),...Object.values(exports.ENUM_READY_TO_DRINK),...Object.values(exports.ENUM_SPIRITS),...Object.values(exports.ENUM_WINE)])}validateAndNormalizeParams(t){const e={...t};return this.validateUPCs(e.upcs),this.locationServiceHelper.validateAndNormalizeLocation(e.loc),e}validateAndNormalizeSearchParams(t){const e=[],r={...t};return this.validateOrderBy(r.orderBy,e),this.validateOrderDirection(r.orderDirection,e),this.validateFilters(r.filters,e),this.validatePagination(r.page,r.perPage,e),this.locationServiceHelper.validateAndNormalizeLocation(r.loc),e.length>0?{...r,error:e.join(". ")}:r}validateUPCs(t){if(!Array.isArray(t)||0===t.length)throw new Error("UPCs must be a non-empty array of strings");if(!t.every((t=>"string"==typeof t&&t.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(t,e){t&&!Object.values(exports.ENUM_ORDER_BY).includes(t)&&e.push(`Invalid orderBy value: ${t}`)}validateOrderDirection(t,e){t&&!Object.values(exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE).includes(t)&&e.push(`Invalid orderDirection value: ${t}`)}validateFilters(t,e){t&&(t.length>10&&e.push("Maximum of 10 filters allowed"),t.forEach((t=>{switch(Object.values(exports.ENUM_FILTER_KEYS).includes(t.key)||e.push(`Invalid filter key: ${t.key}`),t.key){case exports.ENUM_FILTER_KEYS.AVAILABILITY:this.validateAvailabilityFilter(t.values,e);break;case exports.ENUM_FILTER_KEYS.BRANDS:this.validateArrayFilter(t.values,30,"brands",e);break;case exports.ENUM_FILTER_KEYS.CATEGORIES:this.validateCategoriesFilter(t.values,e);break;case exports.ENUM_FILTER_KEYS.COLORS:this.validateArrayFilter(t.values,75,"colors",e)}})))}validateAvailabilityFilter(t,e){Object.values(exports.ENUM_AVAILABILITY_VALUE).includes(t)||e.push(`Invalid availability value: ${t}`)}validateArrayFilter(t,e,r,i){Array.isArray(t)?t.length>e&&i.push(`${r} filter can have a maximum of ${e} values`):i.push(`${r} filter must be an array`)}validateCategoriesFilter(t,e){Array.isArray(t)?t.every((t=>this.taxonomyValues.has(t)))||e.push("Invalid category value(s) in categories filter"):e.push("Categories filter must be an array")}validatePagination(t,e,r){void 0!==t&&("number"!=typeof t||t<0)&&r.push("Page must be a non-negative number"),void 0!==e&&("number"!=typeof e||e<=0)&&r.push("PerPage must be a positive number")}}class O{constructor(t){this.locationHelperService=t}validateAndNormalizePrepareParams(t){const e={...t};if(!e.cartId||"string"!=typeof e.cartId)throw new Error("Invalid cartId");return this.validateRecipient(e.recipient),e.billingAddress&&this.validateAddress(e.billingAddress),e.hasSubstitutionPolicy=Boolean(e.hasSubstitutionPolicy),e.isGift=Boolean(e.isGift),e.billingSameAsShipping=Boolean(e.billingSameAsShipping),e.isGift&&this.validateGiftOptions(e.giftOptions),this.validateMarketingPreferences(e.marketingPreferences),e.deliveryTips&&this.validateDeliveryTips(e.deliveryTips),e.refresh=Boolean(e.refresh),e}validateAndNormalizeCompleteParams(t){const e={...t};if(!e.token||"string"!=typeof e.token)throw new Error("Invalid token");if(!e.payment||"string"!=typeof e.payment)throw new Error("Invalid payment token");return void 0!==e.refresh&&(e.refresh=Boolean(e.refresh)),e}validateRecipient(t){if(!t||"object"!=typeof t)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((e=>{if(!t[e]||"string"!=typeof t[e])throw new Error(`Invalid recipient ${e}`)})),t.hasAgeVerify=Boolean(t.hasAgeVerify)}validateAddress(t){if(!t||"object"!=typeof t)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((e=>{if(!t[e]||"string"!=typeof t[e])throw new Error(`Invalid address ${e}`)})),this.locationHelperService.validateAndNormalizeLocation({address:t})}validateGiftOptions(t){if(!t||"object"!=typeof t)throw new Error("Invalid giftOptions");if(t.message&&"string"!=typeof t.message)throw new Error("Invalid gift message");if(t.recipient){const{name:e,phone:r,email:i}=t.recipient;if(e&&"string"!=typeof e)throw new Error("Invalid gift recipient name");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient phone");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(t){if(!t||"object"!=typeof t)throw new Error("Invalid marketingPreferences");t.canEmail=Boolean(t.canEmail),t.canSms=Boolean(t.canSms)}validateDeliveryTips(t){if(!Array.isArray(t))throw new Error("Invalid deliveryTips");t.forEach((t=>{if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof t.tip||t.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class N{validateAndNormalizeLocation(t){if(!t||"object"!=typeof t)throw new Error("Location must be a valid object");if(t.coords)this.validateCoordinates(t.coords);else{if(!t.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(t.address)}}validateCoordinates(t){if("number"!=typeof t.lat||"number"!=typeof t.long)throw new Error("Coordinates must be valid numbers");if(t.lat<-90||t.lat>90||t.long<-180||t.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(t){if(!t.state||"string"!=typeof t.state)throw new Error("State is required and must be a string");if(t.state=this.normalizeState(t.state),!t.city||"string"!=typeof t.city)throw new Error("City is required and must be a string");if(!t.zip||"string"!=typeof t.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(t){const e=t.toUpperCase();if(exports.STATES_CODE[e])return exports.STATES_CODE[e];const r=t.toUpperCase();if(exports.STATES_NAME[r])return exports.STATES_NAME[r];throw new Error(`Invalid state: ${t}`)}}class f{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)"}async mount(t){if(!document.getElementById(t.elementId))throw new Error(`Element with id "${t.elementId}" not found`);try{this.stripe=await v.loadStripe(t.key)}catch(t){throw new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");const e={clientSecret:t.clientSecret,appearance:this.mapAppearance(t.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(e);const r=this.mapElementOptions(t.elementOptions);this.paymentElement=this.elements.create("payment",r),this.paymentElement.mount(`#${t.elementId}`)}async generateToken(){var t,e,r,i,s,o,a,n;if(!this.stripe||!this.elements)return{type:"client_error",message:"Payment form has not been initialized"};const{error:h}=await this.elements.submit();if(h)return{type:"validation_error",message:h.message,code:h.code};const{error:c,paymentMethod:d}=await this.stripe.createPaymentMethod({elements:this.elements});return c?{type:"validation_error"===c.type?"validation_error":"api_error",message:c.message,code:c.code,param:c.param}:d?{id:d.id,type:d.type,card:(null==d?void 0:d.card)?{brand:null!==(e=null===(t=d.card)||void 0===t?void 0:t.brand)&&void 0!==e?e:"",country:null!==(r=d.card.country)&&void 0!==r?r:"",expMonth:null!==(i=d.card.exp_month)&&void 0!==i?i:0,expYear:null!==(s=d.card.exp_year)&&void 0!==s?s:0,last4:null!==(o=d.card.last4)&&void 0!==o?o:"",funding:null!==(a=d.card.funding)&&void 0!==a?a:""}:void 0,created:null!==(n=null==d?void 0:d.created)&&void 0!==n?n:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(t,e){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(t))throw new Error(this.eventsErrorMsg);this.paymentElement.on(t,e)}unsubscribe(t,e){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(t))throw new Error(this.eventsErrorMsg);this.paymentElement.off(t,e)}mapAppearance(t){if(t)return{theme:"night"===t.theme?"night":"stripe"}}mapElementOptions(t){return{layout:null==t?void 0:t.layout,wallets:{applePay:"auto",googlePay:"auto"}}}}class C{constructor(t){this.client=t}async autocomplete(t,e){try{return await this.client.post("/address/autocomplete",{...t,key:e})}catch(t){throw t}}async details(t,e){try{return await this.client.post("/address/details",{...t,key:e})}catch(t){throw t}}}class T{constructor(t,e){this.client=t,this.cartHelperService=e,this.servicePath="/cart/update"}async get(t,e){try{let r=this.cartHelperService.validateId(t);if(r=""!==r&&r,r){const t={id:r};return"boolean"==typeof e&&(t.refresh=e),await this.client.post(this.servicePath,t)}return await this.client.post(this.servicePath)}catch(t){throw t}}async update(t){try{const e=this.cartHelperService.validateAndNormalizeParams(t);return await this.client.post(this.servicePath,e)}catch(t){throw t}}}class g{constructor(t,e){this.client=t,this.catalogHelperService=e,this.servicePath="/catalog/"}async availability(t){try{const e=this.catalogHelperService.validateAndNormalizeParams(t);return await this.client.post(`${this.servicePath}availability`,e)}catch(t){throw t}}async search(t){try{const e=this.catalogHelperService.validateAndNormalizeSearchParams(t);if(null==e?void 0:e.error)throw new Error(null==e?void 0:e.error);return await this.client.post(`${this.servicePath}search`,e)}catch(t){throw t}}}class x{constructor(t,e){this.client=t,this.checkoutHelperService=e,this.servicePath="/checkout"}async prepare(t){try{const e=this.checkoutHelperService.validateAndNormalizePrepareParams(t);return await this.client.post(`${this.servicePath}/prepare`,e)}catch(t){throw t}}async complete(t){try{const e=this.checkoutHelperService.validateAndNormalizeCompleteParams(t);return await this.client.post(`${this.servicePath}/complete`,e)}catch(t){throw t}}}class D{constructor(t){this.paymentProvider=t}async mount(t){try{await this.paymentProvider.mount(t)}catch(t){throw t}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(t,e){this.paymentProvider.subscribe(t,e)}unsubscribe(t,e){this.paymentProvider.unsubscribe(t,e)}}class P{constructor(t){this.client=t,this.servicePath="/users"}async createOrUpdateSession(t){try{if(!(null==t?void 0:t.id)&&!(null==t?void 0:t.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,t)}catch(t){throw t}}async purge(t){try{if(!t)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${t}`)}catch(t){throw t}}async updateAddress(t){try{if(!(t.customerId&&t.one&&t.city&&t.state&&t.zip&&t.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,t)}catch(t){throw t}}async purgeAddress(t){try{if(!t)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${t}`)}catch(t){throw t}}}class L{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return L.instance||(L.instance=new L),L.instance}setLiquidCommerceClientConstructor(t){this.liquidCommerceClientConstructor=t}async getLiquidCommerceClient(t,e){const r=`LiquidCommerceClient_${t}_${JSON.stringify(e)}`;if(!this.services.has(r)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const i=new this.liquidCommerceClientConstructor(t,e);await i.init(),this.services.set(r,i)}return this.services.get(r)}getOrCreateService(t,e,...r){if(!this.services.has(t)){const i="getInstance"in e?e.getInstance(...r):new e(...r);this.services.set(t,i)}return this.services.get(t)}getAuthenticatedClient(t){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(t)}`,A,t)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",N)}getAddressService(t){return this.getOrCreateService(`AddressService_${t.getUniqueKey()}`,C,t)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",R,this.getLocationHelperService())}getCatalogService(t){return this.getOrCreateService(`CatalogService_${t.getUniqueKey()}`,g,t,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",m,this.getLocationHelperService())}getCartService(t){return this.getOrCreateService(`CartService_${t.getUniqueKey()}`,T,t,this.getCartHelperService())}getUserService(t){return this.getOrCreateService(`UserService_${t.getUniqueKey()}`,P,t)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",f)}getPaymentService(){return this.getOrCreateService("PaymentService",D,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",O,this.getLocationHelperService())}getCheckoutService(t){return this.getOrCreateService(`CheckoutService_${t.getUniqueKey()}`,x,t,this.getCheckoutHelperService())}}L.instance=null;class b{constructor(t,e){this.address={autocomplete:async t=>(await this.ensureAuthenticated(),this.addressService.autocomplete(t,this.config.googlePlacesApiKey)),details:async t=>(await this.ensureAuthenticated(),this.addressService.details(t,this.config.googlePlacesApiKey))},this.catalog={availability:async t=>(await this.ensureAuthenticated(),this.catalogService.availability(t)),search:async t=>(await this.ensureAuthenticated(),this.catalogService.search(t))},this.cart={get:async(t,e)=>(await this.ensureAuthenticated(),this.cartService.get(t,e)),update:async t=>(await this.ensureAuthenticated(),this.cartService.update(t))},this.user={session:async t=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(t)),purge:async t=>(await this.ensureAuthenticated(),this.userService.purge(t)),updateAddress:async t=>(await this.ensureAuthenticated(),this.userService.updateAddress(t)),purgeAddress:async t=>(await this.ensureAuthenticated(),this.userService.purgeAddress(t))},this.payment={mount:async t=>(await this.ensureAuthenticated(),this.paymentService.mount(t)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(t,e)=>{this.paymentService.subscribe(t,e)},unsubscribe:(t,e)=>{this.paymentService.unsubscribe(t,e)}},this.checkout={prepare:async t=>(await this.ensureAuthenticated(),this.checkoutService.prepare(t)),complete:async t=>(await this.ensureAuthenticated(),this.checkoutService.complete(t))},this.config=e,this.singletonManager=L.getInstance();const r=this.determineBaseURL(e);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:t,baseURL:r}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(t){const e=t.env||exports.LIQUID_COMMERCE_ENV.STAGE;return y[e]}async init(){try{await this.authenticatedClient.authenticate()}catch(t){throw new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}exports.LiquidCommerce=async function(t,e){const r=L.getInstance();return r.setLiquidCommerceClientConstructor(b),await r.getLiquidCommerceClient(t,e)};
1
+ "use strict";var LIQUID_COMMERCE_ENV,t,e,r,i,s,a,o,n,h,d,c,l,u,p,I,E,w,y,m=require("@stripe/stripe-js");exports.LIQUID_COMMERCE_ENV=void 0,(LIQUID_COMMERCE_ENV=exports.LIQUID_COMMERCE_ENV||(exports.LIQUID_COMMERCE_ENV={})).LOC="loc",LIQUID_COMMERCE_ENV.STAGE="stage",LIQUID_COMMERCE_ENV.PROD="prod",LIQUID_COMMERCE_ENV.DEV="dev",exports.ENUM_MODALITIES=void 0,(t=exports.ENUM_MODALITIES||(exports.ENUM_MODALITIES={})).ON_DEMAND="onDemand",t.SHIPPING="shipping",exports.DAYS_OF_WEEK=void 0,(e=exports.DAYS_OF_WEEK||(exports.DAYS_OF_WEEK={})).MONDAY="monday",e.TUESDAY="tuesday",e.WEDNESDAY="wednesday",e.THURSDAY="thursday",e.FRIDAY="friday",e.SATURDAY="saturday",e.SUNDAY="sunday",exports.STATES_CODE=void 0,(r=exports.STATES_CODE||(exports.STATES_CODE={})).AL="AL",r.AK="AK",r.AR="AR",r.CA="CA",r.CO="CO",r.CT="CT",r.DE="DE",r.DC="DC",r.FL="FL",r.GA="GA",r.HI="HI",r.ID="ID",r.IL="IL",r.IN="IN",r.IA="IA",r.KS="KS",r.KY="KY",r.LA="LA",r.ME="ME",r.MD="MD",r.MA="MA",r.MI="MI",r.MN="MN",r.MS="MS",r.MO="MO",r.MT="MT",r.NE="NE",r.NV="NV",r.NH="NH",r.NJ="NJ",r.NM="NM",r.NY="NY",r.NC="NC",r.ND="ND",r.OH="OH",r.OK="OK",r.OR="OR",r.PA="PA",r.RI="RI",r.SC="SC",r.SD="SD",r.TN="TN",r.TX="TX",r.UT="UT",r.VT="VT",r.VA="VA",r.WA="WA",r.WV="WV",r.WI="WI",r.WY="WY",exports.STATES_NAME=void 0,(i=exports.STATES_NAME||(exports.STATES_NAME={})).ALABAMA="AL",i.ALASKA="AK",i.ARKANSAS="AR",i.CALIFORNIA="CA",i.COLORADO="CO",i.CONNECTICUT="CT",i.DELAWARE="DE",i.DISTRICT_OF_COLUMBIA="DC",i.FLORIDA="FL",i.GEORGIA="GA",i.HAWAII="HI",i.IDAHO="ID",i.ILLINOIS="IL",i.INDIANA="IN",i.IOWA="IA",i.KANSAS="KS",i.KENTUCKY="KY",i.LOUISIANA="LA",i.MAINE="ME",i.MARYLAND="MD",i.MASSACHUSETTS="MA",i.MICHIGAN="MI",i.MINNESOTA="MN",i.MISSISSIPPI="MS",i.MISSOURI="MO",i.MONTANA="MT",i.NEBRASKA="NE",i.NEVADA="NV",i.NEW_HAMPSHIRE="NH",i.NEW_JERSEY="NJ",i.NEW_MEXICO="NM",i.NEW_YORK="NY",i.NORTH_CAROLINA="NC",i.NORTH_DAKOTA="ND",i.OHIO="OH",i.OKLAHOMA="OK",i.OREGON="OR",i.PENNSYLVANIA="PA",i.RHODE_ISLAND="RI",i.SOUTH_CAROLINA="SC",i.SOUTH_DAKOTA="SD",i.TENNESSEE="TN",i.TEXAS="TX",i.UTAH="UT",i.VERMONT="VT",i.VIRGINIA="VA",i.WASHINGTON="WA",i.WEST_VIRGINIA="WV",i.WISCONSIN="WI",i.WYOMING="WY",exports.ENUM_BEER=void 0,(s=exports.ENUM_BEER||(exports.ENUM_BEER={})).ALE="BEER > ALE",s.LAGER="BEER > LAGER",s.MAIN="BEER",s.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",s.OTHER_BEER="BEER > OTHER BEER",exports.ENUM_FOOD=void 0,(a=exports.ENUM_FOOD||(exports.ENUM_FOOD={})).BASE="FOOD",a.PANTRY_OTHER="FOOD > PANTRY > OTHER",exports.ENUM_MERCHANDISE=void 0,(o=exports.ENUM_MERCHANDISE||(exports.ENUM_MERCHANDISE={})).BASE="MERCHANDISE",o.GLASSWARE="MERCHANDISE > GLASSWARE",o.HUMIDOR="MERCHANDISE > HUMIDOR",exports.ENUM_MISCELLANEOUS=void 0,(n=exports.ENUM_MISCELLANEOUS||(exports.ENUM_MISCELLANEOUS={})).BASE="MISCELLANEOUS",n.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",n.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",n.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP",exports.ENUM_NON_ALCOHOLIC=void 0,(h=exports.ENUM_NON_ALCOHOLIC||(exports.ENUM_NON_ALCOHOLIC={})).BASE="NON ALCOHOLIC",h.BITTERS="NON ALCOHOLIC > BITTERS",h.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",h.COFFEE="NON ALCOHOLIC > COFFEE",h.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",h.JUICE="NON ALCOHOLIC > JUICE",h.SODA="NON ALCOHOLIC > SODA",h.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",h.SPIRITS="NON ALCOHOLIC > SPIRITS",h.TEA="NON ALCOHOLIC > TEA",h.WATER="NON ALCOHOLIC > WATER",h.WINE="NON ALCOHOLIC > WINE",exports.ENUM_READY_TO_DRINK=void 0,(d=exports.ENUM_READY_TO_DRINK||(exports.ENUM_READY_TO_DRINK={})).BASE="READY TO DRINK",d.HARD_CIDER="READY TO DRINK > HARD CIDER",d.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",d.HARD_TEA="READY TO DRINK > HARD TEA",d.MALT_BASED="READY TO DRINK > MALT BASED",d.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",d.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",d.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",d.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",d.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",d.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS",exports.ENUM_SPIRITS=void 0,(c=exports.ENUM_SPIRITS||(exports.ENUM_SPIRITS={})).BASE="SPIRITS",c.BAIJIU="SPIRITS > BAIJIU",c.BITTERS="SPIRITS > BITTERS",c.BRANDY="SPIRITS > BRANDY",c.CACHACA="SPIRITS > CACHACA",c.GIN="SPIRITS > GIN",c.LAGER="SPIRITS > LAGER",c.LIQUEUR="SPIRITS > LIQUEUR",c.MEZCAL="SPIRITS > MEZCAL",c.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",c.RUM="SPIRITS > RUM",c.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",c.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",c.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",c.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",c.RUM_OTHER="SPIRITS > RUM > OTHER",c.RUM_SPICED="SPIRITS > RUM > SPICED",c.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",c.SOJU="SPIRITS > SOJU",c.TEQUILA="SPIRITS > TEQUILA",c.VODKA="SPIRITS > VODKA",c.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",c.WHISKEY="SPIRITS > WHISKEY",c.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",c.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",c.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",c.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",c.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH",exports.ENUM_WINE=void 0,(l=exports.ENUM_WINE||(exports.ENUM_WINE={})).BASE="WINE",l.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",l.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",l.COOKING="WINE > COOKING",l.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",l.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",l.RED_WINE="WINE > RED WINE",l.ROSE_WINE="WINE > ROSE WINE",l.SAKE="WINE > SAKE",l.WHITE_WINE="WINE > WHITE WINE",exports.ENUM_FILTER_KEYS=void 0,(u=exports.ENUM_FILTER_KEYS||(exports.ENUM_FILTER_KEYS={})).BRANDS="brands",u.FLAVOR="flavor",u.REGION="region",u.VARIETY="variety",u.PRICE="price",u.AVAILABILITY="availability",u.CATEGORIES="categories",u.SIZES="sizes",u.COLORS="colors",u.APPELLATION="appellation",u.COUNTRY="country",u.VINTAGE="vintage",u.MATERIALS="materials",exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE=void 0,(p=exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE||(exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE={})).ASC="asc",p.DESC="desc",exports.ENUM_ORDER_BY=void 0,(exports.ENUM_ORDER_BY||(exports.ENUM_ORDER_BY={})).PRICE="price",exports.ENUM_AVAILABILITY_VALUE=void 0,(I=exports.ENUM_AVAILABILITY_VALUE||(exports.ENUM_AVAILABILITY_VALUE={})).UNSPECIFIED="AVAILABILITY_UNSPECIFIED",I.IN_STOCK="IN_STOCK",I.OUT_OF_STOCK="OUT_OF_STOCK",I.PREORDER="PREORDER",I.BACKORDER="BACKORDER",exports.CART_PARAM_ERROR_ENUM=void 0,(E=exports.CART_PARAM_ERROR_ENUM||(exports.CART_PARAM_ERROR_ENUM={})).INVALID_ITEMS_TYPE="Items must be a non-empty array",E.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",E.INVALID_PART_NUMBER="The partnerNumber provided is invalid",E.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid",exports.CART_EVENT_ENUM=void 0,(w=exports.CART_EVENT_ENUM||(exports.CART_EVENT_ENUM={})).OOS="OutOfStock",w.ITEMS_NOT_ADDED="ItemsNotAdded",w.ITEMS_REQUESTED_NOT_ADDED="ItemsRequestedNotAdded",w.ITEM_NOT_ENGRAVED="ItemEngravingError",w.ADDRESS_CHANGE="AddressChange",w.LOCATION_AVAILABILITY="LocationAvailability",w.REMOVED_EXISTING_ITEMS="RemovedExistingCartItems",w.RETAILER_MIN="RetailerMinNotMet",w.NO_ITEMS_IN_CART="NoItemsInCart",w.INVALID_ID="InvalidId",w.NO_ID="NoId",w.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",w.NEW_CART="NewCart",w.DEFAULT="CartError",w.ITEM_QTY_CHANGE="ItemQuantityChange",exports.ENUM_ADDRESS_TYPE=void 0,(y=exports.ENUM_ADDRESS_TYPE||(exports.ENUM_ADDRESS_TYPE={})).SHIPPING="shipping",y.BILLING="billing";const v={[exports.LIQUID_COMMERCE_ENV.LOC]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.DEV]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.STAGE]:"https://staging.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.PROD]:"https://staging.cloud.liquidcommerce.co/api"};class S{constructor(t){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(t,e)=>new Promise(((r,i)=>{const s=new XMLHttpRequest;s.open(e.method||"GET",t),Object.entries(e.headers).forEach((([t,e])=>{s.setRequestHeader(t,e)})),s.onload=()=>{r({ok:s.status>=200&&s.status<300,status:s.status,statusText:s.statusText,headers:s.getAllResponseHeaders().split("\r\n").reduce(((t,e)=>{const[r,i]=e.split(": ");return r&&(t[r]=i),t}),{}),json:()=>Promise.resolve(JSON.parse(s.responseText)),text:()=>Promise.resolve(s.responseText)})},s.onerror=()=>{i(new TypeError("Network request failed"))},s.send(e.body)})),this.apiKey=t.apiKey,this.baseURL=t.baseURL,this.httpClient=this.getFetchImplementation()}static getInstance(t){return S.instance||(S.instance=new S(t)),S.instance}getFetchImplementation(){return"undefined"!=typeof fetch?this.fetchAdapter(fetch):"undefined"!=typeof global&&global.fetch?this.fetchAdapter(global.fetch):this.xhrFetch}fetchAdapter(t){return async(e,r)=>{var i;const s=await t(e,r);let a;return"function"==typeof(null===(i=s.headers)||void 0===i?void 0:i.entries)?a=Object.fromEntries(s.headers.entries()):(a={},s.headers.forEach(((t,e)=>{a[e]=t}))),{ok:s.ok,status:s.status,statusText:s.statusText,headers:a,json:()=>s.json(),text:()=>s.text()}}}getUniqueKey(){return`${this.apiKey}_${this.baseURL}`}async authenticate(){var t,e;if(this.isAuthenticating)await new Promise((t=>{const e=()=>{this.isAuthenticating?setTimeout(e,100):t(void 0)};e()}));else{this.isAuthenticating=!0;try{const r=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(t=null==r?void 0:r.data)||void 0===t?void 0:t.token,this.tokenExpiration=Date.now()+1e3*(null===(e=null==r?void 0:r.data)||void 0===e?void 0:e.exp)}catch(t){throw new Error("Failed to authenticate with LiquidCommerce API")}finally{this.isAuthenticating=!1}}}async requestWithoutAuth(t,e){const r=new URL(`api${t}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...e.headers},s={method:e.method,headers:i,body:e.body?JSON.stringify(e.body):void 0},a=await this.httpClient(r.toString(),s);if(!a.ok)throw new Error(`HTTP error! status: ${a.status}`);return a.json()}isTokenExpired(){return!this.tokenExpiration||Date.now()>=this.tokenExpiration}async request(t,e){this.accessToken&&!this.isTokenExpired()||await this.authenticate();const r=new URL(`api${t}`,this.baseURL),i={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...e.headers},s={method:e.method,headers:i,body:e.body?JSON.stringify(e.body):void 0},a=await this.httpClient(r.toString(),s);if(!a.ok)throw new Error(`HTTP error! status: ${a.status}`);return a.json()}async get(t,e){return this.request(t,{method:"GET",headers:e})}async post(t,e,r){return this.request(t,{method:"POST",body:e,headers:r})}async put(t,e,r){return this.request(t,{method:"PUT",body:e,headers:r})}async delete(t,e){return this.request(t,{method:"DELETE",headers:e})}}S.instance=null;class A{constructor(t){this.locationHelperService=t}validateAndNormalizeParams(t){const e={...t};return e.id=this.validateId(e.id),e.items=this.validateAndNormalizeItems(e.items),this.locationHelperService.validateAndNormalizeLocation(e.loc),e.refresh=Boolean(e.refresh),e}validateId(t){return t&&"string"==typeof t&&0!==t.trim().length?t.trim():""}validateAndNormalizeItems(t){if(!Array.isArray(t)||0===t.length)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_ITEMS_TYPE);if(t.length>25)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_ITEMS_MAX);return t.map((t=>this.validateAndNormalizeItem(t)))}validateAndNormalizeItem(t){const e={...t};if(!this.validatePartNumber(e.partNumber))throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_PART_NUMBER);if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId||0===e.fulfillmentId.trim().length)throw new Error(exports.CART_PARAM_ERROR_ENUM.INVALID_FULFILLMENT_ID);return e.quantity=Math.max(0,Math.floor(e.quantity)),e.engravingLines&&(e.engravingLines=e.engravingLines.map((t=>t.trim())).filter((t=>t.length>0))),e}validatePartNumber(t){if(!t||"string"!=typeof t)return!1;const e=t.split("_");return 2===e.length&&14===e[0].length&&e[1].length>0}}class R{constructor(t){this.locationServiceHelper=t,this.taxonomyValues=new Set([...Object.values(exports.ENUM_BEER),...Object.values(exports.ENUM_FOOD),...Object.values(exports.ENUM_MERCHANDISE),...Object.values(exports.ENUM_NON_ALCOHOLIC),...Object.values(exports.ENUM_READY_TO_DRINK),...Object.values(exports.ENUM_SPIRITS),...Object.values(exports.ENUM_WINE)])}validateAndNormalizeParams(t){const e={...t};return this.validateUPCs(e.upcs),this.locationServiceHelper.validateAndNormalizeLocation(e.loc),e}validateAndNormalizeSearchParams(t){const e=[],r={...t};return this.validateOrderBy(r.orderBy,e),this.validateOrderDirection(r.orderDirection,e),this.validateFilters(r.filters,e),this.validatePagination(r.page,r.perPage,e),this.locationServiceHelper.validateAndNormalizeLocation(r.loc),e.length>0?{...r,error:e.join(". ")}:r}validateUPCs(t){if(!Array.isArray(t)||0===t.length)throw new Error("UPCs must be a non-empty array of strings");if(!t.every((t=>"string"==typeof t&&t.trim().length>0)))throw new Error("All UPCs must be non-empty strings")}validateOrderBy(t,e){t&&!Object.values(exports.ENUM_ORDER_BY).includes(t)&&e.push(`Invalid orderBy value: ${t}`)}validateOrderDirection(t,e){t&&!Object.values(exports.ENUM_NAVIGATION_ORDER_DIRECTION_TYPE).includes(t)&&e.push(`Invalid orderDirection value: ${t}`)}validateFilters(t,e){t&&(t.length>10&&e.push("Maximum of 10 filters allowed"),t.forEach((t=>{switch(Object.values(exports.ENUM_FILTER_KEYS).includes(t.key)||e.push(`Invalid filter key: ${t.key}`),t.key){case exports.ENUM_FILTER_KEYS.AVAILABILITY:this.validateAvailabilityFilter(t.values,e);break;case exports.ENUM_FILTER_KEYS.BRANDS:this.validateArrayFilter(t.values,30,"brands",e);break;case exports.ENUM_FILTER_KEYS.CATEGORIES:this.validateCategoriesFilter(t.values,e);break;case exports.ENUM_FILTER_KEYS.COLORS:this.validateArrayFilter(t.values,75,"colors",e)}})))}validateAvailabilityFilter(t,e){Object.values(exports.ENUM_AVAILABILITY_VALUE).includes(t)||e.push(`Invalid availability value: ${t}`)}validateArrayFilter(t,e,r,i){Array.isArray(t)?t.length>e&&i.push(`${r} filter can have a maximum of ${e} values`):i.push(`${r} filter must be an array`)}validateCategoriesFilter(t,e){Array.isArray(t)?t.every((t=>this.taxonomyValues.has(t)))||e.push("Invalid category value(s) in categories filter"):e.push("Categories filter must be an array")}validatePagination(t,e,r){void 0!==t&&("number"!=typeof t||t<0)&&r.push("Page must be a non-negative number"),void 0!==e&&("number"!=typeof e||e<=0)&&r.push("PerPage must be a positive number")}}class f{constructor(t){this.locationHelperService=t}validateAndNormalizePrepareParams(t){const e={...t};if(!e.cartId||"string"!=typeof e.cartId)throw new Error("Invalid cartId");return this.validateRecipient(e.recipient),e.billingAddress&&this.validateAddress(e.billingAddress),e.hasSubstitutionPolicy=Boolean(e.hasSubstitutionPolicy),e.isGift=Boolean(e.isGift),e.billingSameAsShipping=Boolean(e.billingSameAsShipping),e.isGift&&this.validateGiftOptions(e.giftOptions),this.validateMarketingPreferences(e.marketingPreferences),e.deliveryTips&&this.validateDeliveryTips(e.deliveryTips),e.refresh=Boolean(e.refresh),e}validateAndNormalizeCompleteParams(t){const e={...t};if(!e.token||"string"!=typeof e.token)throw new Error("Invalid token");if(!e.payment||"string"!=typeof e.payment)throw new Error("Invalid payment token");return void 0!==e.refresh&&(e.refresh=Boolean(e.refresh)),e}validateRecipient(t){if(!t||"object"!=typeof t)throw new Error("Invalid recipient");["firstName","lastName","email","phone","birthDate"].forEach((e=>{if(!t[e]||"string"!=typeof t[e])throw new Error(`Invalid recipient ${e}`)})),t.hasAgeVerify=Boolean(t.hasAgeVerify)}validateAddress(t){if(!t||"object"!=typeof t)throw new Error("Invalid address");["firstName","lastName","email","phone","one","city","state","zip"].forEach((e=>{if(!t[e]||"string"!=typeof t[e])throw new Error(`Invalid address ${e}`)})),this.locationHelperService.validateAndNormalizeLocation({address:t})}validateGiftOptions(t){if(!t||"object"!=typeof t)throw new Error("Invalid giftOptions");if(t.message&&"string"!=typeof t.message)throw new Error("Invalid gift message");if(t.recipient){const{name:e,phone:r,email:i}=t.recipient;if(e&&"string"!=typeof e)throw new Error("Invalid gift recipient name");if(r&&"string"!=typeof r)throw new Error("Invalid gift recipient phone");if(i&&"string"!=typeof i)throw new Error("Invalid gift recipient email")}}validateMarketingPreferences(t){if(!t||"object"!=typeof t)throw new Error("Invalid marketingPreferences");t.canEmail=Boolean(t.canEmail),t.canSms=Boolean(t.canSms)}validateDeliveryTips(t){if(!Array.isArray(t))throw new Error("Invalid deliveryTips");t.forEach((t=>{if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId)throw new Error("Invalid fulfillmentId in deliveryTip");if("number"!=typeof t.tip||t.tip<0)throw new Error("Invalid tip amount in deliveryTip")}))}}class O{validateAndNormalizeLocation(t){if(!t||"object"!=typeof t)throw new Error("Location must be a valid object");if(t.coords)this.validateCoordinates(t.coords);else{if(!t.address)throw new Error("Location must contain either coords or address");this.validateAndNormalizeAddress(t.address)}}validateCoordinates(t){if("number"!=typeof t.lat||"number"!=typeof t.long)throw new Error("Coordinates must be valid numbers");if(t.lat<-90||t.lat>90||t.long<-180||t.long>180)throw new Error("Coordinates are out of valid range")}validateAndNormalizeAddress(t){if(!t.state||"string"!=typeof t.state)throw new Error("State is required and must be a string");if(t.state=this.normalizeState(t.state),!t.city||"string"!=typeof t.city)throw new Error("City is required and must be a string");if(!t.zip||"string"!=typeof t.zip)throw new Error("ZIP code is required and must be a string")}normalizeState(t){const e=t.toUpperCase();if(exports.STATES_CODE[e])return exports.STATES_CODE[e];const r=t.toUpperCase();if(exports.STATES_NAME[r])return exports.STATES_NAME[r];throw new Error(`Invalid state: ${t}`)}}class N{constructor(){this.stripe=null,this.elements=null,this.paymentElement=null,this.events=["ready","change","loaderror","loaderstart"],this.eventsErrorMsg="The only Payment Element events allowed (change, ready, loaderstart, loadererror)",this.clientSecret=null}async mount(t){if(!document.getElementById(t.elementId))throw new Error(`Element with id "${t.elementId}" not found`);try{this.stripe=await m.loadStripe(t.key)}catch(t){throw new Error("Failed to initialize Stripe")}if(!this.stripe)throw new Error("Failed to initialize Stripe");this.clientSecret=t.clientSecret;try{const{setupIntent:t}=await this.stripe.retrieveSetupIntent(this.clientSecret);if("succeeded"===(null==t?void 0:t.status))throw new Error(`The client secret (${this.clientSecret}) has already been used previously. Generate a new one through a use session.`)}catch(t){throw t}const e={clientSecret:t.clientSecret,appearance:this.mapAppearance(t.appearance),paymentMethodCreation:"manual"};this.elements=this.stripe.elements(e);const r=this.mapElementOptions(t.elementOptions);this.paymentElement=this.elements.create("payment",r),this.paymentElement.mount(`#${t.elementId}`)}async generateToken(){var t,e,r,i,s,a,o,n,h,d,c,l;if(!this.stripe||!this.elements||!this.clientSecret)return{type:"client_error",message:"Payment form has not been initialized"};const{error:u}=await this.elements.submit();if(u)return{type:"validation_error",message:u.message,code:u.code};const{error:p,paymentMethod:I}=await this.stripe.createPaymentMethod({elements:this.elements}),E=await this.stripe.confirmSetup({elements:this.elements,redirect:"if_required"});return E.error?{type:"confirm_error",message:null!==(e=null===(t=null==E?void 0:E.error)||void 0===t?void 0:t.message)&&void 0!==e?e:"",code:null!==(i=null===(r=null==E?void 0:E.error)||void 0===r?void 0:r.code)&&void 0!==i?i:""}:p?{type:"validation_error"===p.type?"validation_error":"api_error",message:p.message,code:p.code,param:p.param}:I?{id:I.id,type:I.type,card:(null==I?void 0:I.card)?{brand:null!==(a=null===(s=I.card)||void 0===s?void 0:s.brand)&&void 0!==a?a:"",country:null!==(o=I.card.country)&&void 0!==o?o:"",expMonth:null!==(n=I.card.exp_month)&&void 0!==n?n:0,expYear:null!==(h=I.card.exp_year)&&void 0!==h?h:0,last4:null!==(d=I.card.last4)&&void 0!==d?d:"",funding:null!==(c=I.card.funding)&&void 0!==c?c:""}:void 0,created:null!==(l=null==I?void 0:I.created)&&void 0!==l?l:0}:{type:"client_error",message:"Failed to generate payment token"}}subscribe(t,e){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(t))throw new Error(this.eventsErrorMsg);this.paymentElement.on(t,e)}unsubscribe(t,e){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");if(!this.events.includes(t))throw new Error(this.eventsErrorMsg);this.paymentElement.off(t,e)}mapAppearance(t){if(t)return{theme:"night"===t.theme?"night":"stripe"}}mapElementOptions(t){return{layout:null==t?void 0:t.layout,wallets:{applePay:"auto",googlePay:"auto"}}}unmount(){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");this.paymentElement.unmount()}collapse(){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");this.paymentElement.collapse()}destroy(){if(!this.paymentElement)throw new Error("Payment Element has not been initialized");this.paymentElement.destroy()}}class T{constructor(t){this.client=t}async autocomplete(t,e){try{return await this.client.post("/address/autocomplete",{...t,key:e})}catch(t){throw t}}async details(t,e){try{return await this.client.post("/address/details",{...t,key:e})}catch(t){throw t}}}class C{constructor(t,e){this.client=t,this.cartHelperService=e,this.servicePath="/cart/update"}async get(t,e){try{let r=this.cartHelperService.validateId(t);if(r=""!==r&&r,r){const t={id:r};return"boolean"==typeof e&&(t.refresh=e),await this.client.post(this.servicePath,t)}return await this.client.post(this.servicePath)}catch(t){throw t}}async update(t){try{const e=this.cartHelperService.validateAndNormalizeParams(t);return await this.client.post(this.servicePath,e)}catch(t){throw t}}}class g{constructor(t,e){this.client=t,this.catalogHelperService=e,this.servicePath="/catalog/"}async availability(t){try{const e=this.catalogHelperService.validateAndNormalizeParams(t);return await this.client.post(`${this.servicePath}availability`,e)}catch(t){throw t}}async search(t){try{const e=this.catalogHelperService.validateAndNormalizeSearchParams(t);if(null==e?void 0:e.error)throw new Error(null==e?void 0:e.error);return await this.client.post(`${this.servicePath}search`,e)}catch(t){throw t}}}class P{constructor(t,e){this.client=t,this.checkoutHelperService=e,this.servicePath="/checkout"}async prepare(t){try{const e=this.checkoutHelperService.validateAndNormalizePrepareParams(t);return await this.client.post(`${this.servicePath}/prepare`,e)}catch(t){throw t}}async complete(t){try{const e=this.checkoutHelperService.validateAndNormalizeCompleteParams(t);return await this.client.post(`${this.servicePath}/complete`,e)}catch(t){throw t}}}class x{constructor(t){this.paymentProvider=t,this.collapse=()=>this.paymentProvider.collapse(),this.unmount=()=>this.paymentProvider.unmount(),this.destroy=()=>this.paymentProvider.destroy()}async mount(t){try{await this.paymentProvider.mount(t)}catch(t){throw t}}async generateToken(){return this.paymentProvider.generateToken()}subscribe(t,e){this.paymentProvider.subscribe(t,e)}unsubscribe(t,e){this.paymentProvider.unsubscribe(t,e)}}class D{constructor(t){this.client=t,this.servicePath="/users"}async createOrUpdateSession(t){try{if(!(null==t?void 0:t.id)&&!(null==t?void 0:t.email))throw new Error("Either id or email must be provided");return await this.client.post(`${this.servicePath}/session`,t)}catch(t){throw t}}async purge(t){try{if(!t)throw new Error("User identifier (ID or email) must be provided");return await this.client.delete(`${this.servicePath}/purge/${t}`)}catch(t){throw t}}async addAddress(t){try{if(!(t.customerId&&t.one&&t.city&&t.state&&t.zip&&t.type))throw new Error("Missing required parameters to add address");return await this.client.post(`${this.servicePath}/addresses/add`,t)}catch(t){throw t}}async updateAddress(t){try{if(!(t.customerId&&t.one&&t.city&&t.state&&t.zip&&t.type))throw new Error("Missing required parameters for address update");return await this.client.post(`${this.servicePath}/addresses/update`,t)}catch(t){throw t}}async purgeAddress(t){try{if(!t)throw new Error("Address ID must be provided");return await this.client.delete(`${this.servicePath}/addresses/purge/${t}`)}catch(t){throw t}}async addPayment(t){try{if(!t.customerId||!t.paymentMethodId)throw new Error("Missing required parameters to add payment");return void 0===(null==t?void 0:t.isDefault)&&(null==t||delete t.isDefault),await this.client.post(`${this.servicePath}/payments/add`,t)}catch(t){throw t}}async updatePayment(t){try{if(!t.customerId||!t.paymentMethodId||void 0===(null==t?void 0:t.isDefault)||"boolean"!=typeof(null==t?void 0:t.isDefault))throw new Error("Missing required parameters to add payment");return await this.client.post(`${this.servicePath}/payments/update`,t)}catch(t){throw t}}async purgePayment(t,e){try{if(!t||!e)throw new Error("Missing required parameters for payment purge");return await this.client.delete(`${this.servicePath}/payments/purge/${t}/${e}`)}catch(t){throw t}}}class b{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return b.instance||(b.instance=new b),b.instance}setLiquidCommerceClientConstructor(t){this.liquidCommerceClientConstructor=t}async getLiquidCommerceClient(t,e){const r=`LiquidCommerceClient_${t}_${JSON.stringify(e)}`;if(!this.services.has(r)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const i=new this.liquidCommerceClientConstructor(t,e);await i.init(),this.services.set(r,i)}return this.services.get(r)}getOrCreateService(t,e,...r){if(!this.services.has(t)){const i="getInstance"in e?e.getInstance(...r):new e(...r);this.services.set(t,i)}return this.services.get(t)}getAuthenticatedClient(t){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(t)}`,S,t)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",O)}getAddressService(t){return this.getOrCreateService(`AddressService_${t.getUniqueKey()}`,T,t)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",R,this.getLocationHelperService())}getCatalogService(t){return this.getOrCreateService(`CatalogService_${t.getUniqueKey()}`,g,t,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",A,this.getLocationHelperService())}getCartService(t){return this.getOrCreateService(`CartService_${t.getUniqueKey()}`,C,t,this.getCartHelperService())}getUserService(t){return this.getOrCreateService(`UserService_${t.getUniqueKey()}`,D,t)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",N)}getPaymentService(){return this.getOrCreateService("PaymentService",x,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",f,this.getLocationHelperService())}getCheckoutService(t){return this.getOrCreateService(`CheckoutService_${t.getUniqueKey()}`,P,t,this.getCheckoutHelperService())}}b.instance=null;class L{constructor(t,e){this.address={autocomplete:async t=>(await this.ensureAuthenticated(),this.addressService.autocomplete(t,this.config.googlePlacesApiKey)),details:async t=>(await this.ensureAuthenticated(),this.addressService.details(t,this.config.googlePlacesApiKey))},this.catalog={availability:async t=>(await this.ensureAuthenticated(),this.catalogService.availability(t)),search:async t=>(await this.ensureAuthenticated(),this.catalogService.search(t))},this.cart={get:async(t,e)=>(await this.ensureAuthenticated(),this.cartService.get(t,e)),update:async t=>(await this.ensureAuthenticated(),this.cartService.update(t))},this.user={session:async t=>(await this.ensureAuthenticated(),this.userService.createOrUpdateSession(t)),purge:async t=>(await this.ensureAuthenticated(),this.userService.purge(t)),addAddress:async t=>(await this.ensureAuthenticated(),this.userService.addAddress(t)),updateAddress:async t=>(await this.ensureAuthenticated(),this.userService.updateAddress(t)),purgeAddress:async t=>(await this.ensureAuthenticated(),this.userService.purgeAddress(t)),addPayment:async t=>(await this.ensureAuthenticated(),this.userService.addPayment(t)),updatePayment:async t=>(await this.ensureAuthenticated(),this.userService.updatePayment(t)),purgePayment:async(t,e)=>(await this.ensureAuthenticated(),this.userService.purgePayment(t,e))},this.payment={mount:async t=>(await this.ensureAuthenticated(),this.paymentService.mount(t)),generateToken:async()=>(await this.ensureAuthenticated(),this.paymentService.generateToken()),subscribe:(t,e)=>{this.paymentService.subscribe(t,e)},unsubscribe:(t,e)=>{this.paymentService.unsubscribe(t,e)},collapse:()=>{this.paymentService.collapse()},unmount:()=>{this.paymentService.unmount()},destroy:()=>{this.paymentService.destroy()}},this.checkout={prepare:async t=>(await this.ensureAuthenticated(),this.checkoutService.prepare(t)),complete:async t=>(await this.ensureAuthenticated(),this.checkoutService.complete(t))},this.config=e,this.singletonManager=b.getInstance();const r=this.determineBaseURL(e);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:t,baseURL:r}),this.addressService=this.singletonManager.getAddressService(this.authenticatedClient),this.catalogService=this.singletonManager.getCatalogService(this.authenticatedClient),this.cartService=this.singletonManager.getCartService(this.authenticatedClient),this.userService=this.singletonManager.getUserService(this.authenticatedClient),this.paymentService=this.singletonManager.getPaymentService(),this.checkoutService=this.singletonManager.getCheckoutService(this.authenticatedClient)}determineBaseURL(t){const e=t.env||exports.LIQUID_COMMERCE_ENV.STAGE;return v[e]}async init(){try{await this.authenticatedClient.authenticate()}catch(t){throw new Error("Authentication failed during initialization")}}async ensureAuthenticated(){this.authenticatedClient.isTokenExpired()&&await this.authenticatedClient.authenticate()}}exports.LiquidCommerce=async function(t,e){const r=b.getInstance();return r.setLiquidCommerceClientConstructor(L),await r.getLiquidCommerceClient(t,e)};