@liquidcommerce/cloud-sdk 1.0.1
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 +256 -0
- package/dist/index.cjs +1 -0
- package/dist/index.esm.js +1 -0
- package/dist/liquidcommerce-cloud-sdk.ssr.js +1 -0
- package/dist/types/constants/core.constant.d.ts +4 -0
- package/dist/types/core/authenticated.service.d.ts +125 -0
- package/dist/types/core/cart-helper.service.d.ts +48 -0
- package/dist/types/core/catalog-helper.service.d.ts +113 -0
- package/dist/types/core/checkout-helper.service.d.ts +76 -0
- package/dist/types/core/index.d.ts +7 -0
- package/dist/types/core/location-helper.service.d.ts +47 -0
- package/dist/types/core/payment-provider.service.d.ts +91 -0
- package/dist/types/core/singleton.service.d.ts +138 -0
- package/dist/types/enums.d.ts +265 -0
- package/dist/types/index.d.ts +1 -0
- package/dist/types/index.umd.d.ts +2 -0
- package/dist/types/interfaces/address.interface.d.ts +21 -0
- package/dist/types/interfaces/cart.interface.d.ts +188 -0
- package/dist/types/interfaces/catalog.interface.d.ts +69 -0
- package/dist/types/interfaces/catalog.service.interface.d.ts +65 -0
- package/dist/types/interfaces/checkout.interface.d.ts +118 -0
- package/dist/types/interfaces/liquid-commerce-client.interface.d.ts +597 -0
- package/dist/types/interfaces/payment.interface.d.ts +88 -0
- package/dist/types/interfaces/retailer.interface.d.ts +63 -0
- package/dist/types/interfaces/user.interface.d.ts +53 -0
- package/dist/types/liquid-commerce-client.d.ts +189 -0
- package/dist/types/services/address.service.d.ts +44 -0
- package/dist/types/services/cart.service.d.ts +31 -0
- package/dist/types/services/catalog.service.d.ts +38 -0
- package/dist/types/services/checkout.service.d.ts +28 -0
- package/dist/types/services/payment.service.d.ts +39 -0
- package/dist/types/services/user.service.d.ts +43 -0
- package/dist/types/types.d.ts +36 -0
- package/package.json +108 -0
- package/umd/liquidcommerce-cloud-sdk.min.js +1 -0
package/README.md
ADDED
|
@@ -0,0 +1,256 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
# LiquidCommerce Cloud SDK
|
|
4
|
+
|
|
5
|
+
The LiquidCommerce Cloud SDK provides an easy way to interact with our APIs through a server-side SDK for Node.js and Web JS script.
|
|
6
|
+
|
|
7
|
+
## Table of Contents
|
|
8
|
+
|
|
9
|
+
- [Installation](#installation)
|
|
10
|
+
- [Authentication](#authentication)
|
|
11
|
+
- [Usage](#usage)
|
|
12
|
+
- [Methods](#methods)
|
|
13
|
+
- [Address](#address)
|
|
14
|
+
- [Catalog](#catalog)
|
|
15
|
+
- [Cart](#cart)
|
|
16
|
+
- [User](#user)
|
|
17
|
+
- [Payment](#payment)
|
|
18
|
+
- [Checkout](#checkout)
|
|
19
|
+
- [Price Type](#price-type)
|
|
20
|
+
- [Documentation](#documentation)
|
|
21
|
+
|
|
22
|
+
## Installation
|
|
23
|
+
|
|
24
|
+
Install the package with:
|
|
25
|
+
|
|
26
|
+
```sh
|
|
27
|
+
npm install @liquidcommerce/cloud-sdk
|
|
28
|
+
# or
|
|
29
|
+
yarn add @liquidcommerce/cloud-sdk
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
## Authentication
|
|
33
|
+
|
|
34
|
+
The LiquidCommerce library uses API keys to authenticate requests. You can request your keys from your Partnerships liaison.
|
|
35
|
+
|
|
36
|
+
Your API keys carry many privileges, so be sure to keep them secure! Do not share your secret API keys in publicly accessible areas such as GitHub, client-side code, and so forth.
|
|
37
|
+
|
|
38
|
+
All API requests in production must be made over HTTPS. Calls made over plain HTTP will fail. API requests without authentication will also fail.
|
|
39
|
+
|
|
40
|
+
## Usage
|
|
41
|
+
|
|
42
|
+
```javascript
|
|
43
|
+
import LiquidCommerce from '@liquidcommerce/cloud-sdk';
|
|
44
|
+
|
|
45
|
+
// Your Account token provided to you through your account representative
|
|
46
|
+
const client = await LiquidCommerce('YOUR_LIQUIDCOMMERCE_API_KEY', {
|
|
47
|
+
googlePlacesApiKey: 'YOUR_GOOGLE_PLACES_API_KEY',
|
|
48
|
+
env: 'stage' // or 'prod'
|
|
49
|
+
});
|
|
50
|
+
|
|
51
|
+
// Initialize the client
|
|
52
|
+
await client.init();
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Methods
|
|
56
|
+
|
|
57
|
+
### Address
|
|
58
|
+
|
|
59
|
+
The `address` method provides address autocompletion and details using Google Places API.
|
|
60
|
+
|
|
61
|
+
```javascript
|
|
62
|
+
// Address autocompletion
|
|
63
|
+
const autocompleteResults = await client.address.autocomplete({
|
|
64
|
+
input: '100 Madison Ave, New York'
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
// Address details
|
|
68
|
+
const addressDetails = await client.address.details({
|
|
69
|
+
id: 'ChIJd8BlQ2BZwokRjMKtTjMezRw'
|
|
70
|
+
});
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
### Catalog
|
|
74
|
+
|
|
75
|
+
The `catalog` method allows you to search and check availability of products in the LiquidCommerce catalog.
|
|
76
|
+
|
|
77
|
+
```javascript
|
|
78
|
+
// Check availability
|
|
79
|
+
const availabilityResponse = await client.catalog.availability({
|
|
80
|
+
upcs: ['123456789012', '210987654321'],
|
|
81
|
+
loc: {
|
|
82
|
+
address: {
|
|
83
|
+
one: '123 Main St',
|
|
84
|
+
city: 'New York',
|
|
85
|
+
state: 'NY',
|
|
86
|
+
zip: '10001'
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
shouldShowOffHours: true
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
// Search catalog
|
|
93
|
+
const searchResults = await client.catalog.search({
|
|
94
|
+
search: 'whiskey',
|
|
95
|
+
pageToken: '',
|
|
96
|
+
page: 1,
|
|
97
|
+
perPage: 20,
|
|
98
|
+
orderBy: 'price',
|
|
99
|
+
orderDirection: 'asc',
|
|
100
|
+
filters: [
|
|
101
|
+
{ key: 'categories', values: ['SPIRITS > WHISKEY'] },
|
|
102
|
+
{ key: 'price', values: { min: 20, max: 100 } }
|
|
103
|
+
],
|
|
104
|
+
loc: {
|
|
105
|
+
address: {
|
|
106
|
+
one: '123 Main St',
|
|
107
|
+
city: 'New York',
|
|
108
|
+
state: 'NY',
|
|
109
|
+
zip: '10001'
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
});
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### Cart
|
|
116
|
+
|
|
117
|
+
The `cart` method allows you to manage shopping carts.
|
|
118
|
+
|
|
119
|
+
```javascript
|
|
120
|
+
// Get an existing cart
|
|
121
|
+
const existingCart = await client.cart.get('existing_cart_id');
|
|
122
|
+
|
|
123
|
+
// Update cart
|
|
124
|
+
const updatedCart = await client.cart.update({
|
|
125
|
+
id: 'existing_cart_id',
|
|
126
|
+
items: [
|
|
127
|
+
{
|
|
128
|
+
id: 'item_id_1',
|
|
129
|
+
partNumber: '123456789012_retailer_id',
|
|
130
|
+
quantity: 2,
|
|
131
|
+
engravingLines: ['Happy Birthday', 'John!'],
|
|
132
|
+
fulfillmentId: 'fulfillment_id_1'
|
|
133
|
+
}
|
|
134
|
+
],
|
|
135
|
+
loc: {
|
|
136
|
+
address: {
|
|
137
|
+
one: '123 Main St',
|
|
138
|
+
city: 'New York',
|
|
139
|
+
state: 'NY',
|
|
140
|
+
zip: '10001'
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
});
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
### User
|
|
147
|
+
|
|
148
|
+
The `user` method provides user management functionality.
|
|
149
|
+
|
|
150
|
+
```javascript
|
|
151
|
+
// Create or update user session
|
|
152
|
+
const userSession = await client.user.session({
|
|
153
|
+
email: "user@example.com",
|
|
154
|
+
firstName: "John"
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
// Update user address
|
|
158
|
+
const updatedAddress = await client.user.updateAddress({
|
|
159
|
+
customerId: 'c1fbd454-a540-4f42-86e9-f87a98bf1812',
|
|
160
|
+
one: '100 Madison St',
|
|
161
|
+
city: 'New York',
|
|
162
|
+
state: 'NY',
|
|
163
|
+
zip: '10004',
|
|
164
|
+
type: 'shipping',
|
|
165
|
+
isDefault: true
|
|
166
|
+
});
|
|
167
|
+
|
|
168
|
+
// Purge user data
|
|
169
|
+
const purgeResponse = await client.user.purge('user@example.com');
|
|
170
|
+
|
|
171
|
+
// Purge user address
|
|
172
|
+
const addressPurgeResponse = await client.user.purgeAddress('26af8958-0deb-44ec-b9fd-ca150b198e45');
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
### Payment
|
|
176
|
+
|
|
177
|
+
The `payment` method handles secure payment processing.
|
|
178
|
+
|
|
179
|
+
```javascript
|
|
180
|
+
// Mount payment form
|
|
181
|
+
await client.payment.mount({
|
|
182
|
+
clientSecret: 'client_secret_from_server',
|
|
183
|
+
elementId: 'payment-element-container',
|
|
184
|
+
appearance: { theme: 'night' },
|
|
185
|
+
elementOptions: { layout: 'tabs' }
|
|
186
|
+
});
|
|
187
|
+
|
|
188
|
+
// Generate payment token
|
|
189
|
+
const token = await client.payment.generateToken();
|
|
190
|
+
|
|
191
|
+
// Subscribe to payment events
|
|
192
|
+
client.payment.subscribe('change', (event) => {
|
|
193
|
+
console.log('Payment element changed:', event);
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
// Unsubscribe from payment events
|
|
197
|
+
client.payment.unsubscribe('change');
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
### Checkout
|
|
201
|
+
|
|
202
|
+
The `checkout` method manages the checkout process.
|
|
203
|
+
|
|
204
|
+
```javascript
|
|
205
|
+
// Prepare checkout
|
|
206
|
+
const preparedCheckout = await client.checkout.prepare({
|
|
207
|
+
cartId: "65df5c***********512f",
|
|
208
|
+
recipient: {
|
|
209
|
+
firstName: "Jack",
|
|
210
|
+
lastName: "Smith",
|
|
211
|
+
email: "sample.jack@gmail.com",
|
|
212
|
+
phone: "2129983315",
|
|
213
|
+
birthDate: "11-22-1998",
|
|
214
|
+
hasAgeVerify: false
|
|
215
|
+
},
|
|
216
|
+
billingAddress: {
|
|
217
|
+
firstName: "Jenna",
|
|
218
|
+
lastName: "Smith",
|
|
219
|
+
email: "sample.jenna@gmail.com",
|
|
220
|
+
phone: "2129983315",
|
|
221
|
+
one: "251 Mercer St",
|
|
222
|
+
city: "New York",
|
|
223
|
+
state: "NY",
|
|
224
|
+
zip: "10012"
|
|
225
|
+
},
|
|
226
|
+
hasSubstitutionPolicy: true,
|
|
227
|
+
isGift: false,
|
|
228
|
+
billingSameAsShipping: false,
|
|
229
|
+
marketingPreferences: {
|
|
230
|
+
canEmail: true,
|
|
231
|
+
canSms: true
|
|
232
|
+
},
|
|
233
|
+
deliveryTips: [
|
|
234
|
+
{
|
|
235
|
+
fulfillmentId: "6570c3e********1910c105",
|
|
236
|
+
tip: 2500
|
|
237
|
+
}
|
|
238
|
+
]
|
|
239
|
+
});
|
|
240
|
+
|
|
241
|
+
// Complete checkout
|
|
242
|
+
const completedCheckout = await client.checkout.complete({
|
|
243
|
+
token: "checkout_token_123",
|
|
244
|
+
payment: "payment_id_456"
|
|
245
|
+
});
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
This method allows you to prepare and complete a checkout process. The `prepare` method sets up the checkout with all necessary details, while the `complete` method finalizes the checkout using a token and payment information.
|
|
249
|
+
|
|
250
|
+
## Price Type
|
|
251
|
+
|
|
252
|
+
All prices in our services are represented in the currency's subunit. For example, **$4.99** is output as **499**.
|
|
253
|
+
|
|
254
|
+
## Documentation
|
|
255
|
+
|
|
256
|
+
For more detailed information about each method and its parameters, please refer to our [official documentation](https://docs.liquidcommerce.co/cloud/getting-started).
|
package/dist/index.cjs
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var e,t,r,i,a,s,n,o,c,l,h,d,I,u,A,E,S,p,v,R,m=require("@stripe/stripe-js");exports.LIQUID_COMMERCE_ENV=void 0,(e=exports.LIQUID_COMMERCE_ENV||(exports.LIQUID_COMMERCE_ENV={})).DEV="dev",e.STAGE="stage",function(e){e.ON_DEMAND="onDemand",e.SHIPPING="shipping"}(t||(t={})),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"}(i||(i={})),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"}(a||(a={})),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"}(s||(s={})),function(e){e.BASE="FOOD",e.PANTRY_OTHER="FOOD > PANTRY > OTHER"}(n||(n={})),function(e){e.BASE="MERCHANDISE",e.GLASSWARE="MERCHANDISE > GLASSWARE",e.HUMIDOR="MERCHANDISE > HUMIDOR"}(o||(o={})),function(e){e.BASE="MISCELLANEOUS",e.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",e.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",e.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP"}(c||(c={})),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"}(l||(l={})),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"}(d||(d={})),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"}(u||(u={})),function(e){e.ASC="asc",e.DESC="desc"}(A||(A={})),function(e){e.PRICE="price"}(E||(E={})),function(e){e.UNSPECIFIED="AVAILABILITY_UNSPECIFIED",e.IN_STOCK="IN_STOCK",e.OUT_OF_STOCK="OUT_OF_STOCK",e.PREORDER="PREORDER",e.BACKORDER="BACKORDER"}(S||(S={})),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"}(p||(p={})),function(e){e.OOS="OutOfStock",e.ITEMS_NOT_ADDED="ItemsNotAdded",e.ITEM_NOT_ENGRAVED="ItemEngravingError",e.ADDRESS_CHANGE="AddressChange",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"}(R||(R={}));const C={[exports.LIQUID_COMMERCE_ENV.DEV]:"https://dev.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.STAGE]:"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(((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 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,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})}}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(p.INVALID_ITEMS_TYPE);if(e.length>25)throw new Error(p.INVALID_ITEMS_MAX);return e.map((e=>this.validateAndNormalizeItem(e)))}validateAndNormalizeItem(e){const t={...e};if(!this.validatePartNumber(t.partNumber))throw new Error(p.INVALID_PART_NUMBER);if(!t.fulfillmentId||"string"!=typeof t.fulfillmentId||0===t.fulfillmentId.trim().length)throw new Error(p.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(s),...Object.values(n),...Object.values(o),...Object.values(l),...Object.values(h),...Object.values(d),...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(E).includes(e)&&t.push(`Invalid orderBy value: ${e}`)}validateOrderDirection(e,t){e&&!Object.values(A).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(u).includes(e.key)||t.push(`Invalid filter key: ${e.key}`),e.key){case u.AVAILABILITY:this.validateAvailabilityFilter(e.values,t);break;case u.BRANDS:this.validateArrayFilter(e.values,30,"brands",t);break;case u.CATEGORIES:this.validateCategoriesFilter(e.values,t);break;case u.COLORS:this.validateArrayFilter(e.values,75,"colors",t)}})))}validateAvailabilityFilter(e,t){Object.values(S).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 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: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 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(i[t])return i[t];const r=e.toUpperCase();if(a[r])return a[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)"}async mount(e){if(!document.getElementById(e.elementId))throw new Error(`Element with id "${e.elementId}" not found`);try{this.stripe=await m.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,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!==(r=h.card.country)&&void 0!==r?r:"",expMonth:null!==(i=h.card.exp_month)&&void 0!==i?i: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 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 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 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)}`,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 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)),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 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 C[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=H.getInstance();return r.setLiquidCommerceClientConstructor(U),await r.getLiquidCommerceClient(e,t)};
|
|
@@ -0,0 +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,S,E,p,v,R,m;!function(e){e.DEV="dev",e.STAGE="stage"}(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"}(S||(S={})),function(e){e.PRICE="price"}(E||(E={})),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.ITEM_NOT_ENGRAVED="ItemEngravingError",e.ADDRESS_CHANGE="AddressChange",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.DEV]:"https://dev.cloud.liquidcommerce.co/api",[t.STAGE]:"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(E).includes(e)&&t.push(`Invalid orderBy value: ${e}`)}validateOrderDirection(e,t){e&&!Object.values(S).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{t as LIQUID_COMMERCE_ENV,U as LiquidCommerce};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";var LIQUID_COMMERCE_ENV,t,e,i,r,s,a,n,o,h,c,l,d,u,I,E,S,w,y,p,A=require("@stripe/stripe-js");exports.LIQUID_COMMERCE_ENV=void 0,(LIQUID_COMMERCE_ENV=exports.LIQUID_COMMERCE_ENV||(exports.LIQUID_COMMERCE_ENV={})).DEV="dev",LIQUID_COMMERCE_ENV.STAGE="stage",function(t){t.ON_DEMAND="onDemand",t.SHIPPING="shipping"}(t||(t={})),function(t){t.MONDAY="monday",t.TUESDAY="tuesday",t.WEDNESDAY="wednesday",t.THURSDAY="thursday",t.FRIDAY="friday",t.SATURDAY="saturday",t.SUNDAY="sunday"}(e||(e={})),function(t){t.AL="AL",t.AK="AK",t.AR="AR",t.CA="CA",t.CO="CO",t.CT="CT",t.DE="DE",t.DC="DC",t.FL="FL",t.GA="GA",t.HI="HI",t.ID="ID",t.IL="IL",t.IN="IN",t.IA="IA",t.KS="KS",t.KY="KY",t.LA="LA",t.ME="ME",t.MD="MD",t.MA="MA",t.MI="MI",t.MN="MN",t.MS="MS",t.MO="MO",t.MT="MT",t.NE="NE",t.NV="NV",t.NH="NH",t.NJ="NJ",t.NM="NM",t.NY="NY",t.NC="NC",t.ND="ND",t.OH="OH",t.OK="OK",t.OR="OR",t.PA="PA",t.RI="RI",t.SC="SC",t.SD="SD",t.TN="TN",t.TX="TX",t.UT="UT",t.VT="VT",t.VA="VA",t.WA="WA",t.WV="WV",t.WI="WI",t.WY="WY"}(i||(i={})),function(t){t.ALABAMA="AL",t.ALASKA="AK",t.ARKANSAS="AR",t.CALIFORNIA="CA",t.COLORADO="CO",t.CONNECTICUT="CT",t.DELAWARE="DE",t.DISTRICT_OF_COLUMBIA="DC",t.FLORIDA="FL",t.GEORGIA="GA",t.HAWAII="HI",t.IDAHO="ID",t.ILLINOIS="IL",t.INDIANA="IN",t.IOWA="IA",t.KANSAS="KS",t.KENTUCKY="KY",t.LOUISIANA="LA",t.MAINE="ME",t.MARYLAND="MD",t.MASSACHUSETTS="MA",t.MICHIGAN="MI",t.MINNESOTA="MN",t.MISSISSIPPI="MS",t.MISSOURI="MO",t.MONTANA="MT",t.NEBRASKA="NE",t.NEVADA="NV",t.NEW_HAMPSHIRE="NH",t.NEW_JERSEY="NJ",t.NEW_MEXICO="NM",t.NEW_YORK="NY",t.NORTH_CAROLINA="NC",t.NORTH_DAKOTA="ND",t.OHIO="OH",t.OKLAHOMA="OK",t.OREGON="OR",t.PENNSYLVANIA="PA",t.RHODE_ISLAND="RI",t.SOUTH_CAROLINA="SC",t.SOUTH_DAKOTA="SD",t.TENNESSEE="TN",t.TEXAS="TX",t.UTAH="UT",t.VERMONT="VT",t.VIRGINIA="VA",t.WASHINGTON="WA",t.WEST_VIRGINIA="WV",t.WISCONSIN="WI",t.WYOMING="WY"}(r||(r={})),function(t){t.ALE="BEER > ALE",t.LAGER="BEER > LAGER",t.MAIN="BEER",t.NON_ALCOHOLIC="BEER > NON-ALCOHOLIC",t.OTHER_BEER="BEER > OTHER BEER"}(s||(s={})),function(t){t.BASE="FOOD",t.PANTRY_OTHER="FOOD > PANTRY > OTHER"}(a||(a={})),function(t){t.BASE="MERCHANDISE",t.GLASSWARE="MERCHANDISE > GLASSWARE",t.HUMIDOR="MERCHANDISE > HUMIDOR"}(n||(n={})),function(t){t.BASE="MISCELLANEOUS",t.GIFT_CARD="MISCELLANEOUS > GIFT CARDS",t.PROMOTIONAL="MISCELLANEOUS > PROMOTIONAL",t.MEMBERSHIP="MISCELLANEOUS > MEMBERSHIP"}(o||(o={})),function(t){t.BASE="NON ALCOHOLIC",t.BITTERS="NON ALCOHOLIC > BITTERS",t.COCKTAIL_MIX="NON ALCOHOLIC > COCKTAIL MIX",t.COFFEE="NON ALCOHOLIC > COFFEE",t.ENERGY_DRINKS="NON ALCOHOLIC > ENERGY DRINKS",t.JUICE="NON ALCOHOLIC > JUICE",t.SODA="NON ALCOHOLIC > SODA",t.SPECIALTY_ITEM="NON ALCOHOLIC > SPECIALTY ITEM",t.SPIRITS="NON ALCOHOLIC > SPIRITS",t.TEA="NON ALCOHOLIC > TEA",t.WATER="NON ALCOHOLIC > WATER",t.WINE="NON ALCOHOLIC > WINE"}(h||(h={})),function(t){t.BASE="READY TO DRINK",t.HARD_CIDER="READY TO DRINK > HARD CIDER",t.HARD_CIDER_PERRY_PEAR_CIDER="READY TO DRINK > HARD CIDER > PERRY (PEAR CIDER)",t.HARD_TEA="READY TO DRINK > HARD TEA",t.MALT_BASED="READY TO DRINK > MALT BASED",t.SPIRITS_BASED_RTDS="READY TO DRINK > SPIRITS-BASED RTDS",t.SPIRITS_BASED_RTDS_RUM_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > RUM COCKTAILS",t.SPIRITS_BASED_RTDS_TEQUILA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > TEQUILA COCKTAILS",t.SPIRITS_BASED_RTDS_VODKA_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > VODKA COCKTAILS",t.SPIRITS_BASED_RTDS_WHISKEY_COCKTAILS="READY TO DRINK > SPIRITS-BASED RTDS > WHISKEY COCKTAILS",t.WINE_COCKTAILS="READY TO DRINK > WINE COCKTAILS"}(c||(c={})),function(t){t.BASE="SPIRITS",t.BAIJIU="SPIRITS > BAIJIU",t.BITTERS="SPIRITS > BITTERS",t.BRANDY="SPIRITS > BRANDY",t.CACHACA="SPIRITS > CACHACA",t.GIN="SPIRITS > GIN",t.LAGER="SPIRITS > LAGER",t.LIQUEUR="SPIRITS > LIQUEUR",t.MEZCAL="SPIRITS > MEZCAL",t.OTHER_SPIRITS="SPIRITS > OTHER SPIRITS",t.RUM="SPIRITS > RUM",t.RUM_AGED_RUM="SPIRITS > RUM > AGED RUM",t.RUM_DARK_RUM="SPIRITS > RUM > DARK RUM",t.RUM_FLAVORED_RUM="SPIRITS > RUM > FLAVORED RUM",t.RUM_GOLD_RUM="SPIRITS > RUM > GOLD RUM",t.RUM_OTHER="SPIRITS > RUM > OTHER",t.RUM_SPICED="SPIRITS > RUM > SPICED",t.RUM_WHITE_RUM="SPIRITS > RUM > WHITE RUM",t.SOJU="SPIRITS > SOJU",t.TEQUILA="SPIRITS > TEQUILA",t.VODKA="SPIRITS > VODKA",t.VODKA_FLAVORED_VODKA="SPIRITS > VODKA > FLAVORED VODKA",t.WHISKEY="SPIRITS > WHISKEY",t.WHISKEY_AMERICAN_WHISKEY="SPIRITS > WHISKEY > AMERICAN WHISKEY",t.WHISKEY_BOURBON="SPIRITS > WHISKEY > BOURBON",t.WHISKEY_CANADIAN_WHISKEY="SPIRITS > WHISKEY > CANADIAN WHISKEY",t.WHISKEY_IRISH_WHISKEY="SPIRITS > WHISKEY > IRISH WHISKEY",t.WHISKEY_SCOTCH="SPIRITS > WHISKEY > SCOTCH"}(l||(l={})),function(t){t.BASE="WINE",t.CHAMPAGNE_SPARKLING="WINE > CHAMPAGNE & SPARKLING",t.CHAMPAGNE_SPARKLING_SPARKLING_WINE="WINE > CHAMPAGNE & SPARKLING > SPARKLING WINE",t.COOKING="WINE > COOKING",t.DESSERT_FORTIFIED_WINE="WINE > DESSERT & FORTIFIED WINE",t.DESSERT_FORTIFIED_WINE_SHERRY="WINE > DESSERT & FORTIFIED WINE > SHERRY",t.RED_WINE="WINE > RED WINE",t.ROSE_WINE="WINE > ROSE WINE",t.SAKE="WINE > SAKE",t.WHITE_WINE="WINE > WHITE WINE"}(d||(d={})),function(t){t.BRANDS="brands",t.FLAVOR="flavor",t.REGION="region",t.VARIETY="variety",t.PRICE="price",t.AVAILABILITY="availability",t.CATEGORIES="categories",t.SIZES="sizes",t.COLORS="colors",t.APPELLATION="appellation",t.COUNTRY="country",t.VINTAGE="vintage",t.MATERIALS="materials"}(u||(u={})),function(t){t.ASC="asc",t.DESC="desc"}(I||(I={})),function(t){t.PRICE="price"}(E||(E={})),function(t){t.UNSPECIFIED="AVAILABILITY_UNSPECIFIED",t.IN_STOCK="IN_STOCK",t.OUT_OF_STOCK="OUT_OF_STOCK",t.PREORDER="PREORDER",t.BACKORDER="BACKORDER"}(S||(S={})),function(t){t.INVALID_ITEMS_TYPE="Items must be a non-empty array",t.INVALID_ITEMS_MAX="You can only send up to 25 items at a time!",t.INVALID_PART_NUMBER="The partnerNumber provided is invalid",t.INVALID_FULFILLMENT_ID="The fulfillmentId provided is invalid"}(w||(w={})),function(t){t.OOS="OutOfStock",t.ITEMS_NOT_ADDED="ItemsNotAdded",t.ITEM_NOT_ENGRAVED="ItemEngravingError",t.ADDRESS_CHANGE="AddressChange",t.RETAILER_MIN="RetailerMinNotMet",t.NO_ITEMS_IN_CART="NoItemsInCart",t.INVALID_ID="InvalidId",t.NO_ID="NoId",t.CART_CHECKOUT_PROCESSED="CartCheckoutProcessed",t.NEW_CART="NewCart",t.DEFAULT="CartError",t.ITEM_QTY_CHANGE="ItemQuantityChange"}(y||(y={})),function(t){t.SHIPPING="shipping",t.BILLING="billing"}(p||(p={}));const m={[exports.LIQUID_COMMERCE_ENV.DEV]:"https://dev.cloud.liquidcommerce.co/api",[exports.LIQUID_COMMERCE_ENV.STAGE]:"https://staging.cloud.liquidcommerce.co/api"};class R{constructor(t){this.accessToken=null,this.tokenExpiration=null,this.isAuthenticating=!1,this.xhrFetch=(t,e)=>new Promise(((i,r)=>{const s=new XMLHttpRequest;s.open(e.method||"GET",t),Object.entries(e.headers).forEach((([t,e])=>{s.setRequestHeader(t,e)})),s.onload=()=>{i({ok:s.status>=200&&s.status<300,status:s.status,statusText:s.statusText,headers:s.getAllResponseHeaders().split("\r\n").reduce(((t,e)=>{const[i,r]=e.split(": ");return i&&(t[i]=r),t}),{}),json:()=>Promise.resolve(JSON.parse(s.responseText)),text:()=>Promise.resolve(s.responseText)})},s.onerror=()=>{r(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 R.instance||(R.instance=new R(t)),R.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,i)=>{var r;const s=await t(e,i);let a;return"function"==typeof(null===(r=s.headers)||void 0===r?void 0:r.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 i=await this.requestWithoutAuth("/authentication",{method:"GET"});this.accessToken=null===(t=null==i?void 0:i.data)||void 0===t?void 0:t.token,this.tokenExpiration=Date.now()+1e3*(null===(e=null==i?void 0:i.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 i=new URL(`api${t}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,...e.headers},s={method:e.method,headers:r,body:e.body?JSON.stringify(e.body):void 0},a=await this.httpClient(i.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 i=new URL(`api${t}`,this.baseURL),r={"Content-Type":"application/json","X-LIQUID-API-KEY":this.apiKey,Authorization:`Bearer ${this.accessToken}`,...e.headers},s={method:e.method,headers:r,body:e.body?JSON.stringify(e.body):void 0},a=await this.httpClient(i.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,i){return this.request(t,{method:"POST",body:e,headers:i})}async put(t,e,i){return this.request(t,{method:"PUT",body:e,headers:i})}async delete(t,e){return this.request(t,{method:"DELETE",headers:e})}}R.instance=null;class f{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(w.INVALID_ITEMS_TYPE);if(t.length>25)throw new Error(w.INVALID_ITEMS_MAX);return t.map((t=>this.validateAndNormalizeItem(t)))}validateAndNormalizeItem(t){const e={...t};if(!this.validatePartNumber(e.partNumber))throw new Error(w.INVALID_PART_NUMBER);if(!e.fulfillmentId||"string"!=typeof e.fulfillmentId||0===e.fulfillmentId.trim().length)throw new Error(w.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 v{constructor(t){this.locationServiceHelper=t,this.taxonomyValues=new Set([...Object.values(s),...Object.values(a),...Object.values(n),...Object.values(h),...Object.values(c),...Object.values(l),...Object.values(d)])}validateAndNormalizeParams(t){const e={...t};return this.validateUPCs(e.upcs),this.locationServiceHelper.validateAndNormalizeLocation(e.loc),e}validateAndNormalizeSearchParams(t){const e=[],i={...t};return this.validateOrderBy(i.orderBy,e),this.validateOrderDirection(i.orderDirection,e),this.validateFilters(i.filters,e),this.validatePagination(i.page,i.perPage,e),this.locationServiceHelper.validateAndNormalizeLocation(i.loc),e.length>0?{...i,error:e.join(". ")}:i}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(E).includes(t)&&e.push(`Invalid orderBy value: ${t}`)}validateOrderDirection(t,e){t&&!Object.values(I).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(u).includes(t.key)||e.push(`Invalid filter key: ${t.key}`),t.key){case u.AVAILABILITY:this.validateAvailabilityFilter(t.values,e);break;case u.BRANDS:this.validateArrayFilter(t.values,30,"brands",e);break;case u.CATEGORIES:this.validateCategoriesFilter(t.values,e);break;case u.COLORS:this.validateArrayFilter(t.values,75,"colors",e)}})))}validateAvailabilityFilter(t,e){Object.values(S).includes(t)||e.push(`Invalid availability value: ${t}`)}validateArrayFilter(t,e,i,r){Array.isArray(t)?t.length>e&&r.push(`${i} filter can have a maximum of ${e} values`):r.push(`${i} 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,i){void 0!==t&&("number"!=typeof t||t<0)&&i.push("Page must be a non-negative number"),void 0!==e&&("number"!=typeof e||e<=0)&&i.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:i,email:r}=t.recipient;if(e&&"string"!=typeof e)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(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(i[e])return i[e];const s=t.toUpperCase();if(r[s])return r[s];throw new Error(`Invalid state: ${t}`)}}class T{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 A.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 i=this.mapElementOptions(t.elementOptions);this.paymentElement=this.elements.create("payment",i),this.paymentElement.mount(`#${t.elementId}`)}async generateToken(){var t,e,i,r,s,a,n,o;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:l}=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}:l?{id:l.id,type:l.type,card:(null==l?void 0:l.card)?{brand:null!==(e=null===(t=l.card)||void 0===t?void 0:t.brand)&&void 0!==e?e:"",country:null!==(i=l.card.country)&&void 0!==i?i:"",expMonth:null!==(r=l.card.exp_month)&&void 0!==r?r: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(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 g{constructor(t,e){this.client=t,this.cartHelperService=e,this.servicePath="/cart/update"}async get(t,e){try{let i=this.cartHelperService.validateId(t);if(i=""!==i&&i,i){const t={id:i};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 D{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 L{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 b{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 M{constructor(){this.services=new Map,this.liquidCommerceClientConstructor=null}static getInstance(){return M.instance||(M.instance=new M),M.instance}setLiquidCommerceClientConstructor(t){this.liquidCommerceClientConstructor=t}async getLiquidCommerceClient(t,e){const i=`LiquidCommerceClient_${t}_${JSON.stringify(e)}`;if(!this.services.has(i)){if(!this.liquidCommerceClientConstructor)throw new Error("LiquidCommerceClient constructor not set");const r=new this.liquidCommerceClientConstructor(t,e);await r.init(),this.services.set(i,r)}return this.services.get(i)}getOrCreateService(t,e,...i){if(!this.services.has(t)){const r="getInstance"in e?e.getInstance(...i):new e(...i);this.services.set(t,r)}return this.services.get(t)}getAuthenticatedClient(t){return this.getOrCreateService(`AuthenticatedClient_${JSON.stringify(t)}`,R,t)}getLocationHelperService(){return this.getOrCreateService("LocationHelperService",N)}getAddressService(t){return this.getOrCreateService(`AddressService_${t.getUniqueKey()}`,C,t)}getCatalogHelperService(){return this.getOrCreateService("CatalogHelperService",v,this.getLocationHelperService())}getCatalogService(t){return this.getOrCreateService(`CatalogService_${t.getUniqueKey()}`,D,t,this.getCatalogHelperService())}getCartHelperService(){return this.getOrCreateService("CartHelperService",f,this.getLocationHelperService())}getCartService(t){return this.getOrCreateService(`CartService_${t.getUniqueKey()}`,g,t,this.getCartHelperService())}getUserService(t){return this.getOrCreateService(`UserService_${t.getUniqueKey()}`,b,t)}getPaymentProviderService(){return this.getOrCreateService("PaymentProviderService",T)}getPaymentService(){return this.getOrCreateService("PaymentService",L,this.getPaymentProviderService())}getCheckoutHelperService(){return this.getOrCreateService("CheckoutHelperService",O,this.getLocationHelperService())}getCheckoutService(t){return this.getOrCreateService(`CheckoutService_${t.getUniqueKey()}`,P,t,this.getCheckoutHelperService())}}M.instance=null;class H{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=M.getInstance();const i=this.determineBaseURL(e);this.authenticatedClient=this.singletonManager.getAuthenticatedClient({apiKey:t,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(t){const e=t.env||exports.LIQUID_COMMERCE_ENV.STAGE;return m[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 i=M.getInstance();return i.setLiquidCommerceClientConstructor(H),await i.getLiquidCommerceClient(t,e)};
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
interface IAuthConfig {
|
|
2
|
+
apiKey: string;
|
|
3
|
+
baseURL: string;
|
|
4
|
+
}
|
|
5
|
+
/**
|
|
6
|
+
* Represents an authenticated service for making HTTP requests.
|
|
7
|
+
*/
|
|
8
|
+
export declare class AuthenticatedService {
|
|
9
|
+
private static instance;
|
|
10
|
+
private readonly apiKey;
|
|
11
|
+
private readonly baseURL;
|
|
12
|
+
private accessToken;
|
|
13
|
+
private tokenExpiration;
|
|
14
|
+
private isAuthenticating;
|
|
15
|
+
private readonly httpClient;
|
|
16
|
+
private constructor();
|
|
17
|
+
/**
|
|
18
|
+
* Returns an instance of AuthenticatedClient. This method follows the singleton pattern,
|
|
19
|
+
* meaning that it ensures only one instance of AuthenticatedClient is created.
|
|
20
|
+
*
|
|
21
|
+
* @param {IAuthConfig} config - The configuration object used to initialize the AuthenticatedClient instance.
|
|
22
|
+
* @return {AuthenticatedService} An instance of AuthenticatedClient.
|
|
23
|
+
*/
|
|
24
|
+
static getInstance(config: IAuthConfig): AuthenticatedService;
|
|
25
|
+
/**
|
|
26
|
+
* Returns the appropriate implementation of the `HttpClient` interface for making HTTP requests.
|
|
27
|
+
*
|
|
28
|
+
* If the `fetch` function is available, it will be used to create a new `HttpClient` instance by calling the `fetchAdapter` method.
|
|
29
|
+
* If the `fetch` function is not available but the `global.fetch` function is defined, the `global.fetch` function will be used.
|
|
30
|
+
* If neither the `fetch` function nor the `global.fetch` function is available, but the `window.fetch` function is defined, the `window.fetch` function will be used.
|
|
31
|
+
* If none of the above conditions are met, the `xhrFetch` property will be returned.
|
|
32
|
+
*
|
|
33
|
+
* @return The appropriate implementation of the `HttpClient` interface.
|
|
34
|
+
*/
|
|
35
|
+
private getFetchImplementation;
|
|
36
|
+
/**
|
|
37
|
+
* Returns a HttpClient function that wraps the provided fetch function.
|
|
38
|
+
*
|
|
39
|
+
* @param {FetchFunction} fetchFunc - The fetch function to be wrapped.
|
|
40
|
+
*
|
|
41
|
+
* @return {HttpClient} - The HttpClient function that makes network requests using the provided fetch function.
|
|
42
|
+
*/
|
|
43
|
+
private fetchAdapter;
|
|
44
|
+
/**
|
|
45
|
+
* Retrieves a unique key based on the apiKey and baseURL properties.
|
|
46
|
+
* The unique key is generated by concatenating the apiKey and baseURL with an underscore.
|
|
47
|
+
*
|
|
48
|
+
* @return {string} The unique key generated by concatenating the apiKey and baseURL.
|
|
49
|
+
*/
|
|
50
|
+
getUniqueKey(): string;
|
|
51
|
+
/**
|
|
52
|
+
* Sends an HTTP request using XMLHttpRequest and returns a Promise that resolves to a custom response object.
|
|
53
|
+
*
|
|
54
|
+
* @param {string} url - The URL to send the request to.
|
|
55
|
+
* @param {IHttpClientOptions} options - The options for the HTTP request.
|
|
56
|
+
* @returns {Promise<ICustomResponse>} - A Promise that resolves to a custom response object.
|
|
57
|
+
* @throws {TypeError} - If the network request fails.
|
|
58
|
+
*/
|
|
59
|
+
private xhrFetch;
|
|
60
|
+
/**
|
|
61
|
+
* Authenticates the user with the LiquidCommerce API.
|
|
62
|
+
*
|
|
63
|
+
* This method sends a POST request to the /api/authentication endpoint,
|
|
64
|
+
* and stores the received access token and token expiration time.
|
|
65
|
+
*
|
|
66
|
+
* @returns A Promise that resolves to void.
|
|
67
|
+
* @throws An Error if the authentication fails.
|
|
68
|
+
* @async
|
|
69
|
+
*/
|
|
70
|
+
authenticate(): Promise<void>;
|
|
71
|
+
private requestWithoutAuth;
|
|
72
|
+
/**
|
|
73
|
+
* Checks if the token is expired.
|
|
74
|
+
*
|
|
75
|
+
* @returns {boolean} Returns true if the token is expired, otherwise returns false.
|
|
76
|
+
*/
|
|
77
|
+
isTokenExpired(): boolean;
|
|
78
|
+
/**
|
|
79
|
+
* Sends an HTTP request to the specified path with the provided options and returns a Promise that resolves to the response data.
|
|
80
|
+
*
|
|
81
|
+
* @param path - The path to send the request to.
|
|
82
|
+
* @param options - The options for the request, including method, headers, and body.
|
|
83
|
+
* @returns A Promise that resolves to the response data.
|
|
84
|
+
* @throws {Error} If the response is not successful (status is not ok).
|
|
85
|
+
*/
|
|
86
|
+
private request;
|
|
87
|
+
/**
|
|
88
|
+
* Sends a GET request to the specified path with optional headers.
|
|
89
|
+
*
|
|
90
|
+
* @param {string} path - The path to send the request to.
|
|
91
|
+
* @param {Record<string, string>} [headers] - Optional headers to include in the request.
|
|
92
|
+
* @return {Promise<T>} - A promise that resolves to the response data.
|
|
93
|
+
*/
|
|
94
|
+
get<T = any>(path: string, headers?: Record<string, string>): Promise<T>;
|
|
95
|
+
/**
|
|
96
|
+
* Sends a POST request to the specified path with optional body and headers.
|
|
97
|
+
*
|
|
98
|
+
* @param {string} path - The path to send the POST request to.
|
|
99
|
+
* @param {any} [body] - The optional body of the request.
|
|
100
|
+
* @param {Record<string, string>} [headers] - The optional headers of the request.
|
|
101
|
+
*
|
|
102
|
+
* @return {Promise<T>} - A Promise that resolves to the response of the request.
|
|
103
|
+
*
|
|
104
|
+
* @throws {Error} - If an error occurs while making the request.
|
|
105
|
+
*/
|
|
106
|
+
post<T = any>(path: string, body?: any, headers?: Record<string, string>): Promise<T>;
|
|
107
|
+
/**
|
|
108
|
+
* Sends a PUT request to the specified path with optional request body and headers.
|
|
109
|
+
*
|
|
110
|
+
* @param {string} path - The path where the PUT request will be sent.
|
|
111
|
+
* @param {any} [body] - The optional body of the request.
|
|
112
|
+
* @param {Record<string, string>} [headers] - The optional headers of the request.
|
|
113
|
+
* @return {Promise<T>} A Promise that resolves with the response data.
|
|
114
|
+
*/
|
|
115
|
+
put<T = any>(path: string, body?: any, headers?: Record<string, string>): Promise<T>;
|
|
116
|
+
/**
|
|
117
|
+
* Deletes a resource from the server using the HTTP DELETE method.
|
|
118
|
+
*
|
|
119
|
+
* @param path - The path of the resource to delete.
|
|
120
|
+
* @param headers - Optional headers to include in the request.
|
|
121
|
+
* @returns A promise that resolves to the deleted resource.
|
|
122
|
+
*/
|
|
123
|
+
delete<T = any>(path: string, headers?: Record<string, string>): Promise<T>;
|
|
124
|
+
}
|
|
125
|
+
export {};
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { ICartUpdateParams } from '../interfaces/cart.interface';
|
|
2
|
+
import type { LocationHelperService } from './location-helper.service';
|
|
3
|
+
/**
|
|
4
|
+
* CartHelperService is a class that provides methods
|
|
5
|
+
* for validating and normalizing parameters for updating a cart.
|
|
6
|
+
*/
|
|
7
|
+
export declare class CartHelperService {
|
|
8
|
+
private locationHelperService;
|
|
9
|
+
constructor(locationHelperService: LocationHelperService);
|
|
10
|
+
/**
|
|
11
|
+
* Validates and normalizes the parameters for updating a cart.
|
|
12
|
+
*
|
|
13
|
+
* @param {ICartUpdateParams} params - The parameters for updating a cart.
|
|
14
|
+
* @return {ICartUpdateParams} - The validated and normalized parameters.
|
|
15
|
+
*/
|
|
16
|
+
validateAndNormalizeParams(params: ICartUpdateParams): ICartUpdateParams;
|
|
17
|
+
/**
|
|
18
|
+
* Validates an ID.
|
|
19
|
+
*
|
|
20
|
+
* @param {string} id - The ID to be validated.
|
|
21
|
+
* @return {string} - The validated ID.
|
|
22
|
+
*/
|
|
23
|
+
validateId(id?: string): string;
|
|
24
|
+
/**
|
|
25
|
+
* Validates and normalizes an array of cart update items.
|
|
26
|
+
*
|
|
27
|
+
* @param {ICartUpdateItem[]} items - The array of cart update items to be validated and normalized.
|
|
28
|
+
* @throws {Error} CART_PARAM_ERROR_ENUM.INVALID_ITEMS_TYPE - If the items parameter is not an array or is empty.
|
|
29
|
+
* @throws {Error} CART_PARAM_ERROR_ENUM.INVALID_ITEMS_MAX - If the items parameter has more than 25 items.
|
|
30
|
+
* @return {ICartUpdateItem[]} - The validated and normalized array of cart update items.
|
|
31
|
+
*/
|
|
32
|
+
private validateAndNormalizeItems;
|
|
33
|
+
/**
|
|
34
|
+
* Validates and normalizes an item in the cart.
|
|
35
|
+
*
|
|
36
|
+
* @param item - The item to be validated and normalized.
|
|
37
|
+
* @throws {Error} - If the part number or fulfillment ID is invalid.
|
|
38
|
+
* @returns The validated and normalized item.
|
|
39
|
+
*/
|
|
40
|
+
private validateAndNormalizeItem;
|
|
41
|
+
/**
|
|
42
|
+
* Validates a given part number.
|
|
43
|
+
*
|
|
44
|
+
* @param {string} partNumber - The part number to be validated.
|
|
45
|
+
* @return {boolean} - Returns true if the part number is valid, false otherwise.
|
|
46
|
+
*/
|
|
47
|
+
private validatePartNumber;
|
|
48
|
+
}
|