@commercengine/storefront-sdk 0.3.0 → 0.3.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/lib/auth.js CHANGED
@@ -1,182 +1,42 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.NextCookieTokenStorage = exports.CookieTokenStorage = exports.BrowserTokenStorage = exports.MemoryTokenStorage = exports.AuthClient = void 0;
4
- exports.createTokenStorage = createTokenStorage;
5
- const client_1 = require("./client");
1
+ import { StorefrontAPIClient } from "./client";
6
2
  /**
7
3
  * Client for interacting with authentication endpoints
8
4
  */
9
- class AuthClient extends client_1.StorefrontAPIClient {
10
- constructor(config, tokenStorage) {
5
+ export class AuthClient extends StorefrontAPIClient {
6
+ constructor(config) {
11
7
  super(config);
12
- this.autoRefreshTimer = null;
13
- this.tokenStorage = tokenStorage;
14
- this.setupAutoRefresh();
15
- }
16
- // Override the setToken method to use storage
17
- async setToken(token) {
18
- super.setToken(token); // Set token in client
19
- await this.tokenStorage.setItem("access_token", token);
20
- // If we also have a refresh token, store it
21
- const refreshToken = await this.tokenStorage.getItem("refresh_token");
22
- if (refreshToken) {
23
- this.setupAutoRefresh();
24
- }
25
- }
26
- // Store refresh token separately
27
- async setRefreshToken(token) {
28
- await this.tokenStorage.setItem("refresh_token", token);
29
- }
30
- // Clear tokens from storage
31
- async clearToken() {
32
- super.clearToken(); // Clear token in client
33
- await this.tokenStorage.removeItem("access_token");
34
- await this.tokenStorage.removeItem("refresh_token");
35
- await this.tokenStorage.removeItem("user_data");
36
- this.clearAutoRefresh();
37
- }
38
- // Setup auto refresh based on token expiry
39
- async setupAutoRefresh() {
40
- this.clearAutoRefresh();
41
- const token = await this.tokenStorage.getItem("access_token");
42
- if (!token)
43
- return;
44
- const expiryTime = this.getTokenExpiry(token);
45
- if (!expiryTime)
46
- return;
47
- // Calculate refresh time (30 seconds before expiry)
48
- const currentTime = Math.floor(Date.now() / 1000);
49
- const timeUntilRefresh = Math.max(0, expiryTime - currentTime - 30) * 1000;
50
- // Cap the timeout to avoid integer overflow (max 2147483647 ms, ~24.8 days)
51
- const maxTimeout = 2147483647;
52
- const safeTimeout = Math.min(timeUntilRefresh, maxTimeout);
53
- // If the token expires far in the future, we'll need to reset the timer periodically
54
- if (timeUntilRefresh > maxTimeout) {
55
- this.autoRefreshTimer = setTimeout(() => {
56
- this.setupAutoRefresh(); // Recalculate the timer
57
- }, maxTimeout);
58
- }
59
- else {
60
- this.autoRefreshTimer = setTimeout(() => {
61
- this.handleTokenRefresh();
62
- }, safeTimeout);
63
- }
64
- }
65
- clearAutoRefresh() {
66
- if (this.autoRefreshTimer) {
67
- clearTimeout(this.autoRefreshTimer);
68
- this.autoRefreshTimer = null;
69
- }
70
- }
71
- async handleTokenRefresh() {
72
- try {
73
- const refreshToken = await this.tokenStorage.getItem("refresh_token");
74
- if (!refreshToken)
75
- return;
76
- const tokens = await this.refreshToken(refreshToken);
77
- await this.setToken(tokens.access_token);
78
- await this.setRefreshToken(tokens.refresh_token);
79
- }
80
- catch (error) {
81
- // If refresh fails, clear tokens
82
- await this.clearToken();
83
- }
84
- }
85
- getTokenExpiry(token) {
86
- try {
87
- // Simple JWT parsing (payload is the middle part between dots)
88
- const parts = token.split(".");
89
- if (parts.length !== 3)
90
- return null;
91
- // Base64 decode the payload
92
- // We need to fix the base64 padding for the browser's atob function
93
- const base64 = parts[1].replace(/-/g, "+").replace(/_/g, "/");
94
- const padded = base64.padEnd(base64.length + ((4 - (base64.length % 4)) % 4), "=");
95
- // In Node.js
96
- let jsonStr;
97
- if (typeof Buffer !== "undefined") {
98
- jsonStr = Buffer.from(padded, "base64").toString();
99
- }
100
- // In browser
101
- else if (typeof atob !== "undefined") {
102
- jsonStr = atob(padded);
103
- }
104
- // Fallback
105
- else {
106
- return null;
107
- }
108
- const payload = JSON.parse(jsonStr);
109
- return payload.exp;
110
- }
111
- catch (error) {
112
- console.error("Error parsing JWT token:", error);
113
- return null;
114
- }
115
8
  }
116
9
  /**
117
- * Store auth data including tokens and user info
118
- */
119
- async storeAuthData(accessToken, refreshToken, user) {
120
- await this.setToken(accessToken);
121
- await this.setRefreshToken(refreshToken);
122
- if (user) {
123
- await this.tokenStorage.setItem("user_data", JSON.stringify(user));
124
- }
125
- }
126
- /**
127
- * Get stored user data
128
- * @returns Promise that resolves to the stored user data or null if none exists
10
+ * Get anonymous token for guest users
129
11
  */
130
- async getStoredUser() {
131
- const userData = await this.tokenStorage.getItem("user_data");
132
- if (!userData)
133
- return null;
134
- try {
135
- return JSON.parse(userData);
136
- }
137
- catch {
138
- return null;
139
- }
12
+ async getAnonymousToken() {
13
+ return this.executeRequest(() => this.client.POST("/auth/anonymous"));
140
14
  }
141
15
  /**
142
- * Get anonymous token for guest users
16
+ * Login with phone number
17
+ *
18
+ * @param phoneNumber - Phone number (without country code)
19
+ * @param countryCode - Country code (defaults to +91)
20
+ * @param registerIfNotExists - Whether to register if user doesn't exist
21
+ * @returns Promise with OTP token and action
143
22
  */
144
- async getAnonymousToken(options) {
145
- return this.executeWithTokenRefresh(async () => {
146
- const { data, error } = await this.client.POST("/auth/anonymous", {
147
- headers: options?.apiKey ? { "X-Api-Key": options.apiKey } : undefined,
148
- });
149
- if (error) {
150
- this.handleError(error);
151
- }
152
- const response = data?.content;
153
- // Store tokens and user data
154
- await this.storeAuthData(response.access_token, response.refresh_token, response.user);
155
- return response;
156
- });
23
+ async loginWithPhone(body) {
24
+ return this.executeRequest(() => this.client.POST("/auth/login/phone", {
25
+ body: body,
26
+ }));
157
27
  }
158
28
  /**
159
- * Login with phone number
29
+ * Login with WhatsApp
160
30
  *
161
31
  * @param phoneNumber - Phone number (without country code)
162
32
  * @param countryCode - Country code (defaults to +91)
163
33
  * @param registerIfNotExists - Whether to register if user doesn't exist
164
34
  * @returns Promise with OTP token and action
165
35
  */
166
- async loginWithPhone(phoneNumber, countryCode = "+91", registerIfNotExists = false) {
167
- return this.executeWithTokenRefresh(async () => {
168
- const { data, error } = await this.client.POST("/auth/login/phone", {
169
- body: {
170
- phone: phoneNumber,
171
- country_code: countryCode,
172
- register_if_not_exists: registerIfNotExists,
173
- },
174
- });
175
- if (error) {
176
- this.handleError(error);
177
- }
178
- return data?.content;
179
- });
36
+ async loginWithWhatsApp(body) {
37
+ return this.executeRequest(() => this.client.POST("/auth/login/whatsapp", {
38
+ body: body,
39
+ }));
180
40
  }
181
41
  /**
182
42
  * Login with email
@@ -185,19 +45,10 @@ class AuthClient extends client_1.StorefrontAPIClient {
185
45
  * @param registerIfNotExists - Whether to register if user doesn't exist
186
46
  * @returns Promise with OTP token and action
187
47
  */
188
- async loginWithEmail(email, registerIfNotExists = false) {
189
- return this.executeWithTokenRefresh(async () => {
190
- const { data, error } = await this.client.POST("/auth/login/email", {
191
- body: {
192
- email,
193
- register_if_not_exists: registerIfNotExists,
194
- },
195
- });
196
- if (error) {
197
- this.handleError(error);
198
- }
199
- return data?.content;
200
- });
48
+ async loginWithEmail(body) {
49
+ return this.executeRequest(() => this.client.POST("/auth/login/email", {
50
+ body: body,
51
+ }));
201
52
  }
202
53
  /**
203
54
  * Login with password
@@ -205,19 +56,45 @@ class AuthClient extends client_1.StorefrontAPIClient {
205
56
  * @param credentials - Login credentials
206
57
  * @returns Promise with user info and tokens
207
58
  */
208
- async loginWithPassword(credentials) {
209
- return this.executeWithTokenRefresh(async () => {
210
- const { data, error } = await this.client.POST("/auth/login/password", {
211
- body: credentials,
212
- });
213
- if (error) {
214
- this.handleError(error);
215
- }
216
- const response = data?.content;
217
- // Store tokens and user ID
218
- await this.storeAuthData(response.access_token, response.refresh_token, response.user);
219
- return response;
220
- });
59
+ async loginWithPassword(body) {
60
+ return this.executeRequest(() => this.client.POST("/auth/login/password", {
61
+ body: body,
62
+ }));
63
+ }
64
+ /**
65
+ * Forgot password
66
+ *
67
+ * @param email - Email address
68
+ * @returns Promise with user info and tokens
69
+ */
70
+ async forgotPassword(body) {
71
+ return this.executeRequest(() => this.client.POST("/auth/forgot-password", {
72
+ body: body,
73
+ }));
74
+ }
75
+ /**
76
+ * Reset password
77
+ *
78
+ * @param email - Email address
79
+ * @returns Promise with user info and tokens
80
+ */
81
+ async resetPassword(body) {
82
+ return this.executeRequest(() => this.client.POST("/auth/reset-password", {
83
+ body: body,
84
+ }));
85
+ }
86
+ /**
87
+ * Change password
88
+ *
89
+ * @param oldPassword - Old password
90
+ * @param newPassword - New password
91
+ * @param newPasswordConfirmation - New password confirmation
92
+ * @returns Promise with new access token and refresh token
93
+ */
94
+ async changePassword(body) {
95
+ return this.executeRequest(() => this.client.POST("/auth/change-password", {
96
+ body: body,
97
+ }));
221
98
  }
222
99
  /**
223
100
  * Verify OTP
@@ -227,24 +104,10 @@ class AuthClient extends client_1.StorefrontAPIClient {
227
104
  * @param otpAction - OTP action from login request
228
105
  * @returns Promise with user info and tokens
229
106
  */
230
- async verifyOtp(otp, otpToken, otpAction) {
231
- return this.executeWithTokenRefresh(async () => {
232
- const { data, error } = await this.client.POST("/auth/verify-otp", {
233
- body: {
234
- otp,
235
- otp_token: otpToken,
236
- otp_action: otpAction,
237
- },
238
- });
239
- if (error) {
240
- this.handleError(error);
241
- }
242
- if (data?.content?.access_token && data?.content?.refresh_token) {
243
- await this.setToken(data.content.access_token);
244
- await this.setRefreshToken(data.content.refresh_token);
245
- }
246
- return data?.content;
247
- });
107
+ async verifyOtp(body) {
108
+ return this.executeRequest(() => this.client.POST("/auth/verify-otp", {
109
+ body: body,
110
+ }));
248
111
  }
249
112
  /**
250
113
  * Register with phone
@@ -252,23 +115,10 @@ class AuthClient extends client_1.StorefrontAPIClient {
252
115
  * @param options - Registration details
253
116
  * @returns Promise with user info and tokens
254
117
  */
255
- async registerWithPhone(options) {
256
- return this.executeWithTokenRefresh(async () => {
257
- const { data, error } = await this.client.POST("/auth/register/phone", {
258
- body: {
259
- ...options,
260
- country_code: options.country_code,
261
- },
262
- });
263
- if (error) {
264
- this.handleError(error);
265
- }
266
- if (data?.content?.access_token && data?.content?.refresh_token) {
267
- await this.setToken(data.content.access_token);
268
- await this.setRefreshToken(data.content.refresh_token);
269
- }
270
- return data?.content;
271
- });
118
+ async registerWithPhone(body) {
119
+ return this.executeRequest(() => this.client.POST("/auth/register/phone", {
120
+ body: body,
121
+ }));
272
122
  }
273
123
  /**
274
124
  * Register with email
@@ -276,35 +126,20 @@ class AuthClient extends client_1.StorefrontAPIClient {
276
126
  * @param options - Registration details
277
127
  * @returns Promise with user info and tokens
278
128
  */
279
- async registerWithEmail(options) {
280
- return this.executeWithTokenRefresh(async () => {
281
- const { data, error } = await this.client.POST("/auth/register/email", {
282
- body: options,
283
- });
284
- if (error) {
285
- this.handleError(error);
286
- }
287
- if (data?.content?.access_token && data?.content?.refresh_token) {
288
- await this.setToken(data.content.access_token);
289
- await this.setRefreshToken(data.content.refresh_token);
290
- }
291
- return data?.content;
292
- });
129
+ async registerWithEmail(body) {
130
+ return this.executeRequest(() => this.client.POST("/auth/register/email", {
131
+ body: body,
132
+ }));
293
133
  }
294
134
  /**
295
135
  * Refresh the access token using a refresh token
136
+ * @param refreshToken - The refresh token to use for refreshing the access token
137
+ * @returns Promise with the new access token and refresh token
296
138
  */
297
- async refreshToken(refreshToken) {
298
- const { data, error } = await this.client.POST("/auth/refresh-token", {
299
- body: { refresh_token: refreshToken },
300
- });
301
- if (error) {
302
- this.handleError(error);
303
- }
304
- const response = data?.content;
305
- // Store new tokens but don't update user ID as it hasn't changed
306
- await this.storeAuthData(response.access_token, response.refresh_token);
307
- return response;
139
+ async refreshToken(body) {
140
+ return this.executeRequest(() => this.client.POST("/auth/refresh-token", {
141
+ body: body,
142
+ }));
308
143
  }
309
144
  /**
310
145
  * Logout
@@ -312,445 +147,181 @@ class AuthClient extends client_1.StorefrontAPIClient {
312
147
  * @returns Promise that resolves when logout is complete
313
148
  */
314
149
  async logout() {
315
- return this.executeWithTokenRefresh(async () => {
316
- const { error } = await this.client.POST("/auth/logout");
317
- if (error) {
318
- this.handleError(error);
319
- }
320
- await this.clearToken();
321
- });
150
+ return this.executeRequest(() => this.client.POST("/auth/logout"));
322
151
  }
323
152
  /**
324
- * Override the base client's attemptTokenRefresh method
325
- * to implement token refresh for 401 errors
153
+ * Get user details
326
154
  *
327
- * @returns Promise that resolves to true if token was refreshed, false otherwise
155
+ * @param userId - User ID
156
+ * @returns Promise with user details
328
157
  */
329
- async attemptTokenRefresh() {
330
- const refreshToken = await this.tokenStorage.getItem("refresh_token");
331
- if (!refreshToken)
332
- return false;
333
- try {
334
- // Get current user data before refresh
335
- const userData = await this.getStoredUser();
336
- const tokens = await this.refreshToken(refreshToken);
337
- if (tokens.access_token) {
338
- await this.setToken(tokens.access_token);
339
- }
340
- if (tokens.refresh_token) {
341
- await this.setRefreshToken(tokens.refresh_token);
342
- }
343
- // Restore user data after refresh since it hasn't changed
344
- if (userData) {
345
- await this.tokenStorage.setItem("user_data", JSON.stringify(userData));
346
- }
347
- return true;
348
- }
349
- catch (error) {
350
- // If refresh fails, clear tokens
351
- await this.clearToken();
352
- return false;
353
- }
158
+ async getUserDetails(pathParams) {
159
+ return this.executeRequest(() => this.client.GET("/auth/user/{id}", {
160
+ params: {
161
+ path: pathParams,
162
+ },
163
+ }));
354
164
  }
355
165
  /**
356
- * Execute a request with automatic token refresh handling
357
- * This wraps any API call in logic that will catch authentication errors,
358
- * attempt to refresh the token, and retry the request once
166
+ * Update user details
359
167
  *
360
- * @param requestFn - Function that executes the API request
361
- * @returns Promise with the API response
168
+ * @param userId - User ID
169
+ * @returns Promise with user details
362
170
  */
363
- async executeWithTokenRefresh(requestFn) {
364
- try {
365
- // Attempt the request
366
- return await requestFn();
367
- }
368
- catch (error) {
369
- // If error message indicates token was refreshed, retry the request
370
- if (error instanceof Error &&
371
- error.message === "Token refreshed, please retry the request") {
372
- return await requestFn();
373
- }
374
- // Otherwise, re-throw the error
375
- throw error;
376
- }
377
- }
378
- }
379
- exports.AuthClient = AuthClient;
380
- /**
381
- * Default in-memory implementation of client storage
382
- */
383
- class MemoryTokenStorage {
384
- constructor() {
385
- this.accessToken = null;
386
- this.refreshToken = null;
387
- this.cartId = null;
388
- this.userData = null;
389
- }
390
- getItem(key) {
391
- if (key === "access_token")
392
- return Promise.resolve(this.accessToken);
393
- if (key === "refresh_token")
394
- return Promise.resolve(this.refreshToken);
395
- if (key === "cart_id")
396
- return Promise.resolve(this.cartId);
397
- if (key === "user_data")
398
- return Promise.resolve(this.userData);
399
- return Promise.resolve(null);
400
- }
401
- setItem(key, value) {
402
- if (key === "access_token")
403
- this.accessToken = value;
404
- if (key === "refresh_token")
405
- this.refreshToken = value;
406
- if (key === "cart_id")
407
- this.cartId = value;
408
- if (key === "user_data")
409
- this.userData = value;
410
- return Promise.resolve();
411
- }
412
- removeItem(key) {
413
- if (key === "access_token")
414
- this.accessToken = null;
415
- if (key === "refresh_token")
416
- this.refreshToken = null;
417
- if (key === "cart_id")
418
- this.cartId = null;
419
- if (key === "user_data")
420
- this.userData = null;
421
- return Promise.resolve();
422
- }
423
- getCartId() {
424
- return Promise.resolve(this.cartId);
425
- }
426
- setCartId(cartId) {
427
- this.cartId = cartId;
428
- return Promise.resolve();
429
- }
430
- clearCartId() {
431
- this.cartId = null;
432
- return Promise.resolve();
433
- }
434
- }
435
- exports.MemoryTokenStorage = MemoryTokenStorage;
436
- /**
437
- * Browser storage implementation using localStorage
438
- */
439
- class BrowserTokenStorage {
440
- constructor(prefix = "storefront_") {
441
- this.accessTokenKey = `${prefix}access_token`;
442
- this.refreshTokenKey = `${prefix}refresh_token`;
443
- this.cartIdKey = `${prefix}cart_id`;
444
- this.userDataKey = `${prefix}user_data`;
445
- }
446
- getItem(key) {
447
- if (key === "access_token")
448
- return Promise.resolve(localStorage.getItem(this.accessTokenKey));
449
- if (key === "refresh_token")
450
- return Promise.resolve(localStorage.getItem(this.refreshTokenKey));
451
- if (key === "cart_id")
452
- return Promise.resolve(localStorage.getItem(this.cartIdKey));
453
- if (key === "user_data")
454
- return Promise.resolve(localStorage.getItem(this.userDataKey));
455
- return Promise.resolve(null);
456
- }
457
- setItem(key, value) {
458
- if (key === "access_token")
459
- localStorage.setItem(this.accessTokenKey, value);
460
- if (key === "refresh_token")
461
- localStorage.setItem(this.refreshTokenKey, value);
462
- if (key === "cart_id")
463
- localStorage.setItem(this.cartIdKey, value);
464
- if (key === "user_data")
465
- localStorage.setItem(this.userDataKey, value);
466
- return Promise.resolve();
467
- }
468
- removeItem(key) {
469
- if (key === "access_token")
470
- localStorage.removeItem(this.accessTokenKey);
471
- if (key === "refresh_token")
472
- localStorage.removeItem(this.refreshTokenKey);
473
- if (key === "cart_id")
474
- localStorage.removeItem(this.cartIdKey);
475
- if (key === "user_data")
476
- localStorage.removeItem(this.userDataKey);
477
- return Promise.resolve();
478
- }
479
- getCartId() {
480
- return Promise.resolve(localStorage.getItem(this.cartIdKey));
481
- }
482
- setCartId(cartId) {
483
- localStorage.setItem(this.cartIdKey, cartId);
484
- return Promise.resolve();
485
- }
486
- clearCartId() {
487
- localStorage.removeItem(this.cartIdKey);
488
- return Promise.resolve();
489
- }
490
- }
491
- exports.BrowserTokenStorage = BrowserTokenStorage;
492
- /**
493
- * Cookie-based token storage for browser or server environments
494
- */
495
- class CookieTokenStorage {
496
- constructor(prefix = "storefront_", cookieOptions = {
497
- path: "/",
498
- secure: true,
499
- sameSite: "lax",
500
- httpOnly: true,
501
- maxAge: 60 * 60 * 24 * 30, // 30 days
502
- }) {
503
- this.accessTokenKey = `${prefix}access_token`;
504
- this.refreshTokenKey = `${prefix}refresh_token`;
505
- this.cartIdKey = `${prefix}cart_id`;
506
- this.userDataKey = `${prefix}user_data`;
507
- this.cookieOptions = cookieOptions;
171
+ async updateUserDetails(pathParams, body) {
172
+ return this.executeRequest(() => this.client.PUT("/auth/user/{id}", {
173
+ params: {
174
+ path: pathParams,
175
+ },
176
+ body: body,
177
+ }));
508
178
  }
509
179
  /**
510
- * Get value from cookies
511
- * Works in both browser and Next.js server components
180
+ * Add profile image
181
+ *
182
+ * @param userId - User ID
183
+ * @returns Promise with user details
512
184
  */
513
- getItem(key) {
514
- // Browser environment
515
- if (typeof document !== "undefined") {
516
- if (key === "access_token")
517
- return Promise.resolve(getCookieValue(this.accessTokenKey));
518
- if (key === "refresh_token")
519
- return Promise.resolve(getCookieValue(this.refreshTokenKey));
520
- if (key === "cart_id")
521
- return Promise.resolve(getCookieValue(this.cartIdKey));
522
- if (key === "user_data")
523
- return Promise.resolve(getCookieValue(this.userDataKey));
524
- }
525
- // Next.js server component - would need to be implemented by user
526
- return Promise.resolve(null);
185
+ async addProfileImage(pathParams, formData) {
186
+ return this.executeRequest(() => this.client.POST("/auth/user/{id}/profile-image", {
187
+ params: {
188
+ path: pathParams,
189
+ },
190
+ body: formData,
191
+ bodySerializer: (body) => {
192
+ const fd = new FormData();
193
+ for (const [key, value] of Object.entries(body)) {
194
+ if (value !== undefined && value !== null) {
195
+ fd.append(key, value);
196
+ }
197
+ }
198
+ return fd;
199
+ }
200
+ }));
527
201
  }
528
202
  /**
529
- * Set value in cookies
530
- * Works in browser environment
203
+ * Update profile image
204
+ *
205
+ * @param userId - User ID
206
+ * @returns Promise with user details
531
207
  */
532
- setItem(key, value) {
533
- // Browser environment
534
- if (typeof document !== "undefined") {
535
- if (key === "access_token")
536
- setCookie(this.accessTokenKey, value, this.cookieOptions);
537
- if (key === "refresh_token")
538
- setCookie(this.refreshTokenKey, value, this.cookieOptions);
539
- if (key === "cart_id")
540
- setCookie(this.cartIdKey, value, this.cookieOptions);
541
- if (key === "user_data")
542
- setCookie(this.userDataKey, value, this.cookieOptions);
543
- }
544
- // Next.js - would need to be implemented by user
545
- return Promise.resolve();
208
+ async updateProfileImage(pathParams, formData) {
209
+ return this.executeRequest(() => this.client.PUT("/auth/user/{id}/profile-image", {
210
+ params: {
211
+ path: pathParams,
212
+ },
213
+ body: formData,
214
+ bodySerializer: (body) => {
215
+ const fd = new FormData();
216
+ for (const [key, value] of Object.entries(body)) {
217
+ if (value !== undefined && value !== null) {
218
+ fd.append(key, value);
219
+ }
220
+ }
221
+ return fd;
222
+ }
223
+ }));
546
224
  }
547
225
  /**
548
- * Remove value from cookies
226
+ * Delete profile image
227
+ *
228
+ * @param userId - User ID
229
+ * @returns Promise with user details
549
230
  */
550
- removeItem(key) {
551
- // Browser environment
552
- if (typeof document !== "undefined") {
553
- if (key === "access_token")
554
- deleteCookie(this.accessTokenKey);
555
- if (key === "refresh_token")
556
- deleteCookie(this.refreshTokenKey);
557
- if (key === "cart_id")
558
- deleteCookie(this.cartIdKey);
559
- if (key === "user_data")
560
- deleteCookie(this.userDataKey);
561
- }
562
- // Next.js - would need to be implemented by user
563
- return Promise.resolve();
231
+ async deleteProfileImage(pathParams) {
232
+ return this.executeRequest(() => this.client.DELETE("/auth/user/{id}/profile-image", {
233
+ params: {
234
+ path: pathParams,
235
+ },
236
+ }));
564
237
  }
565
238
  /**
566
- * Get cart ID from cookies
239
+ * Get profile image
240
+ *
241
+ * @param userId - User ID
242
+ * @returns Promise with user details
567
243
  */
568
- getCartId() {
569
- return this.getItem(this.cartIdKey);
244
+ async getProfileImage(pathParams) {
245
+ return this.executeRequest(() => this.client.GET("/auth/user/{id}/profile-image", {
246
+ params: {
247
+ path: pathParams,
248
+ },
249
+ }));
570
250
  }
571
251
  /**
572
- * Set cart ID in cookies
252
+ * Deactivate user account
253
+ *
254
+ * @param userId - User ID
255
+ * @returns Promise with user details
573
256
  */
574
- setCartId(cartId) {
575
- return this.setItem(this.cartIdKey, cartId);
257
+ async deactivateUserAccount(pathParams) {
258
+ return this.executeRequest(() => this.client.PUT("/auth/user/{id}/deactivate", {
259
+ params: {
260
+ path: pathParams,
261
+ },
262
+ }));
576
263
  }
577
264
  /**
578
- * Clear cart ID from cookies
265
+ * Get user notification preferences
266
+ *
267
+ * @param userId - User ID
268
+ * @returns Promise with user details
579
269
  */
580
- clearCartId() {
581
- return this.removeItem(this.cartIdKey);
582
- }
583
- }
584
- exports.CookieTokenStorage = CookieTokenStorage;
585
- /**
586
- * Next.js specific cookie storage implementation
587
- * Works with the Next.js cookies API
588
- */
589
- class NextCookieTokenStorage {
590
- constructor(cookieStore, prefix = "storefront_") {
591
- this.accessTokenKey = `${prefix}access_token`;
592
- this.refreshTokenKey = `${prefix}refresh_token`;
593
- this.cartIdKey = `${prefix}cart_id`;
594
- this.userDataKey = `${prefix}user_data`;
595
- this.cookieStore = cookieStore;
596
- }
597
- getItem(key) {
598
- try {
599
- // Assuming cookieStore.get method exists (like in next/headers)
600
- let cookieKey = "";
601
- if (key === "access_token")
602
- cookieKey = this.accessTokenKey;
603
- if (key === "refresh_token")
604
- cookieKey = this.refreshTokenKey;
605
- if (key === "cart_id")
606
- cookieKey = this.cartIdKey;
607
- if (key === "user_data")
608
- cookieKey = this.userDataKey;
609
- if (!cookieKey)
610
- return Promise.resolve(null);
611
- const cookie = this.cookieStore.get(cookieKey);
612
- return cookie ? Promise.resolve(cookie.value) : Promise.resolve(null);
613
- }
614
- catch (error) {
615
- return Promise.resolve(null);
616
- }
617
- }
618
- setItem(key, value) {
619
- try {
620
- // Assuming cookieStore.set method exists
621
- let cookieKey = "";
622
- if (key === "access_token")
623
- cookieKey = this.accessTokenKey;
624
- if (key === "refresh_token")
625
- cookieKey = this.refreshTokenKey;
626
- if (key === "cart_id")
627
- cookieKey = this.cartIdKey;
628
- if (key === "user_data")
629
- cookieKey = this.userDataKey;
630
- if (!cookieKey)
631
- return Promise.resolve();
632
- this.cookieStore.set(cookieKey, value, {
633
- path: "/",
634
- secure: process.env.NODE_ENV === "production",
635
- httpOnly: true,
636
- sameSite: "strict",
637
- maxAge: 60 * 60 * 24 * 30, // 30 days
638
- });
639
- return Promise.resolve();
640
- }
641
- catch (error) {
642
- // Silently fail - might be in an environment where cookies can't be set
643
- return Promise.resolve();
644
- }
645
- }
646
- removeItem(key) {
647
- try {
648
- // Assuming cookieStore.delete method exists
649
- let cookieKey = "";
650
- if (key === "access_token")
651
- cookieKey = this.accessTokenKey;
652
- if (key === "refresh_token")
653
- cookieKey = this.refreshTokenKey;
654
- if (key === "cart_id")
655
- cookieKey = this.cartIdKey;
656
- if (key === "user_data")
657
- cookieKey = this.userDataKey;
658
- if (!cookieKey)
659
- return Promise.resolve();
660
- this.cookieStore.delete(cookieKey);
661
- return Promise.resolve();
662
- }
663
- catch (error) {
664
- // Silently fail
665
- return Promise.resolve();
666
- }
270
+ async getUserNotificationPreferences(pathParams) {
271
+ return this.executeRequest(() => this.client.GET("/auth/user/{id}/notification-preferences", {
272
+ params: {
273
+ path: pathParams,
274
+ },
275
+ }));
667
276
  }
668
277
  /**
669
- * Get cart ID from Next.js cookies
278
+ * Update user notification preferences
279
+ *
280
+ * @param userId - User ID
281
+ * @returns Promise with user details
670
282
  */
671
- getCartId() {
672
- return this.getItem(this.cartIdKey);
283
+ async updateUserNotificationPreferences(pathParams, body) {
284
+ return this.executeRequest(() => this.client.PUT("/auth/user/{id}/notification-preferences", {
285
+ params: {
286
+ path: pathParams,
287
+ },
288
+ body: body,
289
+ }));
673
290
  }
674
291
  /**
675
- * Set cart ID in Next.js cookies
292
+ * Create user notification preference
293
+ *
294
+ * @param userId - User ID
295
+ * @returns Promise with user details
676
296
  */
677
- setCartId(cartId) {
678
- return this.setItem(this.cartIdKey, cartId);
297
+ async createUserNotificationPreference(pathParams, body) {
298
+ return this.executeRequest(() => this.client.POST("/auth/user/{id}/notification-preferences", {
299
+ params: {
300
+ path: pathParams,
301
+ },
302
+ body: body,
303
+ }));
679
304
  }
680
305
  /**
681
- * Clear cart ID from Next.js cookies
306
+ * Generate OTP
307
+ *
308
+ * @param body - OTP generation body
309
+ * @returns Promise with OTP generation response
682
310
  */
683
- clearCartId() {
684
- return this.removeItem(this.cartIdKey);
685
- }
686
- }
687
- exports.NextCookieTokenStorage = NextCookieTokenStorage;
688
- /**
689
- * Helper function to get cookie value
690
- */
691
- function getCookieValue(name) {
692
- if (typeof document === "undefined")
693
- return null;
694
- const match = document.cookie.match(new RegExp("(^| )" + name + "=([^;]+)"));
695
- return match ? decodeURIComponent(match[2]) : null;
696
- }
697
- /**
698
- * Helper function to set cookie
699
- */
700
- function setCookie(name, value, options = {}) {
701
- if (typeof document === "undefined")
702
- return;
703
- const cookieOptions = {
704
- path: "/",
705
- ...options,
706
- };
707
- let cookie = `${name}=${encodeURIComponent(value)}`;
708
- if (cookieOptions.maxAge) {
709
- cookie += `; max-age=${cookieOptions.maxAge}`;
710
- }
711
- if (cookieOptions.domain) {
712
- cookie += `; domain=${cookieOptions.domain}`;
311
+ async generateOtp(body) {
312
+ return this.executeRequest(() => this.client.POST("/auth/generate-otp", {
313
+ body: body,
314
+ }));
713
315
  }
714
- if (cookieOptions.path) {
715
- cookie += `; path=${cookieOptions.path}`;
716
- }
717
- if (cookieOptions.secure) {
718
- cookie += "; secure";
719
- }
720
- if (cookieOptions.sameSite) {
721
- cookie += `; samesite=${cookieOptions.sameSite}`;
722
- }
723
- document.cookie = cookie;
724
- }
725
- /**
726
- * Helper function to delete cookie
727
- */
728
- function deleteCookie(name, path = "/") {
729
- if (typeof document === "undefined")
730
- return;
731
- document.cookie = `${name}=; path=${path}; expires=Thu, 01 Jan 1970 00:00:01 GMT`;
732
- }
733
- /**
734
- * Helper to create a token storage instance based on environment
735
- * Automatically selects the best storage method based on context
736
- */
737
- function createTokenStorage(options) {
738
- const prefix = options?.prefix || "storefront_";
739
- // Node.js environment without a cookieStore - use memory
740
- if (typeof window === "undefined" && !options?.cookieStore) {
741
- return new MemoryTokenStorage();
742
- }
743
- // Next.js server component with cookieStore
744
- if (typeof window === "undefined" && options?.cookieStore) {
745
- return new NextCookieTokenStorage(options.cookieStore, prefix);
746
- }
747
- // Browser environment - use localStorage by default unless cookies are specified
748
- if (typeof window !== "undefined") {
749
- if (options?.useLocalStorage === false) {
750
- return new CookieTokenStorage(prefix);
751
- }
752
- return new BrowserTokenStorage(prefix);
316
+ /**
317
+ * Check whether email or phone is already verified
318
+ *
319
+ * @param body - OTP generation body
320
+ * @returns Promise with OTP generation response
321
+ */
322
+ async checkEmailOrPhoneIsVerified(body) {
323
+ return this.executeRequest(() => this.client.POST("/auth/verified-email-phone", {
324
+ body: body,
325
+ }));
753
326
  }
754
- // Fallback to memory storage
755
- return new MemoryTokenStorage();
756
327
  }