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