@betterstore/sdk 0.6.12 → 0.7.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/dist/index.mjs CHANGED
@@ -1,618 +1,332 @@
1
- // src/_utils/axios.ts
2
- import axios from "axios";
3
- var API_BASE_URL = "https://v1.betterstore.io";
4
- var createApiClient = (apiKey, proxy) => {
5
- const client = axios.create({
6
- baseURL: proxy ?? API_BASE_URL,
7
- headers: {
8
- "Content-Type": "application/json",
9
- Authorization: `Bearer ${apiKey}`,
10
- "Access-Control-Allow-Origin": "*",
11
- "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, OPTIONS",
12
- "Access-Control-Allow-Headers": "Content-Type, Authorization"
13
- }
14
- });
15
- client.interceptors.response.use(
16
- (response) => response.data,
17
- (error) => {
18
- const apiError = {
19
- isError: true,
20
- status: 500,
21
- message: "An unexpected error occurred"
22
- };
23
- if (error.response) {
24
- apiError.status = error.response.status;
25
- apiError.message = error.response.data?.error || "Server error occurred";
26
- apiError.code = error.response.data?.code;
27
- apiError.details = error.response.data;
28
- } else if (error.request) {
29
- apiError.status = 503;
30
- apiError.message = "Service unavailable - no response from server";
31
- apiError.code = "SERVICE_UNAVAILABLE";
32
- apiError.details = error;
33
- } else {
34
- apiError.status = 500;
35
- apiError.message = "Request configuration error";
36
- apiError.code = "REQUEST_SETUP_ERROR";
37
- apiError.details = error;
38
- }
39
- console.error("API ERROR: ", apiError);
40
- if (apiError.code === "REQUEST_SETUP_ERROR" || apiError.code === "SERVICE_UNAVAILABLE") {
41
- throw apiError;
42
- }
43
- return apiError;
44
- }
45
- );
46
- return client;
47
- };
48
-
49
- // src/auth/providers/otp.ts
50
- var OTP = class {
51
- apiClient;
52
- constructor(apiClient) {
53
- this.apiClient = apiClient;
54
- }
55
- async signup(params) {
56
- const data = await this.apiClient.post(
57
- "/auth/otp/signup",
58
- params
59
- );
60
- return data;
1
+ // src/base-client.ts
2
+ var BaseClient = class {
3
+ constructor(config) {
4
+ this.config = config;
5
+ }
6
+ async get(path, params) {
7
+ const url = new URL(path, this.config.baseUrl);
8
+ if (params) {
9
+ Object.entries(params).forEach(([key, val]) => {
10
+ if (val !== void 0) url.searchParams.set(key, String(val));
11
+ });
12
+ }
13
+ const res = await fetch(url.toString(), {
14
+ method: "GET",
15
+ headers: this.config.headers
16
+ });
17
+ return this.handleResponse(res);
61
18
  }
62
- async login(params) {
63
- const data = await this.apiClient.post(
64
- "/auth/otp/login",
65
- params
66
- );
67
- return data;
19
+ async post(path, body) {
20
+ const res = await fetch(`${this.config.baseUrl}${path}`, {
21
+ method: "POST",
22
+ headers: this.config.headers,
23
+ body: body ? JSON.stringify(body) : void 0
24
+ });
25
+ return this.handleResponse(res);
68
26
  }
69
- async verify(params) {
70
- const data = await this.apiClient.post(
71
- "/auth/otp/verify",
72
- params
73
- );
74
- return data;
27
+ async delete(path) {
28
+ const res = await fetch(`${this.config.baseUrl}${path}`, {
29
+ method: "DELETE",
30
+ headers: this.config.headers
31
+ });
32
+ return this.handleResponse(res);
75
33
  }
76
- };
77
-
78
- // src/auth/index.ts
79
- var Auth = class {
80
- apiClient;
81
- otp;
82
- constructor(apiKey, proxy) {
83
- this.apiClient = createApiClient(apiKey, proxy);
84
- this.otp = new OTP(this.apiClient);
85
- }
86
- async retrieveSession(id) {
87
- const data = await this.apiClient.get(
88
- `/auth/session/${id}`
89
- );
90
- if ("isError" in data && data.isError || !data || !("token" in data)) {
91
- console.error(`Customer session with id ${id} not found`);
92
- return null;
34
+ async handleResponse(res) {
35
+ if (!res.ok) {
36
+ const error = await res.json().catch(() => ({ message: res.statusText }));
37
+ throw new Error(error.message || `HTTP ${res.status}`);
93
38
  }
94
- return data;
39
+ return res.json();
95
40
  }
96
41
  };
97
- var auth_default = Auth;
98
42
 
99
- // src/checkout/index.ts
100
- var Checkout = class {
101
- apiClient;
102
- constructor(apiKey, proxy) {
103
- this.apiClient = createApiClient(apiKey, proxy);
104
- }
105
- /**
106
- * Create a new checkout session
107
- */
108
- async create(params) {
109
- const data = await this.apiClient.post(
110
- "/checkout",
111
- params
43
+ // src/namespaces/client/client-checkout.ts
44
+ var ClientCheckoutNamespace = class {
45
+ constructor(client) {
46
+ this.client = client;
47
+ }
48
+ async get(id) {
49
+ return this.client.get(
50
+ `/api/client/checkout/get/${id}`
112
51
  );
113
- if ("isError" in data && data.isError || !data || !("id" in data)) {
114
- throw new Error("Failed to create checkout session");
115
- }
116
- return data;
117
52
  }
118
- /**
119
- * Retrieve a checkout session by ID
120
- */
121
- async retrieve(checkoutId) {
122
- const data = await this.apiClient.get(
123
- `/checkout/${checkoutId}`
53
+ async update(id, data) {
54
+ return this.client.post(
55
+ `/api/client/checkout/update/${id}`,
56
+ data
124
57
  );
125
- if ("isError" in data && data.isError || !data || !("id" in data)) {
126
- console.error(`Checkout session with id ${checkoutId} not found`);
127
- return null;
128
- }
129
- return data;
130
58
  }
131
- /**
132
- * Update a checkout session
133
- */
134
- async update(checkoutId, params) {
135
- const data = await this.apiClient.put(
136
- `/checkout/${checkoutId}`,
137
- params
59
+ async getShippingRates(id) {
60
+ return this.client.get(
61
+ `/api/client/checkout/${id}/get-shipping-rates`
138
62
  );
139
- if ("isError" in data && data.isError || !data || !("id" in data)) {
140
- console.error(`Checkout session with id ${checkoutId} not found`);
141
- return null;
142
- }
143
- return data;
144
63
  }
145
- /**
146
- * Apply a discount code to a checkout session
147
- */
148
- async applyDiscountCode(checkoutId, discountCode) {
149
- const data = await this.apiClient.post(
150
- `/checkout/${checkoutId}/discounts/apply`,
151
- { code: discountCode }
64
+ async generatePaymentSecret(id) {
65
+ return this.client.post(
66
+ `/api/client/checkout/payment-secret/${id}`
152
67
  );
153
- if ("isError" in data && data.isError || !data || !("id" in data)) {
154
- throw new Error("Failed to apply discount code");
155
- }
156
- return data;
157
68
  }
158
- /**
159
- * Remove a discount from a checkout session
160
- */
161
- async removeDiscount(checkoutId, discountId) {
162
- const data = await this.apiClient.delete(
163
- `/checkout/${checkoutId}/discounts/remove/${discountId}`
69
+ async revalidateDiscounts(id) {
70
+ return this.client.get(
71
+ `/api/client/checkout/${id}/discounts/revalidate`
164
72
  );
165
- if ("isError" in data && data.isError || !data || !("id" in data)) {
166
- console.error(`Checkout session with id ${checkoutId} not found`);
167
- return null;
168
- }
169
- return data;
170
73
  }
171
- /**
172
- * Revalidate a checkout session
173
- */
174
- async revalidateDiscounts(checkoutId) {
175
- const data = await this.apiClient.get(
176
- `/checkout/${checkoutId}/discounts/revalidate`
74
+ async applyDiscount(id, data) {
75
+ return this.client.post(
76
+ `/api/client/checkout/${id}/discounts/apply`,
77
+ data
177
78
  );
178
- if ("isError" in data && data.isError || !data || !("id" in data)) {
179
- console.error(`Checkout session with id ${checkoutId} not found`);
180
- return null;
181
- }
182
- return data;
183
79
  }
184
- /**
185
- * Get shipping rates for a checkout session
186
- */
187
- async getShippingRates(checkoutId) {
188
- const data = await this.apiClient.get(
189
- `/checkout/${checkoutId}/shipping/rates`
80
+ async removeDiscount(id, discountId) {
81
+ return this.client.delete(
82
+ `/api/client/checkout/${id}/discounts/remove/${discountId}`
190
83
  );
191
- console.log("SHIPPING RATES DATA: ", data);
192
- if ("isError" in data && data.isError || !data) {
193
- console.error("Failed to get shipping rates: ", data);
194
- return {};
195
- }
196
- return data;
197
- }
198
- /**
199
- * Generate payment secret for a checkout session
200
- */
201
- async generatePaymentSecret(checkoutId) {
202
- const data = await this.apiClient.post(`
203
- /checkout/${checkoutId}/payment`);
204
- if ("isError" in data && data.isError || !data || !("paymentSecret" in data)) {
205
- throw new Error("Failed to generate payment secret");
206
- }
207
- return {
208
- paymentSecret: data.paymentSecret,
209
- publicKey: data.publicKey,
210
- checkoutSession: data.checkoutSession
211
- };
212
84
  }
213
85
  };
214
- var checkout_default = Checkout;
215
86
 
216
- // src/client/index.ts
217
- var Client = class {
218
- proxy;
219
- constructor(proxy) {
220
- this.proxy = proxy;
87
+ // src/namespaces/client/client-customers.ts
88
+ var ClientCustomersNamespace = class {
89
+ constructor(client) {
90
+ this.client = client;
91
+ }
92
+ async upsert(data) {
93
+ return this.client.post(
94
+ "/api/client/customers/upsert",
95
+ data
96
+ );
221
97
  }
222
- /**
223
- * Retrieve a checkout session by ID
224
- */
225
- async retrieveCheckout(clientSecret, checkoutId) {
226
- const apiClient = createApiClient(clientSecret, this.proxy);
227
- const data = await apiClient.get(
228
- `/checkout/${checkoutId}`
98
+ async update(id, data) {
99
+ return this.client.post(
100
+ `/api/client/customers/update/${id}`,
101
+ data
229
102
  );
230
- if ("isError" in data && data.isError || !data || !("id" in data)) {
231
- console.error(`Checkout session with id ${checkoutId} not found`);
232
- return null;
233
- }
234
- return data;
235
103
  }
236
- /**
237
- * Update a checkout session
238
- */
239
- async updateCheckout(clientSecret, checkoutId, params) {
240
- const apiClient = createApiClient(clientSecret, this.proxy);
241
- const data = await apiClient.put(
242
- `/checkout/${checkoutId}`,
104
+ };
105
+
106
+ // src/namespaces/client/client-utils.ts
107
+ var ClientUtilsNamespace = class {
108
+ constructor(client) {
109
+ this.client = client;
110
+ }
111
+ async getExchangeRates(currency) {
112
+ return this.client.get(`/api/client/utils/get-exchange-rates/${currency}`);
113
+ }
114
+ async autosuggestAddress(params) {
115
+ const { query, locale, latitude, longitude, countryCode } = params;
116
+ return this.client.get(`/api/client/utils/autosuggest-address`, {
117
+ query,
118
+ locale,
119
+ latitude,
120
+ longitude,
121
+ countryCode
122
+ });
123
+ }
124
+ async lookupAddressById(id, params = {}) {
125
+ return this.client.get(
126
+ `/api/client/utils/lookup-address-by-id/${id}`,
243
127
  params
244
128
  );
245
- if ("isError" in data && data.isError || !data || !("id" in data)) {
246
- console.error(`Checkout session with id ${checkoutId} not found`);
247
- return null;
248
- }
249
- return data;
250
129
  }
251
- /**
252
- * Apply a discount code to a checkout session
253
- */
254
- async applyDiscountCode(clientSecret, checkoutId, discountCode) {
255
- const apiClient = createApiClient(clientSecret, this.proxy);
256
- const data = await apiClient.post(
257
- `/checkout/${checkoutId}/discounts/apply`,
258
- { code: discountCode }
259
- );
260
- if ("isError" in data && data.isError || !data || !("id" in data)) {
261
- throw new Error("Failed to apply discount code");
130
+ };
131
+
132
+ // src/client-factory.ts
133
+ function createBetterStoreClient(clientSecret, config) {
134
+ const baseClient = new BaseClient({
135
+ baseUrl: config?.proxy || "https://api.betterstore.com",
136
+ headers: {
137
+ Authorization: `Bearer ${clientSecret}`,
138
+ "Content-Type": "application/json"
262
139
  }
263
- return data;
140
+ });
141
+ return {
142
+ checkout: new ClientCheckoutNamespace(baseClient),
143
+ customers: new ClientCustomersNamespace(baseClient),
144
+ utils: new ClientUtilsNamespace(baseClient)
145
+ };
146
+ }
147
+
148
+ // src/namespaces/auth.ts
149
+ var AuthNamespace = class {
150
+ constructor(client) {
151
+ this.client = client;
264
152
  }
265
- /**
266
- * Remove a discount code from a checkout session
267
- */
268
- async removeDiscount(clientSecret, checkoutId, discountId) {
269
- const apiClient = createApiClient(clientSecret, this.proxy);
270
- const data = await apiClient.delete(
271
- `/checkout/${checkoutId}/discounts/remove/${discountId}`
272
- );
273
- if ("isError" in data && data.isError || !data || !("id" in data)) {
274
- throw new Error("Failed to remove discount code");
275
- }
276
- return data;
153
+ async loginCustomerOtp(params) {
154
+ return this.client.post("/api/auth/login-customer-otp", params);
277
155
  }
278
- /**
279
- * Revalidate a checkout session
280
- */
281
- async revalidateDiscounts(clientSecret, checkoutId) {
282
- const apiClient = createApiClient(clientSecret, this.proxy);
283
- const data = await apiClient.get(
284
- `/checkout/${checkoutId}/discounts/revalidate`
285
- );
286
- if ("isError" in data && data.isError || !data || !("id" in data)) {
287
- console.error(`Checkout session with id ${checkoutId} not found`);
288
- return null;
289
- }
290
- return data;
156
+ async signupCustomerOtp(params) {
157
+ return this.client.post("/api/auth/signup-customer-otp", params);
291
158
  }
292
- /**
293
- * Get shipping rates for a checkout session
294
- */
295
- async getCheckoutShippingRates(clientSecret, checkoutId) {
296
- const apiClient = createApiClient(clientSecret, this.proxy);
297
- const data = await apiClient.get(
298
- `/checkout/${checkoutId}/shipping/rates`
159
+ async verifyCustomerOtp(params) {
160
+ return this.client.post("/api/auth/verify-customer-otp", params);
161
+ }
162
+ async getCustomerSession(id) {
163
+ return this.client.get(`/api/auth/get-customer-session/${id}`);
164
+ }
165
+ };
166
+
167
+ // src/namespaces/checkout.ts
168
+ var CheckoutNamespace = class {
169
+ constructor(client) {
170
+ this.client = client;
171
+ }
172
+ async create(data) {
173
+ return this.client.post(
174
+ "/api/checkout/create",
175
+ data
299
176
  );
300
- console.log("SHIPPING RATES DATA: ", data);
301
- if ("isError" in data && data.isError || !data) {
302
- console.error("Failed to get shipping rates: ", data);
303
- return {};
304
- }
305
- return data;
306
177
  }
307
- /**
308
- * Generate payment secret for a checkout session
309
- */
310
- async generateCheckoutPaymentSecret(clientSecret, checkoutId) {
311
- const apiClient = createApiClient(clientSecret, this.proxy);
312
- const data = await apiClient.post(`/checkout/${checkoutId}/payment`);
313
- if ("isError" in data && data.isError || !data || !("paymentSecret" in data)) {
314
- throw new Error("Failed to generate payment secret");
315
- }
316
- return {
317
- paymentSecret: data.paymentSecret,
318
- publicKey: data.publicKey,
319
- checkoutSession: data.checkoutSession
320
- };
178
+ async get(id) {
179
+ return this.client.get(`/api/checkout/get/${id}`);
321
180
  }
322
- /**
323
- * Create a new customer
324
- */
325
- async createCustomer(clientSecret, params) {
326
- const apiClient = createApiClient(clientSecret, this.proxy);
327
- const data = await apiClient.post(
328
- "/customer",
329
- params
181
+ async update(id, data) {
182
+ return this.client.post(
183
+ `/api/checkout/update/${id}`,
184
+ data
330
185
  );
331
- if ("isError" in data && data.isError || !data || !("id" in data)) {
332
- throw new Error("Failed to create customer");
333
- }
334
- return data;
335
186
  }
336
- /**
337
- * Retrieve a customer by ID or email
338
- */
339
- async retrieveCustomer(clientSecret, idOrEmail) {
340
- const apiClient = createApiClient(clientSecret, this.proxy);
341
- const data = await apiClient.get(
342
- `/customer/${idOrEmail}`
187
+ async getShippingRates(id) {
188
+ return this.client.get(
189
+ `/api/checkout/${id}/get-shipping-rates`
343
190
  );
344
- if ("isError" in data && data.isError || !data || !("id" in data)) {
345
- console.error(`Customer with id or email ${idOrEmail} not found`);
346
- return null;
347
- }
348
- return data;
349
191
  }
350
- /**
351
- * Update a customer
352
- */
353
- async updateCustomer(clientSecret, customerId, params) {
354
- const apiClient = createApiClient(clientSecret, this.proxy);
355
- const data = await apiClient.put(
356
- `/customer/${customerId}`,
357
- params
192
+ async generatePaymentSecret(id) {
193
+ return this.client.post(
194
+ `/api/checkout/payment-secret/${id}`
358
195
  );
359
- if ("isError" in data && data.isError || !data || !("id" in data)) {
360
- console.error(`Customer with id ${customerId} not found`);
361
- return null;
362
- }
363
- return data;
364
196
  }
365
- /**
366
- * Get exchange rate for a currency
367
- */
368
- async getExchangeRate(clientSecret, baseCurrency, targetCurrency) {
369
- const apiClient = createApiClient(clientSecret, this.proxy);
370
- const data = await apiClient.get(
371
- `/helpers/rates/${baseCurrency}`
197
+ async revalidateDiscounts(id) {
198
+ return this.client.get(
199
+ `/api/checkout/${id}/discounts/revalidate`
372
200
  );
373
- const rate = data.rates[targetCurrency];
374
- if (!rate) {
375
- throw new Error("Could not get exchange rate for target currency");
376
- }
377
- return rate;
378
201
  }
379
- /**
380
- * Get autosuggest address results
381
- */
382
- async getAutosuggestAddressResults(clientSecret, params) {
383
- const apiClient = createApiClient(clientSecret, this.proxy);
384
- const { data } = await apiClient.get("/helpers/address/autosuggest", {
385
- params
386
- });
387
- return data ?? [];
202
+ async applyDiscount(id, data) {
203
+ return this.client.post(
204
+ `/api/checkout/${id}/discounts/apply`,
205
+ data
206
+ );
388
207
  }
389
- async lookupAddress(clientSecret, params) {
390
- const apiClient = createApiClient(clientSecret, this.proxy);
391
- const { data } = await apiClient.get("/helpers/address/lookup", {
392
- params
393
- });
394
- return data;
208
+ async removeDiscount(id, discountId) {
209
+ return this.client.delete(
210
+ `/api/checkout/${id}/discounts/remove/${discountId}`
211
+ );
395
212
  }
396
213
  };
397
- var client_default = Client;
398
214
 
399
- // src/collections/index.ts
400
- var Collections = class {
401
- apiClient;
402
- constructor(apiKey, proxy) {
403
- this.apiClient = createApiClient(apiKey, proxy);
215
+ // src/namespaces/collections.ts
216
+ var CollectionsNamespace = class {
217
+ constructor(client) {
218
+ this.client = client;
404
219
  }
405
220
  async list(params) {
406
- const data = await this.apiClient.post(`/collections`, params ?? {});
407
- if (!data || "isError" in data && data.isError || !("collections" in data)) {
408
- return [];
409
- }
410
- return data.collections;
221
+ return this.client.post(
222
+ "/api/collections/find-many",
223
+ params
224
+ );
411
225
  }
412
- async retrieve(params) {
413
- const data = await this.apiClient.post(`/collections/retrieve`, params);
414
- if ("isError" in data && data.isError || !data || !("collection" in data)) {
415
- console.error(`Collection not found`);
416
- return null;
417
- }
418
- return data.collection;
226
+ async findFirst(params) {
227
+ return this.client.post(
228
+ "/api/collections/find-first",
229
+ params
230
+ );
419
231
  }
420
232
  };
421
- var collections_default = Collections;
422
233
 
423
- // src/customer/index.ts
424
- var Customer = class {
425
- apiClient;
426
- constructor(apiKey, proxy) {
427
- this.apiClient = createApiClient(apiKey, proxy);
428
- }
429
- /**
430
- * Create a new customer
431
- */
432
- async create(params) {
433
- const data = await this.apiClient.post(
434
- "/customer",
435
- params
234
+ // src/namespaces/customers.ts
235
+ var CustomersNamespace = class {
236
+ constructor(client) {
237
+ this.client = client;
238
+ }
239
+ async upsert(data) {
240
+ return this.client.post(
241
+ "/api/customers/upsert",
242
+ data
436
243
  );
437
- if ("isError" in data && data.isError || !data || !("id" in data)) {
438
- throw new Error("Failed to create customer");
439
- }
440
- return data;
441
244
  }
442
- /**
443
- * Retrieve a customer by ID or email
444
- */
445
- async retrieve(idOrEmail) {
446
- const data = await this.apiClient.get(
447
- `/customer/${idOrEmail}`
245
+ async findFirst(idOrEmail) {
246
+ return this.client.get(
247
+ `/api/customers/find-first/${idOrEmail}`
448
248
  );
449
- if ("isError" in data && data.isError || !data || !("id" in data)) {
450
- console.error(`Customer with id or email ${idOrEmail} not found`);
451
- return null;
452
- }
453
- return data;
454
249
  }
455
- /**
456
- * Update a customer
457
- */
458
- async update(customerId, params) {
459
- const data = await this.apiClient.put(
460
- `/customer/${customerId}`,
461
- params
250
+ async update(id, data) {
251
+ return this.client.post(
252
+ `/api/customers/update/${id}`,
253
+ data
462
254
  );
463
- if ("isError" in data && data.isError || !data || !("id" in data)) {
464
- console.error(`Customer with id ${customerId} not found`);
465
- return null;
466
- }
467
- return data;
468
- }
469
- /**
470
- * Delete a customer
471
- */
472
- async delete(customerId) {
473
- await this.apiClient.delete(`/customer/${customerId}`);
474
255
  }
475
- /**
476
- * Update a customer subscription
477
- */
478
- async updateCustomerSubscription(stripeSubscriptionId, params) {
479
- const data = await this.apiClient.put(
480
- `/customer/subscription/${stripeSubscriptionId}`,
481
- params
256
+ async delete(id) {
257
+ return this.client.delete(
258
+ `/api/customers/delete/${id}`
482
259
  );
483
- if ("isError" in data && data.isError || !data || !("id" in data)) {
484
- return null;
485
- }
486
- return data;
487
260
  }
488
261
  };
489
- var customer_default = Customer;
490
262
 
491
- // src/discounts/index.ts
492
- var Discounts = class {
493
- apiClient;
494
- constructor(apiKey, proxy) {
495
- this.apiClient = createApiClient(apiKey, proxy);
263
+ // src/namespaces/products.ts
264
+ var ProductsNamespace = class {
265
+ constructor(client) {
266
+ this.client = client;
496
267
  }
268
+ /**
269
+ * List products with optional filtering, sorting, and pagination
270
+ */
497
271
  async list(params) {
498
- const data = await this.apiClient.post(
499
- "/discounts",
500
- params ?? {}
272
+ return this.client.post(
273
+ "/api/products/find-many",
274
+ params
501
275
  );
502
- if (!data || "isError" in data && data.isError || !("discounts" in data)) {
503
- return [];
504
- }
505
- return data.discounts;
506
276
  }
507
- async retrieve(params) {
508
- const data = await this.apiClient.post(
509
- `/discounts/retrieve`,
277
+ /**
278
+ * Find the first product matching the criteria
279
+ */
280
+ async findFirst(params) {
281
+ return this.client.post(
282
+ "/api/products/find-first",
510
283
  params
511
284
  );
512
- if ("isError" in data && data.isError || !data || !("discount" in data)) {
513
- console.error(`Discount not found`);
514
- return null;
515
- }
516
- return data.discount;
517
285
  }
518
286
  };
519
- var discounts_default = Discounts;
520
287
 
521
- // src/products/index.ts
522
- var Products = class {
523
- apiClient;
524
- constructor(apiKey, proxy) {
525
- this.apiClient = createApiClient(apiKey, proxy);
526
- }
527
- async list(params) {
528
- const data = await this.apiClient.post(
529
- "/products",
530
- params ?? {}
531
- );
532
- if (!data || "isError" in data && data.isError || !("products" in data)) {
533
- return [];
534
- }
535
- return data.products;
288
+ // src/namespaces/utils.ts
289
+ var UtilsNamespace = class {
290
+ constructor(client) {
291
+ this.client = client;
292
+ }
293
+ async getExchangeRates(currency) {
294
+ return this.client.get(`/api/utils/get-exchange-rates/${currency}`);
295
+ }
296
+ async autosuggestAddress(params) {
297
+ const { query, locale, latitude, longitude, countryCode } = params;
298
+ return this.client.get(`/api/utils/autosuggest-address`, {
299
+ query,
300
+ locale,
301
+ latitude,
302
+ longitude,
303
+ countryCode
304
+ });
536
305
  }
537
- async retrieve(params) {
538
- const data = await this.apiClient.post("/products/retrieve", params);
539
- if ("isError" in data && data.isError || !data || !("product" in data)) {
540
- console.error(`Product not found`);
541
- return null;
542
- }
543
- return data.product;
306
+ async lookupAddressById(id, params = {}) {
307
+ return this.client.get(`/api/utils/lookup-address-by-id/${id}`, params);
544
308
  }
545
309
  };
546
- var products_default = Products;
547
310
 
548
- // src/types-and-methods.ts
549
- import { formatCurrency, formatPrice } from "@betterstore/bridge";
550
-
551
- // src/methods/cart-discounts.ts
552
- function getHighestDiscount(productId, priceInCents, discounts) {
553
- const applicableDiscounts = discounts.filter(
554
- (discount) => discount.allowedProductIDs.includes(productId)
555
- );
556
- const bestDiscount = applicableDiscounts.length > 1 ? applicableDiscounts.reduce((bestSoFar, currentDiscount) => {
557
- let currentDiscountValueInCents = currentDiscount.value;
558
- if (currentDiscount.valueType === "PERCENTAGE") {
559
- currentDiscountValueInCents = currentDiscount.value / 100 * priceInCents;
560
- } else if (currentDiscount.valueType === "FREE") {
561
- currentDiscountValueInCents = priceInCents;
311
+ // src/main-factory.ts
312
+ function createBetterStore(secret, config) {
313
+ const baseClient = new BaseClient({
314
+ baseUrl: config?.proxy || "https://v1.betterstore.io",
315
+ headers: {
316
+ Authorization: `Bearer ${secret}`,
317
+ "Content-Type": "application/json"
562
318
  }
563
- return (bestSoFar?.value ?? 0) > currentDiscountValueInCents ? bestSoFar : currentDiscount;
564
- }, applicableDiscounts[0]) : applicableDiscounts[0];
565
- return bestDiscount;
566
- }
567
- function calculateDiscountAmount(originalPrice, discount) {
568
- let discountValueInCents = discount?.value;
569
- const isFreeDiscount = discount?.valueType === "FREE";
570
- if (discount?.valueType === "PERCENTAGE") {
571
- discountValueInCents = discount.value / 100 * originalPrice;
572
- } else if (discount?.valueType === "FREE") {
573
- discountValueInCents = originalPrice;
574
- }
575
- const finalPrice = discountValueInCents ? Math.max(originalPrice - discountValueInCents, 0) : originalPrice;
576
- const isDiscounted = discountValueInCents === 0;
577
- return {
578
- finalPrice,
579
- discountAmount: discountValueInCents ?? 0,
580
- originalPrice,
581
- isFree: isFreeDiscount,
582
- isDiscounted
583
- };
584
- }
585
- function findAutomaticProductDiscount({
586
- productId,
587
- priceInCents,
588
- discounts
589
- }) {
590
- const discount = getHighestDiscount(productId, priceInCents, discounts);
591
- const result = calculateDiscountAmount(priceInCents, discount);
592
- return { ...result, discount };
593
- }
594
-
595
- // src/index.ts
596
- function createBetterStore(config) {
597
- if (!config.apiKey) {
598
- throw new Error("API key is required.");
599
- }
319
+ });
600
320
  return {
601
- checkout: new checkout_default(config.apiKey, config.proxy),
602
- customer: new customer_default(config.apiKey, config.proxy),
603
- discounts: new discounts_default(config.apiKey, config.proxy),
604
- collections: new collections_default(config.apiKey, config.proxy),
605
- products: new products_default(config.apiKey, config.proxy),
606
- auth: new auth_default(config.apiKey, config.proxy)
321
+ products: new ProductsNamespace(baseClient),
322
+ collections: new CollectionsNamespace(baseClient),
323
+ customers: new CustomersNamespace(baseClient),
324
+ auth: new AuthNamespace(baseClient),
325
+ checkout: new CheckoutNamespace(baseClient),
326
+ utils: new UtilsNamespace(baseClient)
607
327
  };
608
328
  }
609
- function createStoreClient(config) {
610
- return new client_default(config?.proxy);
611
- }
612
329
  export {
613
- createStoreClient,
614
- createBetterStore as default,
615
- findAutomaticProductDiscount,
616
- formatCurrency,
617
- formatPrice
330
+ createBetterStore,
331
+ createBetterStoreClient
618
332
  };