@betterstore/sdk 0.6.13 → 0.7.2

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,349 @@ 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: {
28
+ // src/base-client.ts
29
+ var DEFAULT_BASE_URL = "https://v1.betterstore.io";
30
+ var BaseClient = class {
31
+ constructor(config) {
32
+ this.config = config;
33
+ this.headers = {
48
34
  "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;
59
- });
35
+ Authorization: `Bearer ${this.config.secret}`
36
+ };
60
37
  }
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;
38
+ headers;
39
+ async get(path, params) {
40
+ const url = `${this.config.baseUrl}${path}`;
41
+ const searchParams = new URLSearchParams();
42
+ if (params) {
43
+ Object.entries(params).forEach(([key, val]) => {
44
+ if (val !== void 0) searchParams.set(key, val);
45
+ });
46
+ }
47
+ console.log(`${url}?${searchParams.toString()}`);
48
+ const res = await fetch(`${url}?${searchParams.toString()}`, {
49
+ method: "GET",
50
+ headers: this.headers
51
+ });
52
+ return this.handleResponse(res);
89
53
  }
90
- async login(params) {
91
- const data = await this.apiClient.post(
92
- "/auth/otp/login",
93
- params
94
- );
95
- return data;
54
+ async post(path, body) {
55
+ const res = await fetch(`${this.config.baseUrl}${path}`, {
56
+ method: "POST",
57
+ headers: this.headers,
58
+ body: body ? JSON.stringify(body) : void 0
59
+ });
60
+ return this.handleResponse(res);
96
61
  }
97
- async verify(params) {
98
- const data = await this.apiClient.post(
99
- "/auth/otp/verify",
100
- params
101
- );
102
- return data;
62
+ async delete(path) {
63
+ const res = await fetch(`${this.config.baseUrl}${path}`, {
64
+ method: "DELETE",
65
+ headers: this.headers
66
+ });
67
+ return this.handleResponse(res);
103
68
  }
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;
69
+ async handleResponse(res) {
70
+ if (!res.ok) {
71
+ const error = await res.json().catch(() => ({ message: res.statusText, data: res.body }));
72
+ console.log(error);
73
+ throw new Error(error.message || `HTTP ${res.status}`);
121
74
  }
122
- return data;
75
+ return res.json();
123
76
  }
124
77
  };
125
- var auth_default = Auth;
126
78
 
127
- // src/checkout/index.ts
128
- var Checkout = class {
129
- apiClient;
130
- constructor(apiKey, proxy) {
131
- this.apiClient = createApiClient(apiKey, proxy);
79
+ // src/namespaces/client/client-checkout.ts
80
+ var ClientCheckoutNamespace = class {
81
+ constructor(client) {
82
+ this.client = client;
83
+ }
84
+ async get(id) {
85
+ return this.client.get(
86
+ `/api/client/checkout/get/${id}`
87
+ );
132
88
  }
133
- /**
134
- * Create a new checkout session
135
- */
136
- async create(params) {
137
- const data = await this.apiClient.post(
138
- "/checkout",
139
- params
89
+ async update(id, data) {
90
+ return this.client.post(
91
+ `/api/client/checkout/update/${id}`,
92
+ data
140
93
  );
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
94
  }
146
- /**
147
- * Retrieve a checkout session by ID
148
- */
149
- async retrieve(checkoutId) {
150
- const data = await this.apiClient.get(
151
- `/checkout/${checkoutId}`
95
+ async getShippingRates(id) {
96
+ return this.client.get(
97
+ `/api/client/checkout/${id}/get-shipping-rates`
152
98
  );
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
99
  }
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
100
+ async generatePaymentSecret(id) {
101
+ return this.client.post(
102
+ `/api/client/checkout/payment-secret/${id}`
166
103
  );
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
104
  }
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 }
105
+ async revalidateDiscounts(id) {
106
+ return this.client.get(
107
+ `/api/client/checkout/${id}/discounts/revalidate`
180
108
  );
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
109
  }
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}`
110
+ async applyDiscount(id, data) {
111
+ return this.client.post(
112
+ `/api/client/checkout/${id}/discounts/apply`,
113
+ data
192
114
  );
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
115
  }
199
- /**
200
- * Revalidate a checkout session
201
- */
202
- async revalidateDiscounts(checkoutId) {
203
- const data = await this.apiClient.get(
204
- `/checkout/${checkoutId}/discounts/revalidate`
116
+ async removeDiscount(id, discountId) {
117
+ return this.client.delete(
118
+ `/api/client/checkout/${id}/discounts/remove/${discountId}`
205
119
  );
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
120
  }
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`
121
+ };
122
+
123
+ // src/namespaces/client/client-customers.ts
124
+ var ClientCustomersNamespace = class {
125
+ constructor(client) {
126
+ this.client = client;
127
+ }
128
+ async upsert(data) {
129
+ return this.client.post(
130
+ "/api/client/customers/upsert",
131
+ data
218
132
  );
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
133
  }
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
- };
134
+ async update(id, data) {
135
+ return this.client.post(
136
+ `/api/client/customers/update/${id}`,
137
+ data
138
+ );
240
139
  }
241
140
  };
242
- var checkout_default = Checkout;
243
141
 
244
- // src/client/index.ts
245
- var Client = class {
246
- proxy;
247
- constructor(proxy) {
248
- this.proxy = proxy;
142
+ // src/namespaces/client/client-utils.ts
143
+ var ClientUtilsNamespace = class {
144
+ constructor(client) {
145
+ this.client = client;
146
+ }
147
+ async getExchangeRates(currency) {
148
+ return this.client.get(`/api/client/utils/get-exchange-rates/${currency}`);
149
+ }
150
+ async autosuggestAddress(params) {
151
+ const { query, locale, latitude, longitude, countryCode } = params;
152
+ return this.client.get(`/api/client/utils/autosuggest-address`, {
153
+ query,
154
+ locale,
155
+ latitude,
156
+ longitude,
157
+ countryCode
158
+ });
249
159
  }
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}`
160
+ async lookupAddressById(id, params = {}) {
161
+ return this.client.get(
162
+ `/api/client/utils/lookup-address-by-id/${id}`,
163
+ params
257
164
  );
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
165
  }
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;
276
- }
277
- return data;
166
+ };
167
+
168
+ // src/client-factory.ts
169
+ function createBetterStoreClient(checkoutSecret, config) {
170
+ const baseClient = new BaseClient({
171
+ baseUrl: config?.proxy || DEFAULT_BASE_URL,
172
+ secret: checkoutSecret
173
+ });
174
+ return {
175
+ checkout: new ClientCheckoutNamespace(baseClient),
176
+ customers: new ClientCustomersNamespace(baseClient),
177
+ utils: new ClientUtilsNamespace(baseClient)
178
+ };
179
+ }
180
+
181
+ // src/namespaces/auth.ts
182
+ var AuthNamespace = class {
183
+ constructor(client) {
184
+ this.client = client;
278
185
  }
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;
186
+ async loginCustomerOtp(params) {
187
+ return this.client.post("/api/auth/login-customer-otp", params);
292
188
  }
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;
189
+ async signupCustomerOtp(params) {
190
+ return this.client.post("/api/auth/signup-customer-otp", params);
305
191
  }
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;
192
+ async verifyCustomerOtp(params) {
193
+ return this.client.post("/api/auth/verify-customer-otp", params);
319
194
  }
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`
195
+ async getCustomerSession(id) {
196
+ return this.client.get(`/api/auth/get-customer-session/${id}`);
197
+ }
198
+ };
199
+
200
+ // src/namespaces/checkout.ts
201
+ var CheckoutNamespace = class {
202
+ constructor(client) {
203
+ this.client = client;
204
+ }
205
+ async create(data) {
206
+ return this.client.post(
207
+ "/api/checkout/create",
208
+ data
327
209
  );
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
210
  }
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
- };
211
+ async get(id) {
212
+ return this.client.get(`/api/checkout/get/${id}`);
349
213
  }
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
214
+ async update(id, data) {
215
+ return this.client.post(
216
+ `/api/checkout/update/${id}`,
217
+ data
358
218
  );
359
- if ("isError" in data && data.isError || !data || !("id" in data)) {
360
- throw new Error("Failed to create customer");
361
- }
362
- return data;
363
219
  }
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}`
220
+ async getShippingRates(id) {
221
+ return this.client.get(
222
+ `/api/checkout/${id}/get-shipping-rates`
371
223
  );
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
224
  }
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
225
+ async generatePaymentSecret(id) {
226
+ return this.client.post(
227
+ `/api/checkout/payment-secret/${id}`
386
228
  );
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
229
  }
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}`
230
+ async revalidateDiscounts(id) {
231
+ return this.client.get(
232
+ `/api/checkout/${id}/discounts/revalidate`
400
233
  );
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
234
  }
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 ?? [];
235
+ async applyDiscount(id, data) {
236
+ return this.client.post(
237
+ `/api/checkout/${id}/discounts/apply`,
238
+ data
239
+ );
416
240
  }
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;
241
+ async removeDiscount(id, discountId) {
242
+ return this.client.delete(
243
+ `/api/checkout/${id}/discounts/remove/${discountId}`
244
+ );
423
245
  }
424
246
  };
425
- var client_default = Client;
426
247
 
427
- // src/collections/index.ts
428
- var Collections = class {
429
- apiClient;
430
- constructor(apiKey, proxy) {
431
- this.apiClient = createApiClient(apiKey, proxy);
248
+ // src/namespaces/collections.ts
249
+ var CollectionsNamespace = class {
250
+ constructor(client) {
251
+ this.client = client;
432
252
  }
433
253
  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;
254
+ return this.client.post(
255
+ "/api/collections/find-many",
256
+ params
257
+ );
439
258
  }
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;
259
+ async findFirst(params) {
260
+ return this.client.post(
261
+ "/api/collections/find-first",
262
+ params
263
+ );
447
264
  }
448
265
  };
449
- var collections_default = Collections;
450
266
 
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
267
+ // src/namespaces/customers.ts
268
+ var CustomersNamespace = class {
269
+ constructor(client) {
270
+ this.client = client;
271
+ }
272
+ async upsert(data) {
273
+ return this.client.post(
274
+ "/api/customers/upsert",
275
+ data
464
276
  );
465
- if ("isError" in data && data.isError || !data || !("id" in data)) {
466
- throw new Error("Failed to create customer");
467
- }
468
- return data;
469
277
  }
470
- /**
471
- * Retrieve a customer by ID or email
472
- */
473
- async retrieve(idOrEmail) {
474
- const data = await this.apiClient.get(
475
- `/customer/${idOrEmail}`
278
+ async findFirst(idOrEmail) {
279
+ return this.client.get(
280
+ `/api/customers/find-first/${idOrEmail}`
476
281
  );
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
282
  }
483
- /**
484
- * Update a customer
485
- */
486
- async update(customerId, params) {
487
- const data = await this.apiClient.put(
488
- `/customer/${customerId}`,
489
- params
283
+ async update(id, data) {
284
+ return this.client.post(
285
+ `/api/customers/update/${id}`,
286
+ data
490
287
  );
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
288
  }
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
289
+ async delete(id) {
290
+ return this.client.delete(
291
+ `/api/customers/delete/${id}`
510
292
  );
511
- if ("isError" in data && data.isError || !data || !("id" in data)) {
512
- return null;
513
- }
514
- return data;
515
293
  }
516
294
  };
517
- var customer_default = Customer;
518
295
 
519
- // src/discounts/index.ts
520
- var Discounts = class {
521
- apiClient;
522
- constructor(apiKey, proxy) {
523
- this.apiClient = createApiClient(apiKey, proxy);
296
+ // src/namespaces/products.ts
297
+ var ProductsNamespace = class {
298
+ constructor(client) {
299
+ this.client = client;
524
300
  }
301
+ /**
302
+ * List products with optional filtering, sorting, and pagination
303
+ */
525
304
  async list(params) {
526
- const data = await this.apiClient.post(
527
- "/discounts",
528
- params ?? {}
305
+ return this.client.post(
306
+ "/api/products/find-many",
307
+ params
529
308
  );
530
- if (!data || "isError" in data && data.isError || !("discounts" in data)) {
531
- return [];
532
- }
533
- return data.discounts;
534
309
  }
535
- async retrieve(params) {
536
- const data = await this.apiClient.post(
537
- `/discounts/retrieve`,
310
+ /**
311
+ * Find the first product matching the criteria
312
+ */
313
+ async findFirst(params) {
314
+ return this.client.post(
315
+ "/api/products/find-first",
538
316
  params
539
317
  );
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
318
  }
546
319
  };
547
- var discounts_default = Discounts;
548
320
 
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;
321
+ // src/namespaces/utils.ts
322
+ var UtilsNamespace = class {
323
+ constructor(client) {
324
+ this.client = client;
325
+ }
326
+ async getExchangeRates(currency) {
327
+ return this.client.get(`/api/utils/get-exchange-rates/${currency}`);
328
+ }
329
+ async autosuggestAddress(params) {
330
+ const { query, locale, latitude, longitude, countryCode } = params;
331
+ return this.client.get(`/api/utils/autosuggest-address`, {
332
+ query,
333
+ locale,
334
+ latitude,
335
+ longitude,
336
+ countryCode
337
+ });
564
338
  }
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;
339
+ async lookupAddressById(id, params = {}) {
340
+ return this.client.get(`/api/utils/lookup-address-by-id/${id}`, params);
572
341
  }
573
342
  };
574
- var products_default = Products;
575
-
576
- // src/types-and-methods.ts
577
- var import_bridge = require("@betterstore/bridge");
578
-
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;
590
- }
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
343
 
623
- // src/index.ts
624
- function createBetterStore(config) {
625
- if (!config.apiKey) {
626
- throw new Error("API key is required.");
627
- }
344
+ // src/main-factory.ts
345
+ function createBetterStore(secret, config) {
346
+ const baseClient = new BaseClient({
347
+ baseUrl: config?.proxy || DEFAULT_BASE_URL,
348
+ secret
349
+ });
628
350
  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)
351
+ products: new ProductsNamespace(baseClient),
352
+ collections: new CollectionsNamespace(baseClient),
353
+ customers: new CustomersNamespace(baseClient),
354
+ auth: new AuthNamespace(baseClient),
355
+ checkout: new CheckoutNamespace(baseClient),
356
+ utils: new UtilsNamespace(baseClient)
635
357
  };
636
358
  }
637
- function createStoreClient(config) {
638
- return new client_default(config?.proxy);
639
- }
640
359
  // Annotate the CommonJS export names for ESM import in node:
641
360
  0 && (module.exports = {
642
- createStoreClient,
643
- findAutomaticProductDiscount,
644
- formatCurrency,
645
- formatPrice
361
+ createBetterStore,
362
+ createBetterStoreClient
646
363
  });