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