@commercengine/storefront-sdk 0.3.11 → 0.4.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.
@@ -1,66 +0,0 @@
1
- /**
2
- * Mapping of SDK header parameter names to actual HTTP header names
3
- * Only include headers that need transformation - others pass through as-is
4
- */
5
- const HEADER_TRANSFORMATIONS = {
6
- customer_group_id: "x-customer-group-id",
7
- // Future transformations can be added here:
8
- // some_param: "X-Some-Header",
9
- // another_param: "X-Another-Header",
10
- };
11
- /**
12
- * Transform SDK header parameters to actual HTTP header names
13
- * Headers not in the transformation map are passed through unchanged
14
- *
15
- * @param headers - Headers object with SDK parameter names
16
- * @returns Headers object with actual HTTP header names
17
- */
18
- export function transformHeaders(headers) {
19
- const transformed = {};
20
- // Iterate through all headers in the input
21
- for (const [key, value] of Object.entries(headers)) {
22
- if (value !== undefined) {
23
- // Use transformation if available, otherwise use the original key
24
- const headerName = HEADER_TRANSFORMATIONS[key] || key;
25
- transformed[headerName] = value;
26
- }
27
- }
28
- return transformed;
29
- }
30
- /**
31
- * Merge default headers with method-level headers
32
- * Method-level headers take precedence over default headers
33
- * Automatically transforms SDK parameter names to HTTP header names
34
- *
35
- * @param defaultHeaders - Default headers from SDK configuration
36
- * @param methodHeaders - Headers passed to the specific method call
37
- * @returns Merged headers object with proper HTTP header names
38
- */
39
- export function mergeHeaders(defaultHeaders, methodHeaders) {
40
- const merged = {};
41
- // Transform and add default headers if they exist
42
- if (defaultHeaders) {
43
- const transformedDefaults = transformHeaders(defaultHeaders);
44
- Object.assign(merged, transformedDefaults);
45
- }
46
- // Method headers override default headers
47
- if (methodHeaders) {
48
- Object.assign(merged, methodHeaders);
49
- }
50
- // Remove undefined values
51
- Object.keys(merged).forEach((key) => {
52
- if (merged[key] === undefined) {
53
- delete merged[key];
54
- }
55
- });
56
- return merged;
57
- }
58
- /**
59
- * Get the list of supported header transformations
60
- * Useful for debugging or documentation purposes
61
- *
62
- * @returns Copy of the header transformations mapping
63
- */
64
- export function getHeaderTransformations() {
65
- return { ...HEADER_TRANSFORMATIONS };
66
- }
@@ -1,27 +0,0 @@
1
- import type { ApiResult, ListCountriesContent, ListCountryPincodesContent, ListCountryPincodesPathParams, ListCountryStatesContent, ListCountryStatesPathParams } from "../types/storefront-api-types";
2
- import { StorefrontAPIClient } from "./client";
3
- /**
4
- * Client for interacting with helper endpoints
5
- */
6
- export declare class HelpersClient extends StorefrontAPIClient {
7
- /**
8
- * Get a list of countries
9
- *
10
- * @returns Promise with countries
11
- */
12
- listCountries(): Promise<ApiResult<ListCountriesContent>>;
13
- /**
14
- * - Get a list of states for a country
15
- *
16
- * @param pathParams - Path parameters
17
- * @returns Promise with states
18
- */
19
- listCountryStates(pathParams: ListCountryStatesPathParams): Promise<ApiResult<ListCountryStatesContent>>;
20
- /**
21
- * Get pincodes for a country
22
- *
23
- * @param pathParams - Path parameters
24
- * @returns Promise with pincodes
25
- */
26
- listCountryPincodes(pathParams: ListCountryPincodesPathParams): Promise<ApiResult<ListCountryPincodesContent>>;
27
- }
@@ -1,40 +0,0 @@
1
- import { StorefrontAPIClient } from "./client";
2
- /**
3
- * Client for interacting with helper endpoints
4
- */
5
- export class HelpersClient extends StorefrontAPIClient {
6
- /**
7
- * Get a list of countries
8
- *
9
- * @returns Promise with countries
10
- */
11
- async listCountries() {
12
- return this.executeRequest(() => this.client.GET("/common/countries", {}));
13
- }
14
- /**
15
- * - Get a list of states for a country
16
- *
17
- * @param pathParams - Path parameters
18
- * @returns Promise with states
19
- */
20
- async listCountryStates(pathParams) {
21
- return this.executeRequest(() => this.client.GET("/common/countries/{country_iso_code}/states", {
22
- params: {
23
- path: pathParams,
24
- },
25
- }));
26
- }
27
- /**
28
- * Get pincodes for a country
29
- *
30
- * @param pathParams - Path parameters
31
- * @returns Promise with pincodes
32
- */
33
- async listCountryPincodes(pathParams) {
34
- return this.executeRequest(() => this.client.GET("/common/countries/{country_iso_code}/pincodes", {
35
- params: {
36
- path: pathParams,
37
- },
38
- }));
39
- }
40
- }
@@ -1,75 +0,0 @@
1
- /**
2
- * JWT payload structure for storefront tokens
3
- */
4
- export interface JwtPayload {
5
- token_type: string;
6
- exp: number;
7
- iat: number;
8
- jti: string;
9
- ulid: string;
10
- email: string | null;
11
- phone: string | null;
12
- username: string;
13
- first_name: string | null;
14
- last_name: string | null;
15
- store_id: string;
16
- is_logged_in: boolean;
17
- customer_id: string | null;
18
- customer_group_id: string | null;
19
- anonymous_id: string;
20
- }
21
- /**
22
- * User information extracted from JWT token
23
- */
24
- export interface UserInfo {
25
- id: string;
26
- email: string | null;
27
- phone: string | null;
28
- username: string;
29
- firstName: string | null;
30
- lastName: string | null;
31
- storeId: string;
32
- isLoggedIn: boolean;
33
- isAnonymous: boolean;
34
- customerId: string | null;
35
- customerGroupId: string | null;
36
- anonymousId: string;
37
- tokenExpiry: Date;
38
- tokenIssuedAt: Date;
39
- }
40
- /**
41
- * Decode and extract user information from a JWT token
42
- *
43
- * @param token - The JWT token to decode
44
- * @returns User information or null if token is invalid
45
- */
46
- export declare function extractUserInfoFromToken(token: string): UserInfo | null;
47
- /**
48
- * Check if a JWT token is expired
49
- *
50
- * @param token - The JWT token to check
51
- * @param bufferSeconds - Buffer time in seconds (default: 30)
52
- * @returns True if token is expired or will expire within buffer time
53
- */
54
- export declare function isTokenExpired(token: string, bufferSeconds?: number): boolean;
55
- /**
56
- * Get the user ID from a JWT token
57
- *
58
- * @param token - The JWT token
59
- * @returns User ID (ulid) or null if token is invalid
60
- */
61
- export declare function getUserIdFromToken(token: string): string | null;
62
- /**
63
- * Check if user is logged in based on JWT token
64
- *
65
- * @param token - The JWT token
66
- * @returns True if user is logged in, false otherwise
67
- */
68
- export declare function isUserLoggedIn(token: string): boolean;
69
- /**
70
- * Check if user is anonymous based on JWT token
71
- *
72
- * @param token - The JWT token
73
- * @returns True if user is anonymous, false otherwise
74
- */
75
- export declare function isUserAnonymous(token: string): boolean;
@@ -1,84 +0,0 @@
1
- import { decodeJwt } from "jose";
2
- /**
3
- * Decode and extract user information from a JWT token
4
- *
5
- * @param token - The JWT token to decode
6
- * @returns User information or null if token is invalid
7
- */
8
- export function extractUserInfoFromToken(token) {
9
- try {
10
- const payload = decodeJwt(token);
11
- return {
12
- id: payload.ulid,
13
- email: payload.email,
14
- phone: payload.phone,
15
- username: payload.username,
16
- firstName: payload.first_name,
17
- lastName: payload.last_name,
18
- storeId: payload.store_id,
19
- isLoggedIn: payload.is_logged_in,
20
- isAnonymous: !payload.is_logged_in,
21
- customerId: payload.customer_id,
22
- customerGroupId: payload.customer_group_id,
23
- anonymousId: payload.anonymous_id,
24
- tokenExpiry: new Date(payload.exp * 1000),
25
- tokenIssuedAt: new Date(payload.iat * 1000),
26
- };
27
- }
28
- catch (error) {
29
- console.warn("Failed to decode JWT token:", error);
30
- return null;
31
- }
32
- }
33
- /**
34
- * Check if a JWT token is expired
35
- *
36
- * @param token - The JWT token to check
37
- * @param bufferSeconds - Buffer time in seconds (default: 30)
38
- * @returns True if token is expired or will expire within buffer time
39
- */
40
- export function isTokenExpired(token, bufferSeconds = 30) {
41
- try {
42
- const payload = decodeJwt(token);
43
- if (!payload.exp)
44
- return true;
45
- const currentTime = Math.floor(Date.now() / 1000);
46
- const expiryTime = payload.exp;
47
- // Consider token expired if it expires within the buffer time
48
- return currentTime >= (expiryTime - bufferSeconds);
49
- }
50
- catch (error) {
51
- console.warn("Failed to decode JWT token:", error);
52
- return true; // Treat invalid tokens as expired
53
- }
54
- }
55
- /**
56
- * Get the user ID from a JWT token
57
- *
58
- * @param token - The JWT token
59
- * @returns User ID (ulid) or null if token is invalid
60
- */
61
- export function getUserIdFromToken(token) {
62
- const userInfo = extractUserInfoFromToken(token);
63
- return userInfo?.id || null;
64
- }
65
- /**
66
- * Check if user is logged in based on JWT token
67
- *
68
- * @param token - The JWT token
69
- * @returns True if user is logged in, false otherwise
70
- */
71
- export function isUserLoggedIn(token) {
72
- const userInfo = extractUserInfoFromToken(token);
73
- return userInfo?.isLoggedIn || false;
74
- }
75
- /**
76
- * Check if user is anonymous based on JWT token
77
- *
78
- * @param token - The JWT token
79
- * @returns True if user is anonymous, false otherwise
80
- */
81
- export function isUserAnonymous(token) {
82
- const userInfo = extractUserInfoFromToken(token);
83
- return userInfo?.isAnonymous || true;
84
- }
@@ -1,88 +0,0 @@
1
- import type { Middleware } from "openapi-fetch";
2
- /**
3
- * Debug logger function interface
4
- */
5
- export interface DebugLoggerFn {
6
- (level: "info" | "warn" | "error", message: string, data?: any): void;
7
- }
8
- /**
9
- * Response utilities for debugging and working with Response objects
10
- */
11
- export declare class ResponseUtils {
12
- /**
13
- * Get response headers as a plain object
14
- */
15
- static getHeaders(response: Response): Record<string, string>;
16
- /**
17
- * Get specific header value
18
- */
19
- static getHeader(response: Response, name: string): string | null;
20
- /**
21
- * Check if response was successful
22
- */
23
- static isSuccess(response: Response): boolean;
24
- /**
25
- * Get response metadata
26
- */
27
- static getMetadata(response: Response): {
28
- status: number;
29
- statusText: string;
30
- ok: boolean;
31
- url: string;
32
- redirected: boolean;
33
- type: ResponseType;
34
- headers: {
35
- [k: string]: string;
36
- };
37
- };
38
- /**
39
- * Clone and read response as text (useful for debugging)
40
- * Note: This can only be called once per response
41
- */
42
- static getText(response: Response): Promise<string>;
43
- /**
44
- * Clone and read response as JSON (useful for debugging)
45
- * Note: This can only be called once per response
46
- */
47
- static getJSON(response: Response): Promise<any>;
48
- /**
49
- * Format response information for debugging
50
- */
51
- static format(response: Response): string;
52
- }
53
- /**
54
- * Debug logging utilities
55
- */
56
- export declare class DebugLogger {
57
- private logger;
58
- private responseTextCache;
59
- constructor(logger?: DebugLoggerFn);
60
- /**
61
- * Log debug information about API request
62
- */
63
- logRequest(request: Request, requestBody?: any): void;
64
- /**
65
- * Log debug information about API response
66
- */
67
- logResponse(response: Response, responseBody?: any): Promise<void>;
68
- /**
69
- * Log error information
70
- */
71
- logError(message: string, error: any): void;
72
- /**
73
- * Get cached response text for a URL (if available)
74
- */
75
- getCachedResponseText(url: string): string | null;
76
- /**
77
- * Clear cached response texts
78
- */
79
- clearCache(): void;
80
- }
81
- /**
82
- * Extract request body for logging
83
- */
84
- export declare function extractRequestBody(request: Request): Promise<any>;
85
- /**
86
- * Create debug middleware for openapi-fetch (internal use)
87
- */
88
- export declare function createDebugMiddleware(logger?: DebugLoggerFn): Middleware;
@@ -1,211 +0,0 @@
1
- /**
2
- * Response utilities for debugging and working with Response objects
3
- */
4
- export class ResponseUtils {
5
- /**
6
- * Get response headers as a plain object
7
- */
8
- static getHeaders(response) {
9
- return Object.fromEntries(response.headers.entries());
10
- }
11
- /**
12
- * Get specific header value
13
- */
14
- static getHeader(response, name) {
15
- return response.headers.get(name);
16
- }
17
- /**
18
- * Check if response was successful
19
- */
20
- static isSuccess(response) {
21
- return response.ok;
22
- }
23
- /**
24
- * Get response metadata
25
- */
26
- static getMetadata(response) {
27
- return {
28
- status: response.status,
29
- statusText: response.statusText,
30
- ok: response.ok,
31
- url: response.url,
32
- redirected: response.redirected,
33
- type: response.type,
34
- headers: Object.fromEntries(response.headers.entries()),
35
- };
36
- }
37
- /**
38
- * Clone and read response as text (useful for debugging)
39
- * Note: This can only be called once per response
40
- */
41
- static async getText(response) {
42
- const cloned = response.clone();
43
- return await cloned.text();
44
- }
45
- /**
46
- * Clone and read response as JSON (useful for debugging)
47
- * Note: This can only be called once per response
48
- */
49
- static async getJSON(response) {
50
- const cloned = response.clone();
51
- return await cloned.json();
52
- }
53
- /**
54
- * Format response information for debugging
55
- */
56
- static format(response) {
57
- const metadata = this.getMetadata(response);
58
- return `${metadata.status} ${metadata.statusText} - ${metadata.url}`;
59
- }
60
- }
61
- /**
62
- * Debug logging utilities
63
- */
64
- export class DebugLogger {
65
- logger;
66
- responseTextCache = new Map();
67
- constructor(logger) {
68
- this.logger =
69
- logger ||
70
- ((level, message, data) => {
71
- console.log(`[${level.toUpperCase()}]`, message);
72
- if (data)
73
- console.log(data);
74
- });
75
- }
76
- /**
77
- * Log debug information about API request
78
- */
79
- logRequest(request, requestBody) {
80
- this.logger("info", "API Request Debug Info", {
81
- method: request.method,
82
- url: request.url,
83
- headers: Object.fromEntries(request.headers.entries()),
84
- body: requestBody,
85
- timestamp: new Date().toISOString(),
86
- });
87
- }
88
- /**
89
- * Log debug information about API response
90
- */
91
- async logResponse(response, responseBody) {
92
- // Cache response text for later use by ResponseUtils
93
- if (responseBody && typeof responseBody === "string") {
94
- this.responseTextCache.set(response.url, responseBody);
95
- }
96
- // Log response metadata
97
- this.logger("info", "API Response Debug Info", {
98
- url: response.url,
99
- status: response.status,
100
- statusText: response.statusText,
101
- ok: response.ok,
102
- headers: Object.fromEntries(response.headers.entries()),
103
- redirected: response.redirected,
104
- type: response.type,
105
- timestamp: new Date().toISOString(),
106
- });
107
- // Log response body if available
108
- if (responseBody) {
109
- this.logger("info", "API Response Data", {
110
- data: responseBody,
111
- contentType: response.headers.get("content-type"),
112
- contentLength: response.headers.get("content-length"),
113
- });
114
- }
115
- }
116
- /**
117
- * Log error information
118
- */
119
- logError(message, error) {
120
- this.logger("error", message, error);
121
- }
122
- /**
123
- * Get cached response text for a URL (if available)
124
- */
125
- getCachedResponseText(url) {
126
- return this.responseTextCache.get(url) || null;
127
- }
128
- /**
129
- * Clear cached response texts
130
- */
131
- clearCache() {
132
- this.responseTextCache.clear();
133
- }
134
- }
135
- /**
136
- * Extract request body for logging
137
- */
138
- export async function extractRequestBody(request) {
139
- if (request.method === "GET" || request.method === "HEAD") {
140
- return null;
141
- }
142
- try {
143
- const clonedRequest = request.clone();
144
- const contentType = request.headers.get("content-type")?.toLowerCase();
145
- if (contentType?.startsWith("application/json")) {
146
- return await clonedRequest.json();
147
- }
148
- else if (contentType?.startsWith("multipart/form-data")) {
149
- return "[FormData - cannot display]";
150
- }
151
- else if (contentType?.startsWith("text/")) {
152
- return await clonedRequest.text();
153
- }
154
- return "[Request body - unknown format]";
155
- }
156
- catch (error) {
157
- return "[Request body unavailable]";
158
- }
159
- }
160
- /**
161
- * Create debug middleware for openapi-fetch (internal use)
162
- */
163
- export function createDebugMiddleware(logger) {
164
- const debugLogger = new DebugLogger(logger);
165
- return {
166
- async onRequest({ request }) {
167
- // Log request information
168
- const requestBody = await extractRequestBody(request);
169
- debugLogger.logRequest(request, requestBody);
170
- return request;
171
- },
172
- async onResponse({ response }) {
173
- // Clone response to read body without consuming it
174
- const cloned = response.clone();
175
- let responseBody = null;
176
- try {
177
- const contentType = response.headers.get("content-type")?.toLowerCase();
178
- if (contentType?.startsWith("application/json")) {
179
- responseBody = await cloned.json();
180
- }
181
- else if (contentType?.startsWith("text/")) {
182
- responseBody = await cloned.text();
183
- }
184
- }
185
- catch (error) {
186
- // Ignore body reading errors
187
- }
188
- // Log response information
189
- await debugLogger.logResponse(response, responseBody);
190
- return response;
191
- },
192
- async onError({ error, request }) {
193
- // Log error information with request context
194
- debugLogger.logError("API Request Failed", {
195
- error: {
196
- name: error instanceof Error ? error.name : "Unknown",
197
- message: error instanceof Error ? error.message : String(error),
198
- stack: error instanceof Error ? error.stack : undefined,
199
- },
200
- request: {
201
- method: request.method,
202
- url: request.url,
203
- headers: Object.fromEntries(request.headers.entries()),
204
- },
205
- timestamp: new Date().toISOString(),
206
- });
207
- // Re-throw the error to maintain normal error handling
208
- throw error;
209
- },
210
- };
211
- }