@commercengine/storefront-sdk 0.1.0

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/README.md ADDED
@@ -0,0 +1,111 @@
1
+ # Storefront SDK
2
+
3
+ TypeScript SDK for the CommerceEngine Storefront API.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @commercengine/storefront-sdk
9
+ ```
10
+
11
+ Or with yarn:
12
+
13
+ ```bash
14
+ yarn add @commercengine/storefront-sdk
15
+ ```
16
+
17
+ Or with pnpm:
18
+
19
+ ```bash
20
+ pnpm add @commercengine/storefront-sdk
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ### Initializing the SDK
26
+
27
+ You can initialize the SDK in just a few lines:
28
+
29
+ ```typescript
30
+ import StorefrontSDK, { Environment } from "@commercengine/storefront-sdk";
31
+
32
+ // Initialize with environment and store ID
33
+ const sdk = new StorefrontSDK({
34
+ storeId: "your-store-id",
35
+ environment: Environment.Staging, // or Environment.Production
36
+ });
37
+
38
+ // Or with a custom base URL (if needed)
39
+ const customSdk = new StorefrontSDK({
40
+ storeId: "your-store-id",
41
+ baseUrl: "https://custom-api.example.com",
42
+ });
43
+ ```
44
+
45
+ ### Authentication
46
+
47
+ The SDK supports various authentication methods:
48
+
49
+ ```typescript
50
+ // Anonymous authentication
51
+ const { access_token, refresh_token, user } =
52
+ await sdk.auth.getAnonymousToken();
53
+
54
+ // Phone login
55
+ const { otp_token, otp_action } = await sdk.auth.loginWithPhone("9876543210");
56
+
57
+ // Email login
58
+ const { otp_token, otp_action } = await sdk.auth.loginWithEmail(
59
+ "user@example.com"
60
+ );
61
+
62
+ // Verify OTP
63
+ const { user, access_token, refresh_token } = await sdk.auth.verifyOtp(
64
+ "123456",
65
+ otp_token,
66
+ "login"
67
+ );
68
+
69
+ // Password login
70
+ const { user, access_token, refresh_token } = await sdk.auth.loginWithPassword({
71
+ email: "user@example.com",
72
+ password: "your-password",
73
+ });
74
+
75
+ // Registration
76
+ const { user, access_token, refresh_token } = await sdk.auth.registerWithPhone({
77
+ phone: "9876543210",
78
+ email: "user@example.com",
79
+ first_name: "John",
80
+ last_name: "Doe",
81
+ });
82
+
83
+ // Token management
84
+ sdk.setToken(access_token); // Set token for all clients
85
+ sdk.clearToken(); // Clear token from all clients
86
+ ```
87
+
88
+ ### Using the API Clients
89
+
90
+ The SDK provides dedicated clients for different API sections:
91
+
92
+ ```typescript
93
+ // Catalog client example (product listing)
94
+ const products = await sdk.catalog.listProducts();
95
+
96
+ // Cart client example (add to cart)
97
+ const cart = await sdk.cart.addToCart("product-id", 1);
98
+ ```
99
+
100
+ ## Advanced Configuration
101
+
102
+ You can configure timeout and other options:
103
+
104
+ ```typescript
105
+ const sdk = new StorefrontSDK({
106
+ storeId: "your-store-id",
107
+ environment: Environment.Production,
108
+ timeout: 5000, // 5 second timeout
109
+ token: "existing-token", // Initialize with an existing token
110
+ });
111
+ ```
@@ -0,0 +1,80 @@
1
+ import { StorefrontAPIClient, Environment } from "./lib/client";
2
+ import { CatalogClient } from "./lib/catalog";
3
+ import { CartClient } from "./lib/cart";
4
+ import { AuthClient } from "./lib/auth";
5
+ /**
6
+ * SDK initialization options
7
+ */
8
+ export interface StorefrontSDKOptions {
9
+ /**
10
+ * Store ID for the API requests
11
+ */
12
+ storeId: string;
13
+ /**
14
+ * Environment to use (defaults to Production)
15
+ */
16
+ environment?: Environment;
17
+ /**
18
+ * Custom base URL (overrides environment if provided)
19
+ */
20
+ baseUrl?: string;
21
+ /**
22
+ * Optional authentication token
23
+ */
24
+ token?: string;
25
+ /**
26
+ * X-Api-Key for anonymous authentication endpoints
27
+ * Required for initial authentication
28
+ */
29
+ apiKey?: string;
30
+ /**
31
+ * Optional timeout in milliseconds
32
+ */
33
+ timeout?: number;
34
+ }
35
+ /**
36
+ * Main SDK class for the Storefront API
37
+ */
38
+ export declare class StorefrontSDK {
39
+ /**
40
+ * Client for catalog-related endpoints (products, categories, etc.)
41
+ */
42
+ readonly catalog: CatalogClient;
43
+ /**
44
+ * Client for cart-related endpoints
45
+ */
46
+ readonly cart: CartClient;
47
+ /**
48
+ * Client for authentication-related endpoints
49
+ */
50
+ readonly auth: AuthClient;
51
+ /**
52
+ * Create a new StorefrontSDK instance
53
+ *
54
+ * @param options - Configuration options for the SDK
55
+ */
56
+ constructor(options: StorefrontSDKOptions);
57
+ /**
58
+ * Set the authentication token for all clients
59
+ *
60
+ * @param token - The authentication token
61
+ */
62
+ setToken(token: string): void;
63
+ /**
64
+ * Clear the authentication token from all clients
65
+ */
66
+ clearToken(): void;
67
+ /**
68
+ * Set the API key for all clients
69
+ *
70
+ * @param apiKey - The API key to set
71
+ */
72
+ setApiKey(apiKey: string): void;
73
+ /**
74
+ * Clear the API key from all clients
75
+ */
76
+ clearApiKey(): void;
77
+ }
78
+ export default StorefrontSDK;
79
+ export { StorefrontAPIClient, CatalogClient, CartClient, AuthClient };
80
+ export { Environment };
package/dist/index.js ADDED
@@ -0,0 +1,75 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Environment = exports.AuthClient = exports.CartClient = exports.CatalogClient = exports.StorefrontAPIClient = exports.StorefrontSDK = void 0;
4
+ const client_1 = require("./lib/client");
5
+ Object.defineProperty(exports, "StorefrontAPIClient", { enumerable: true, get: function () { return client_1.StorefrontAPIClient; } });
6
+ Object.defineProperty(exports, "Environment", { enumerable: true, get: function () { return client_1.Environment; } });
7
+ const catalog_1 = require("./lib/catalog");
8
+ Object.defineProperty(exports, "CatalogClient", { enumerable: true, get: function () { return catalog_1.CatalogClient; } });
9
+ const cart_1 = require("./lib/cart");
10
+ Object.defineProperty(exports, "CartClient", { enumerable: true, get: function () { return cart_1.CartClient; } });
11
+ const auth_1 = require("./lib/auth");
12
+ Object.defineProperty(exports, "AuthClient", { enumerable: true, get: function () { return auth_1.AuthClient; } });
13
+ /**
14
+ * Main SDK class for the Storefront API
15
+ */
16
+ class StorefrontSDK {
17
+ /**
18
+ * Create a new StorefrontSDK instance
19
+ *
20
+ * @param options - Configuration options for the SDK
21
+ */
22
+ constructor(options) {
23
+ // Convert options to internal config format
24
+ const config = {
25
+ storeId: options.storeId,
26
+ environment: options.environment,
27
+ baseUrl: options.baseUrl,
28
+ token: options.token,
29
+ apiKey: options.apiKey,
30
+ timeout: options.timeout,
31
+ };
32
+ this.catalog = new catalog_1.CatalogClient(config);
33
+ this.cart = new cart_1.CartClient(config);
34
+ this.auth = new auth_1.AuthClient(config);
35
+ }
36
+ /**
37
+ * Set the authentication token for all clients
38
+ *
39
+ * @param token - The authentication token
40
+ */
41
+ setToken(token) {
42
+ this.catalog.setToken(token);
43
+ this.cart.setToken(token);
44
+ this.auth.setToken(token);
45
+ }
46
+ /**
47
+ * Clear the authentication token from all clients
48
+ */
49
+ clearToken() {
50
+ this.catalog.clearToken();
51
+ this.cart.clearToken();
52
+ this.auth.clearToken();
53
+ }
54
+ /**
55
+ * Set the API key for all clients
56
+ *
57
+ * @param apiKey - The API key to set
58
+ */
59
+ setApiKey(apiKey) {
60
+ this.catalog.setApiKey(apiKey);
61
+ this.cart.setApiKey(apiKey);
62
+ this.auth.setApiKey(apiKey);
63
+ }
64
+ /**
65
+ * Clear the API key from all clients
66
+ */
67
+ clearApiKey() {
68
+ this.catalog.clearApiKey();
69
+ this.cart.clearApiKey();
70
+ this.auth.clearApiKey();
71
+ }
72
+ }
73
+ exports.StorefrontSDK = StorefrontSDK;
74
+ // Export the main SDK class
75
+ exports.default = StorefrontSDK;
@@ -0,0 +1,261 @@
1
+ import { StorefrontAPIClient, StorefrontAPIConfig } from "./client";
2
+ import type { components } from "../types/storefront";
3
+ /**
4
+ * Client for interacting with authentication endpoints
5
+ */
6
+ export declare class AuthClient extends StorefrontAPIClient {
7
+ private tokenStorage;
8
+ private autoRefreshTimer;
9
+ constructor(config: StorefrontAPIConfig, tokenStorage?: TokenStorage);
10
+ setToken(token: string): void;
11
+ protected setRefreshToken(token: string): void;
12
+ clearToken(): void;
13
+ private setupAutoRefresh;
14
+ private clearAutoRefresh;
15
+ private handleTokenRefresh;
16
+ private getTokenExpiry;
17
+ /**
18
+ * Get an anonymous user token
19
+ *
20
+ * @param options - Options for anonymous authentication
21
+ * @returns Promise with user info and tokens
22
+ */
23
+ getAnonymousToken(options?: {
24
+ apiKey?: string;
25
+ }): Promise<{
26
+ user: components["schemas"]["AnonymousUser"];
27
+ access_token: string;
28
+ refresh_token: string;
29
+ }>;
30
+ /**
31
+ * Login with phone number
32
+ *
33
+ * @param phoneNumber - Phone number (without country code)
34
+ * @param countryCode - Country code (defaults to +91)
35
+ * @param registerIfNotExists - Whether to register if user doesn't exist
36
+ * @returns Promise with OTP token and action
37
+ */
38
+ loginWithPhone(phoneNumber: string, countryCode?: string, registerIfNotExists?: boolean): Promise<{
39
+ otp_token: string;
40
+ otp_action: string;
41
+ }>;
42
+ /**
43
+ * Login with email
44
+ *
45
+ * @param email - Email address
46
+ * @param registerIfNotExists - Whether to register if user doesn't exist
47
+ * @returns Promise with OTP token and action
48
+ */
49
+ loginWithEmail(email: string, registerIfNotExists?: boolean): Promise<{
50
+ otp_token: string;
51
+ otp_action: string;
52
+ }>;
53
+ /**
54
+ * Login with password
55
+ *
56
+ * @param options - Login credentials
57
+ * @returns Promise with user info and tokens
58
+ */
59
+ loginWithPassword(options: {
60
+ email?: string;
61
+ phone?: string;
62
+ country_code?: string;
63
+ password: string;
64
+ }): Promise<{
65
+ user: components["schemas"]["User"];
66
+ access_token: string;
67
+ refresh_token: string;
68
+ }>;
69
+ /**
70
+ * Verify OTP
71
+ *
72
+ * @param otp - One-time password
73
+ * @param otpToken - OTP token from login request
74
+ * @param otpAction - OTP action from login request
75
+ * @returns Promise with user info and tokens
76
+ */
77
+ verifyOtp(otp: string, otpToken: string, otpAction: "login" | "register" | "reset-password" | "verify-phone" | "verify-email" | "update-phone" | "update-email"): Promise<{
78
+ user?: components["schemas"]["User"];
79
+ access_token?: string;
80
+ refresh_token?: string;
81
+ }>;
82
+ /**
83
+ * Register with phone
84
+ *
85
+ * @param options - Registration details
86
+ * @returns Promise with user info and tokens
87
+ */
88
+ registerWithPhone(options: {
89
+ country_code?: string;
90
+ phone: string;
91
+ first_name: string;
92
+ last_name?: string;
93
+ email: string;
94
+ otp_token?: string;
95
+ }): Promise<{
96
+ user: components["schemas"]["User"];
97
+ access_token: string;
98
+ refresh_token: string;
99
+ }>;
100
+ /**
101
+ * Register with email
102
+ *
103
+ * @param options - Registration details
104
+ * @returns Promise with user info and tokens
105
+ */
106
+ registerWithEmail(options: {
107
+ email: string;
108
+ first_name: string;
109
+ last_name?: string;
110
+ phone: string;
111
+ otp_token?: string;
112
+ }): Promise<{
113
+ user: components["schemas"]["User"];
114
+ access_token: string;
115
+ refresh_token: string;
116
+ }>;
117
+ /**
118
+ * Refresh token
119
+ *
120
+ * @param refreshToken - Refresh token
121
+ * @returns Promise with new tokens
122
+ */
123
+ refreshToken(refreshToken: string): Promise<{
124
+ access_token: string;
125
+ refresh_token: string;
126
+ }>;
127
+ /**
128
+ * Logout
129
+ *
130
+ * @returns Promise that resolves when logout is complete
131
+ */
132
+ logout(): Promise<void>;
133
+ /**
134
+ * Override the base client's attemptTokenRefresh method
135
+ * to implement token refresh for 401 errors
136
+ *
137
+ * @returns Promise that resolves to true if token was refreshed, false otherwise
138
+ */
139
+ protected attemptTokenRefresh(): Promise<boolean>;
140
+ /**
141
+ * Execute a request with automatic token refresh handling
142
+ * This wraps any API call in logic that will catch authentication errors,
143
+ * attempt to refresh the token, and retry the request once
144
+ *
145
+ * @param requestFn - Function that executes the API request
146
+ * @returns Promise with the API response
147
+ */
148
+ executeWithTokenRefresh<T>(requestFn: () => Promise<T>): Promise<T>;
149
+ }
150
+ /**
151
+ * Interface for token storage implementations
152
+ */
153
+ export interface TokenStorage {
154
+ getAccessToken(): string | null;
155
+ setAccessToken(token: string): void;
156
+ getRefreshToken(): string | null;
157
+ setRefreshToken(token: string): void;
158
+ clearTokens(): void;
159
+ }
160
+ /**
161
+ * Default in-memory implementation of token storage
162
+ */
163
+ export declare class MemoryTokenStorage implements TokenStorage {
164
+ private accessToken;
165
+ private refreshToken;
166
+ getAccessToken(): string | null;
167
+ setAccessToken(token: string): void;
168
+ getRefreshToken(): string | null;
169
+ setRefreshToken(token: string): void;
170
+ clearTokens(): void;
171
+ }
172
+ /**
173
+ * Browser storage implementation using localStorage
174
+ */
175
+ export declare class BrowserTokenStorage implements TokenStorage {
176
+ private accessTokenKey;
177
+ private refreshTokenKey;
178
+ constructor(prefix?: string);
179
+ getAccessToken(): string | null;
180
+ setAccessToken(token: string): void;
181
+ getRefreshToken(): string | null;
182
+ setRefreshToken(token: string): void;
183
+ clearTokens(): void;
184
+ }
185
+ /**
186
+ * Cookie-based token storage for browser or server environments
187
+ */
188
+ export declare class CookieTokenStorage implements TokenStorage {
189
+ private accessTokenKey;
190
+ private refreshTokenKey;
191
+ private cookieOptions;
192
+ constructor(prefix?: string, cookieOptions?: {
193
+ path: string;
194
+ secure: boolean;
195
+ sameSite: string;
196
+ maxAge: number;
197
+ });
198
+ /**
199
+ * Get access token from cookies
200
+ * Works in both browser and Next.js server components
201
+ */
202
+ getAccessToken(): string | null;
203
+ /**
204
+ * Set access token in cookies
205
+ * Works in browser environment
206
+ */
207
+ setAccessToken(token: string): void;
208
+ /**
209
+ * Get refresh token from cookies
210
+ * Works in both browser and Next.js server components
211
+ */
212
+ getRefreshToken(): string | null;
213
+ /**
214
+ * Set refresh token in cookies
215
+ * Works in browser environment
216
+ */
217
+ setRefreshToken(token: string): void;
218
+ /**
219
+ * Clear all tokens from cookies
220
+ */
221
+ clearTokens(): void;
222
+ }
223
+ /**
224
+ * Next.js specific cookie storage implementation
225
+ * Works with the Next.js cookies API
226
+ */
227
+ export declare class NextCookieTokenStorage implements TokenStorage {
228
+ private accessTokenKey;
229
+ private refreshTokenKey;
230
+ private cookieStore;
231
+ constructor(cookieStore: any, prefix?: string);
232
+ /**
233
+ * Get access token from Next.js cookies
234
+ */
235
+ getAccessToken(): string | null;
236
+ /**
237
+ * Set access token in Next.js cookies
238
+ */
239
+ setAccessToken(token: string): void;
240
+ /**
241
+ * Get refresh token from Next.js cookies
242
+ */
243
+ getRefreshToken(): string | null;
244
+ /**
245
+ * Set refresh token in Next.js cookies
246
+ */
247
+ setRefreshToken(token: string): void;
248
+ /**
249
+ * Clear all tokens from Next.js cookies
250
+ */
251
+ clearTokens(): void;
252
+ }
253
+ /**
254
+ * Helper to create a token storage instance based on environment
255
+ * Automatically selects the best storage method based on context
256
+ */
257
+ export declare function createTokenStorage(options?: {
258
+ prefix?: string;
259
+ cookieStore?: any;
260
+ useLocalStorage?: boolean;
261
+ }): TokenStorage;