|
1
|
import { events } from "fetch-event-stream" |
|
2
|
import { stringify } from "qs" |
|
3
|
import { |
|
4
|
ClientFetch, |
|
5
|
Config, |
|
6
|
FetchArgs, |
|
7
|
FetchInput, |
|
8
|
FetchStreamResponse, |
|
9
|
Logger, |
|
10
|
} from "./types.js" |
|
11
|
|
|
12
|
/** |
|
13
|
* The header name used for the publishable API key. |
|
14
|
*/ |
|
15
|
export const PUBLISHABLE_KEY_HEADER = "x-publishable-api-key" |
|
16
|
/** |
|
17
|
* The storage key used for storing the locale in localStorage. |
|
18
|
*/ |
|
19
|
export const LOCALE_STORAGE_KEY = "medusa_locale" |
|
20
|
|
|
21
|
// We want to explicitly retrieve the base URL instead of relying on relative paths that differ in behavior between browsers. |
|
22
|
const getBaseUrl = (passedBaseUrl: string) => { |
|
23
|
if (typeof window === "undefined") { |
|
24
|
return passedBaseUrl |
|
25
|
} |
|
26
|
|
|
27
|
// If the passed base URL is empty or "/", we use the current origin from the browser. |
|
28
|
if (passedBaseUrl === "" || passedBaseUrl === "/") { |
|
29
|
return window.location.origin |
|
30
|
} |
|
31
|
|
|
32
|
return passedBaseUrl |
|
33
|
} |
|
34
|
|
|
35
|
const hasStorage = (storage: "localStorage" | "sessionStorage") => { |
|
36
|
if (typeof window === "undefined") { |
|
37
|
return false |
|
38
|
} |
|
39
|
|
|
40
|
try { |
|
41
|
const value = window[storage] |
|
42
|
|
|
43
|
return Boolean( |
|
44
|
value && |
|
45
|
typeof value.getItem === "function" && |
|
46
|
typeof value.setItem === "function" |
|
47
|
) |
|
48
|
} catch { |
|
49
|
return false |
|
50
|
} |
|
51
|
} |
|
52
|
|
|
53
|
const toBase64 = (str: string) => { |
|
54
|
if (typeof window !== "undefined") { |
|
55
|
return window.btoa(str) |
|
56
|
} |
|
57
|
|
|
58
|
return Buffer.from(str).toString("base64") |
|
59
|
} |
|
60
|
|
|
61
|
const sanitizeHeaders = (headers: Headers) => { |
|
62
|
return { |
|
63
|
...Object.fromEntries(headers.entries()), |
|
64
|
authorization: "<REDACTED>", |
|
65
|
} |
|
66
|
} |
|
67
|
|
|
68
|
const normalizeRequest = ( |
|
69
|
init: FetchArgs | undefined, |
|
70
|
headers: Headers, |
|
71
|
config: Config |
|
72
|
): RequestInit | undefined => { |
|
73
|
let body = init?.body |
|
74
|
if (body && headers.get("content-type")?.includes("application/json")) { |
|
75
|
body = JSON.stringify(body) |
|
76
|
} |
|
77
|
|
|
78
|
// "credentials" is not supported in some environments (eg. on the backend), and it might throw an exception if the field is set. |
|
79
|
const isFetchCredentialsSupported = "credentials" in Request.prototype |
|
80
|
|
|
81
|
// Oftentimes the server will be on a different origin, so we want to default to include |
|
82
|
// Note that the cookie's SameSite attribute takes precedence over this setting. |
|
83
|
const credentials = |
|
84
|
config.auth?.type === "session" |
|
85
|
? config.auth?.fetchCredentials || "include" |
|
86
|
: "omit" |
|
87
|
|
|
88
|
return { |
|
89
|
...init, |
|
90
|
headers, |
|
91
|
credentials: isFetchCredentialsSupported ? credentials : undefined, |
|
92
|
...(body ? { body: body as RequestInit["body"] } : {}), |
|
93
|
} as RequestInit |
|
94
|
} |
|
95
|
|
|
96
|
const normalizeResponse = async (resp: Response, reqHeaders: Headers) => { |
|
97
|
if (resp.status >= 300) { |
|
98
|
const jsonError = (await resp.json().catch(() => ({}))) as { |
|
99
|
message?: string |
|
100
|
} |
|
101
|
throw new FetchError( |
|
102
|
jsonError.message ?? resp.statusText, |
|
103
|
resp.statusText, |
|
104
|
resp.status |
|
105
|
) |
|
106
|
} |
|
107
|
|
|
108
|
// If we requested JSON, we try to parse the response. Otherwise, we return the raw response. |
|
109
|
const isJsonRequest = reqHeaders.get("accept")?.includes("application/json") |
|
110
|
return isJsonRequest ? await resp.json() : resp |
|
111
|
} |
|
112
|
|
|
113
|
/** |
|
114
|
* Error class for HTTP fetch operations that includes status information. |
|
115
|
*/ |
|
116
|
export class FetchError extends Error { |
|
117
|
status: number | undefined |
|
118
|
statusText: string | undefined |
|
119
|
|
|
120
|
constructor(message: string, statusText?: string, status?: number) { |
|
121
|
super(message) |
|
122
|
this.statusText = statusText |
|
123
|
this.status = status |
|
124
|
} |
|
125
|
} |
|
126
|
|
|
127
|
/** |
|
128
|
* The main HTTP client for the Medusa JS SDK. |
|
129
|
*/ |
|
130
|
export class Client { |
|
131
|
public fetch_: ClientFetch |
|
132
|
private config: Config |
|
133
|
private logger: Logger |
|
134
|
|
|
135
|
private DEFAULT_JWT_STORAGE_KEY = "medusa_auth_token" |
|
136
|
private token = "" |
|
137
|
|
|
138
|
private locale_ = "" |
|
139
|
|
|
140
|
get locale() { |
|
141
|
if (hasStorage("localStorage")) { |
|
142
|
const storedLocale = window.localStorage.getItem(LOCALE_STORAGE_KEY) |
|
143
|
if (storedLocale) { |
|
144
|
return storedLocale |
|
145
|
} |
|
146
|
} |
|
147
|
return this.locale_ |
|
148
|
} |
|
149
|
|
|
150
|
constructor(config: Config) { |
|
151
|
this.config = { ...config, baseUrl: getBaseUrl(config.baseUrl) } |
|
152
|
const logger = config.logger || { |
|
153
|
error: console.error, |
|
154
|
warn: console.warn, |
|
155
|
info: console.info, |
|
156
|
debug: console.debug, |
|
157
|
} |
|
158
|
|
|
159
|
this.logger = { |
|
160
|
...logger, |
|
161
|
debug: config.debug ? logger.debug : () => {}, |
|
162
|
} |
|
163
|
|
|
164
|
if (hasStorage("localStorage")) { |
|
165
|
this.locale_ = window.localStorage.getItem(LOCALE_STORAGE_KEY) || "" |
|
166
|
} |
|
167
|
|
|
168
|
this.fetch_ = this.initClient() |
|
169
|
} |
|
170
|
|
|
171
|
setLocale(locale: string) { |
|
172
|
if (typeof window === "undefined") { |
|
173
|
this.logger.warn( |
|
174
|
"setLocale is not available in the server environment. Please set the locale directly through the 'x-medusa-locale' header." |
|
175
|
) |
|
176
|
return |
|
177
|
} |
|
178
|
|
|
179
|
if (hasStorage("localStorage")) { |
|
180
|
window.localStorage.setItem(LOCALE_STORAGE_KEY, locale) |
|
181
|
} |
|
182
|
|
|
183
|
this.locale_ = locale |
|
184
|
} |
|
185
|
|
|
186
|
/** |
|
187
|
* `fetch` closely follows (and uses under the hood) the native `fetch` API. There are, however, few key differences: |
|
188
|
* - Non 2xx statuses throw a `FetchError` with the status code as the `status` property, rather than resolving the promise |
|
189
|
* - You can pass `body` and `query` as objects, and they will be encoded and stringified. |
|
190
|
* - The response gets parsed as JSON if the `accept` header is set to `application/json`, otherwise the raw Response object is returned |
|
191
|
* |
|
192
|
* Since the response is dynamically determined, we cannot know if it is JSON or not. Therefore, it is important to pass `Response` as the return type |
|
193
|
* |
|
194
|
* @param input: FetchInput |
|
195
|
* @param init: FetchArgs |
|
196
|
* @returns Promise<T> |
|
197
|
*/ |
|
198
|
fetch<T extends any>(input: FetchInput, init?: FetchArgs): Promise<T> { |
|
199
|
return this.fetch_(input, init) as unknown as Promise<T> |
|
200
|
} |
|
201
|
|
|
202
|
/** |
|
203
|
* `fetchStream` is a helper method to deal with server-sent events. It returns an object with a stream and an abort function. |
|
204
|
* It follows a very similar interface to `fetch`, with the return value being an async generator. |
|
205
|
* The stream is an async generator that yields `ServerSentEventMessage` objects, which contains the event name, stringified data, and few other properties. |
|
206
|
* The caller is responsible for handling `disconnect` events and aborting the stream. The caller is also responsible for parsing the data field. |
|
207
|
* |
|
208
|
* @param input: FetchInput |
|
209
|
* @param init: FetchArgs |
|
210
|
* @returns FetchStreamResponse |
|
211
|
*/ |
|
212
|
async fetchStream( |
|
213
|
input: FetchInput, |
|
214
|
init?: FetchArgs |
|
215
|
): Promise<FetchStreamResponse> { |
|
216
|
const abortController = new AbortController() |
|
217
|
const abortFunc = abortController.abort.bind(abortController) |
|
218
|
|
|
219
|
const fetchPromise = this.fetch_(input, { |
|
220
|
...init, |
|
221
|
signal: abortController.signal, |
|
222
|
headers: { ...init?.headers, accept: "text/event-stream" }, |
|
223
|
}) |
|
224
|
|
|
225
|
return { |
|
226
|
stream: (async function* () { |
|
227
|
const res = await fetchPromise |
|
228
|
|
|
229
|
if (!res.ok) { |
|
230
|
const error = new Error(`Stream failed with status ${res.status}`) |
|
231
|
error.name = "HttpError" |
|
232
|
throw error |
|
233
|
} |
|
234
|
|
|
235
|
yield* events(res, abortController.signal) |
|
236
|
})(), |
|
237
|
abort: abortFunc |
|
238
|
} |
|
239
|
} |
|
240
|
|
|
241
|
async setToken(token: string) { |
|
242
|
await this.setToken_(token) |
|
243
|
} |
|
244
|
|
|
245
|
async getToken() { |
|
246
|
return await this.getToken_() |
|
247
|
} |
|
248
|
|
|
249
|
async clearToken() { |
|
250
|
await this.clearToken_() |
|
251
|
} |
|
252
|
|
|
253
|
protected async clearToken_() { |
|
254
|
const { storageMethod, storageKey } = this.getTokenStorageInfo_() |
|
255
|
switch (storageMethod) { |
|
256
|
case "local": { |
|
257
|
window.localStorage.removeItem(storageKey) |
|
258
|
break |
|
259
|
} |
|
260
|
case "session": { |
|
261
|
window.sessionStorage.removeItem(storageKey) |
|
262
|
break |
|
263
|
} |
|
264
|
case "custom": { |
|
265
|
await this.config.auth?.storage?.removeItem(storageKey) |
|
266
|
break |
|
267
|
} |
|
268
|
case "memory": { |
|
269
|
this.token = "" |
|
270
|
break |
|
271
|
} |
|
272
|
} |
|
273
|
} |
|
274
|
|
|
275
|
protected initClient(): ClientFetch { |
|
276
|
const defaultHeaders = new Headers({ |
|
277
|
"content-type": "application/json", |
|
278
|
accept: "application/json", |
|
279
|
...this.getApiKeyHeader_(), |
|
280
|
...this.getPublishableKeyHeader_(), |
|
281
|
}) |
|
282
|
|
|
283
|
this.logger.debug( |
|
284
|
"Initiating Medusa client with default headers:\n", |
|
285
|
`${JSON.stringify(sanitizeHeaders(defaultHeaders), null, 2)}\n` |
|
286
|
) |
|
287
|
|
|
288
|
return async (input: FetchInput, init?: FetchArgs) => { |
|
289
|
// We always want to fetch the up-to-date JWT token before firing off a request. |
|
290
|
const headers = new Headers(defaultHeaders) |
|
291
|
|
|
292
|
if (this.locale) { |
|
293
|
headers.set("x-medusa-locale", this.locale) |
|
294
|
} |
|
295
|
|
|
296
|
const customHeaders = { |
|
297
|
"x-medusa-locale": this.locale, |
|
298
|
...this.config.globalHeaders, |
|
299
|
...(await this.getJwtHeader_()), |
|
300
|
...init?.headers, |
|
301
|
} |
|
302
|
|
|
303
|
// We use `headers.set` in order to ensure headers are overwritten in a case-insensitive manner. |
|
304
|
Object.entries(customHeaders).forEach(([key, value]) => { |
|
305
|
if (value === null) { |
|
306
|
headers.delete(key) |
|
307
|
} else { |
|
308
|
headers.set(key, value) |
|
309
|
} |
|
310
|
}) |
|
311
|
|
|
312
|
let normalizedInput: RequestInfo | URL = input |
|
313
|
if (input instanceof URL || typeof input === "string") { |
|
314
|
const baseUrl = new URL(this.config.baseUrl) |
|
315
|
const fullPath = `${baseUrl.pathname.replace(/\/$/, "")}/${input |
|
316
|
.toString() |
|
317
|
.replace(/^\//, "")}` |
|
318
|
normalizedInput = new URL(fullPath, baseUrl.origin) |
|
319
|
if (init?.query) { |
|
320
|
const params = Object.fromEntries( |
|
321
|
normalizedInput.searchParams.entries() |
|
322
|
) |
|
323
|
const stringifiedQuery = stringify( |
|
324
|
{ ...params, ...init.query }, |
|
325
|
{ skipNulls: true } |
|
326
|
) |
|
327
|
normalizedInput.search = stringifiedQuery |
|
328
|
} |
|
329
|
} |
|
330
|
|
|
331
|
this.logger.debug( |
|
332
|
"Performing request to:\n", |
|
333
|
`URL: ${normalizedInput.toString()}\n`, |
|
334
|
`Headers: ${JSON.stringify(sanitizeHeaders(headers), null, 2)}\n` |
|
335
|
) |
|
336
|
|
|
337
|
// Any non-request errors (eg. invalid JSON in the response) will be thrown as-is. |
|
338
|
return await fetch( |
|
339
|
normalizedInput, |
|
340
|
normalizeRequest(init, headers, this.config) |
|
341
|
).then((resp) => { |
|
342
|
this.logger.debug(`Received response with status ${resp.status}\n`) |
|
343
|
return normalizeResponse(resp, headers) |
|
344
|
}) |
|
345
|
} |
|
346
|
} |
|
347
|
|
|
348
|
protected getApiKeyHeader_ = (): { Authorization: string } | {} => { |
|
349
|
return this.config.apiKey |
|
350
|
? { Authorization: "Basic " + toBase64(this.config.apiKey + ":") } |
|
351
|
: {} |
|
352
|
} |
|
353
|
|
|
354
|
protected getPublishableKeyHeader_ = (): |
|
355
|
| { [PUBLISHABLE_KEY_HEADER]: string } |
|
356
|
| {} => { |
|
357
|
return this.config.publishableKey |
|
358
|
? { [PUBLISHABLE_KEY_HEADER]: this.config.publishableKey } |
|
359
|
: {} |
|
360
|
} |
|
361
|
|
|
362
|
protected async getJwtHeader_(): Promise<{ Authorization: string } | {}> { |
|
363
|
// If the user has requested for session storage, we don't want to send the JWT token in the header. |
|
364
|
if (this.config.auth?.type === "session") { |
|
365
|
return {} |
|
366
|
} |
|
367
|
|
|
368
|
const token = await this.getToken_() |
|
369
|
return token ? { Authorization: `Bearer ${token}` } : {} |
|
370
|
} |
|
371
|
|
|
372
|
protected async setToken_(token: string) { |
|
373
|
const { storageMethod, storageKey } = this.getTokenStorageInfo_() |
|
374
|
switch (storageMethod) { |
|
375
|
case "local": { |
|
376
|
window.localStorage.setItem(storageKey, token) |
|
377
|
break |
|
378
|
} |
|
379
|
case "session": { |
|
380
|
window.sessionStorage.setItem(storageKey, token) |
|
381
|
break |
|
382
|
} |
|
383
|
case "custom": { |
|
384
|
await this.config.auth?.storage?.setItem(storageKey, token) |
|
385
|
break |
|
386
|
} |
|
387
|
case "memory": { |
|
388
|
this.token = token |
|
389
|
break |
|
390
|
} |
|
391
|
} |
|
392
|
} |
|
393
|
|
|
394
|
protected async getToken_() { |
|
395
|
const { storageMethod, storageKey } = this.getTokenStorageInfo_() |
|
396
|
switch (storageMethod) { |
|
397
|
case "local": { |
|
398
|
return window.localStorage.getItem(storageKey) |
|
399
|
} |
|
400
|
case "session": { |
|
401
|
return window.sessionStorage.getItem(storageKey) |
|
402
|
} |
|
403
|
case "custom": { |
|
404
|
return await this.config.auth?.storage?.getItem(storageKey) |
|
405
|
} |
|
406
|
case "memory": { |
|
407
|
return this.token |
|
408
|
} |
|
409
|
} |
|
410
|
|
|
411
|
return null |
|
412
|
} |
|
413
|
|
|
414
|
protected getTokenStorageInfo_ = () => { |
|
415
|
const hasLocal = hasStorage("localStorage") |
|
416
|
const hasSession = hasStorage("sessionStorage") |
|
417
|
const hasCustom = Boolean(this.config.auth?.storage) |
|
418
|
|
|
419
|
const storageMethod = |
|
420
|
this.config.auth?.jwtTokenStorageMethod || |
|
421
|
(hasLocal ? "local" : "nostore") |
|
422
|
const storageKey = |
|
423
|
this.config.auth?.jwtTokenStorageKey || this.DEFAULT_JWT_STORAGE_KEY |
|
424
|
|
|
425
|
if (!hasLocal && storageMethod === "local") { |
|
426
|
this.throwError_("Local JWT storage is only available in the browser") |
|
427
|
} |
|
428
|
if (!hasSession && storageMethod === "session") { |
|
429
|
this.throwError_("Session JWT storage is only available in the browser") |
|
430
|
} |
|
431
|
if (!hasCustom && storageMethod === "custom") { |
|
432
|
this.throwError_("Custom storage was not provided in the config") |
|
433
|
} |
|
434
|
|
|
435
|
return { |
|
436
|
storageMethod, |
|
437
|
storageKey, |
|
438
|
} |
|
439
|
} |
|
440
|
|
|
441
|
protected throwError_(message: string) { |
|
442
|
this.logger.error(message) |
|
443
|
throw new Error(message) |
|
444
|
} |
|
445
|
} |