@commercetools/sdk-client-v2 2.0.2 → 2.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.
@@ -13,7 +13,6 @@ function _defineProperty(obj, key, value) {
13
13
  } else {
14
14
  obj[key] = value;
15
15
  }
16
-
17
16
  return obj;
18
17
  }
19
18
 
@@ -22,7 +21,6 @@ var METHODS = ['ACL', 'BIND', 'CHECKOUT', 'CONNECT', 'COPY', 'DELETE', 'GET', 'H
22
21
  /**
23
22
  * @throws {Error}
24
23
  */
25
-
26
24
  function validate(funcName, request, options = {
27
25
  allowedMethods: METHODS
28
26
  }) {
@@ -32,19 +30,18 @@ function validate(funcName, request, options = {
32
30
  }
33
31
 
34
32
  let _options;
35
-
36
33
  function compose(...funcs) {
37
34
  funcs = funcs.filter(func => typeof func === 'function');
38
35
  if (funcs.length === 1) return funcs[0];
39
36
  return funcs.reduce((a, b) => (...args) => a(b(...args)));
40
37
  }
41
-
42
38
  function process$1(request, fn, processOpt) {
43
39
  validate('process', request, {
44
40
  allowedMethods: ['GET']
45
41
  });
46
- if (typeof fn !== 'function') throw new Error('The "process" function accepts a "Function" as a second argument that returns a Promise. See https://commercetools.github.io/nodejs/sdk/api/sdkClient.html#processrequest-processfn-options'); // Set default process options
42
+ if (typeof fn !== 'function') throw new Error('The "process" function accepts a "Function" as a second argument that returns a Promise. See https://commercetools.github.io/nodejs/sdk/api/sdkClient.html#processrequest-processfn-options');
47
43
 
44
+ // Set default process options
48
45
  const opt = {
49
46
  total: Number.POSITIVE_INFINITY,
50
47
  accumulate: true,
@@ -52,15 +49,14 @@ function process$1(request, fn, processOpt) {
52
49
  };
53
50
  return new Promise((resolve, reject) => {
54
51
  let _path,
55
- _queryString = '';
56
-
52
+ _queryString = '';
57
53
  if (request && request.uri) {
58
54
  const [path, queryString] = request.uri.split('?');
59
55
  _path = path;
60
56
  _queryString = queryString;
61
57
  }
62
-
63
- const requestQuery = { ...qs.parse(_queryString)
58
+ const requestQuery = {
59
+ ...qs.parse(_queryString)
64
60
  };
65
61
  const query = {
66
62
  // defaults
@@ -70,11 +66,11 @@ function process$1(request, fn, processOpt) {
70
66
  };
71
67
  let hasFirstPageBeenProcessed = false;
72
68
  let itemsToGet = opt.total;
73
-
74
69
  const processPage = async (lastId, acc = []) => {
75
70
  // Use the lesser value between limit and itemsToGet in query
76
71
  const limit = query.limit < itemsToGet ? query.limit : itemsToGet;
77
- const originalQueryString = qs.stringify({ ...query,
72
+ const originalQueryString = qs.stringify({
73
+ ...query,
78
74
  limit
79
75
  });
80
76
  const enhancedQuery = {
@@ -85,45 +81,42 @@ function process$1(request, fn, processOpt) {
85
81
  } : {})
86
82
  };
87
83
  const enhancedQueryString = qs.stringify(enhancedQuery);
88
- const enhancedRequest = { ...request,
84
+ const enhancedRequest = {
85
+ ...request,
89
86
  uri: `${_path}?${enhancedQueryString}&${originalQueryString}`
90
87
  };
91
-
92
88
  try {
93
89
  const payload = await createClient(_options).execute(enhancedRequest);
94
90
  const {
95
91
  results,
96
92
  count: resultsLength
97
93
  } = payload.body;
98
-
99
94
  if (!resultsLength && hasFirstPageBeenProcessed) {
100
95
  return resolve(acc || []);
101
96
  }
102
-
103
97
  const result = await Promise.resolve(fn(payload));
104
98
  let accumulated;
105
99
  hasFirstPageBeenProcessed = true;
106
100
  if (opt.accumulate) accumulated = acc.concat(result || []);
107
- itemsToGet -= resultsLength; // If there are no more items to get, it means the total number
101
+ itemsToGet -= resultsLength;
102
+ // If there are no more items to get, it means the total number
108
103
  // of items in the original request have been fetched so we
109
104
  // resolve the promise.
110
105
  // Also, if we get less results in a page then the limit set it
111
106
  // means that there are no more pages and that we can finally
112
107
  // resolve the promise.
113
-
114
108
  if (resultsLength < query.limit || !itemsToGet) {
115
109
  return resolve(accumulated || []);
116
110
  }
117
-
118
111
  const last = results[resultsLength - 1];
119
112
  const newLastId = last && last.id;
120
113
  processPage(newLastId, accumulated);
121
114
  } catch (error) {
122
115
  reject(error);
123
116
  }
124
- }; // Start iterating through pages
125
-
117
+ };
126
118
 
119
+ // Start iterating through pages
127
120
  processPage();
128
121
  });
129
122
  }
@@ -137,7 +130,6 @@ function createClient(options) {
137
130
  * Given a request object,
138
131
  */
139
132
  process: process$1,
140
-
141
133
  execute(request) {
142
134
  validate('exec', request);
143
135
  return new Promise((resolve, reject) => {
@@ -156,9 +148,9 @@ function createClient(options) {
156
148
  rs.resolve(resObj);
157
149
  }
158
150
  };
159
-
160
151
  const dispatch = compose(...options.middlewares)(resolver);
161
- dispatch(request, // Initial response shape
152
+ dispatch(request,
153
+ // Initial response shape
162
154
  {
163
155
  resolve,
164
156
  reject,
@@ -167,14 +159,12 @@ function createClient(options) {
167
159
  });
168
160
  });
169
161
  }
170
-
171
162
  };
172
163
  }
173
164
 
174
165
  // POST https://{host}/oauth/token?grant_type=client_credentials&scope={scope}
175
166
  // Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
176
167
  const Buffer$1 = require('buffer/').Buffer;
177
-
178
168
  function buildRequestForClientCredentialsFlow(options) {
179
169
  if (!options) throw new Error('Missing required options');
180
170
  if (!options.host) throw new Error('Missing required option (host)');
@@ -186,9 +176,9 @@ function buildRequestForClientCredentialsFlow(options) {
186
176
  } = options.credentials;
187
177
  if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
188
178
  const scope = options.scopes ? options.scopes.join(' ') : undefined;
189
- const basicAuth = Buffer$1.from(`${clientId}:${clientSecret}`).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
179
+ const basicAuth = Buffer$1.from(`${clientId}:${clientSecret}`).toString('base64');
180
+ // This is mostly useful for internal testing purposes to be able to check
190
181
  // other oauth endpoints.
191
-
192
182
  const oauthUri = options.oauthUri || '/oauth/token';
193
183
  const url = options.host.replace(/\/$/, '') + oauthUri;
194
184
  const body = `grant_type=client_credentials${scope ? `&scope=${scope}` : ''}`;
@@ -222,10 +212,9 @@ function buildRequestForPasswordFlow(options) {
222
212
  * This is mostly useful for internal testing purposes to be able to check
223
213
  * other oauth endpoints.
224
214
  */
225
-
226
215
  const oauthUri = options.oauthUri || `/oauth/${pKey}/customers/token`;
227
- const url = options.host.replace(/\/$/, '') + oauthUri; // encode username and password as requested by the system
228
-
216
+ const url = options.host.replace(/\/$/, '') + oauthUri;
217
+ // encode username and password as requested by the system
229
218
  const body = `grant_type=password&username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}${scopeStr}`;
230
219
  return {
231
220
  basicAuth,
@@ -244,9 +233,9 @@ function buildRequestForRefreshTokenFlow(options) {
244
233
  clientSecret
245
234
  } = options.credentials;
246
235
  if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
247
- const basicAuth = Buffer$1.from(`${clientId}:${clientSecret}`).toString('base64'); // This is mostly useful for internal testing purposes to be able to check
236
+ const basicAuth = Buffer$1.from(`${clientId}:${clientSecret}`).toString('base64');
237
+ // This is mostly useful for internal testing purposes to be able to check
248
238
  // other oauth endpoints.
249
-
250
239
  const oauthUri = options.oauthUri || '/oauth/token';
251
240
  const url = options.host.replace(/\/$/, '') + oauthUri;
252
241
  const body = `grant_type=refresh_token&refresh_token=${encodeURIComponent(options.refreshToken)}`;
@@ -263,25 +252,26 @@ function buildRequestForAnonymousSessionFlow(options) {
263
252
  options.oauthUri = options.oauthUri || `/oauth/${pKey}/anonymous/token`;
264
253
  const result = buildRequestForClientCredentialsFlow(options);
265
254
  if (options.credentials.anonymousId) result.body += `&anonymous_id=${options.credentials.anonymousId}`;
266
- return { ...result
255
+ return {
256
+ ...result
267
257
  };
268
258
  }
269
259
 
270
260
  const Buffer = require('buffer/').Buffer;
271
-
272
261
  function mergeAuthHeader(token, req) {
273
- return { ...req,
274
- headers: { ...req.headers,
262
+ return {
263
+ ...req,
264
+ headers: {
265
+ ...req.headers,
275
266
  Authorization: `Bearer ${token}`
276
267
  }
277
268
  };
278
269
  }
279
-
280
270
  function calculateExpirationTime(expiresIn) {
281
- return Date.now() + // Add a gap of 5 minutes before expiration time.
271
+ return Date.now() +
272
+ // Add a gap of 5 minutes before expiration time.
282
273
  expiresIn * 1000 - 5 * 60 * 1000;
283
274
  }
284
-
285
275
  async function executeRequest({
286
276
  fetcher,
287
277
  url,
@@ -303,27 +293,28 @@ async function executeRequest({
303
293
  },
304
294
  body
305
295
  });
306
-
307
296
  if (_res.ok) {
308
297
  const {
309
298
  access_token: token,
310
299
  expires_in: expiresIn,
311
300
  refresh_token: refreshToken
312
301
  } = await _res.json();
313
- const expirationTime = calculateExpirationTime(expiresIn); // cache new generated token
302
+ const expirationTime = calculateExpirationTime(expiresIn);
314
303
 
304
+ // cache new generated token
315
305
  tokenCache.set({
316
306
  token,
317
307
  expirationTime,
318
308
  refreshToken
319
- }, tokenCacheKey); // Dispatch all pending requests
309
+ }, tokenCacheKey);
320
310
 
311
+ // Dispatch all pending requests
321
312
  requestState.set(false);
313
+
322
314
  /**
323
315
  * Freeze and copy pending queue, reset original one for accepting
324
316
  * new pending tasks
325
317
  */
326
-
327
318
  const executionQueue = pendingTasks.slice();
328
319
  pendingTasks = [];
329
320
  executionQueue.forEach(task => {
@@ -333,31 +324,28 @@ async function executeRequest({
333
324
  * console.log('test', cache, pendingTasks)
334
325
  * Continue by calling the task's own next function
335
326
  */
336
-
337
327
  task.next(requestWithAuth, task.response);
338
328
  });
339
329
  return;
340
- } // Handle error response
341
-
330
+ }
342
331
 
332
+ // Handle error response
343
333
  let parsed;
344
334
  const text = await _res.text();
345
-
346
335
  try {
347
336
  parsed = JSON.parse(text);
348
337
  } catch (error) {
349
338
  /* noop */
350
339
  }
351
-
352
340
  const error = new Error(parsed ? parsed.message : text);
353
341
  if (parsed) error.body = parsed;
342
+
354
343
  /**
355
344
  * to notify that token is either fetched or failed
356
345
  * in the below case token failed to be fetched
357
346
  * and reset requestState to false
358
347
  * so requestState could be shared between multi authMiddlewareBase functions
359
348
  */
360
-
361
349
  requestState.set(false);
362
350
  response.reject(error);
363
351
  } catch (error) {
@@ -371,7 +359,6 @@ async function executeRequest({
371
359
  if (response && typeof response.reject === 'function') response.reject(error);
372
360
  }
373
361
  }
374
-
375
362
  function authMiddlewareBase({
376
363
  request,
377
364
  response,
@@ -385,50 +372,50 @@ function authMiddlewareBase({
385
372
  fetch: fetcher
386
373
  }, next, userOptions) {
387
374
  if (!fetcher && typeof fetch === 'undefined') throw new Error('`fetch` is not available. Please pass in `fetch` as an option or have it globally available.');
388
- if (!fetcher) fetcher = fetch; // Check if there is already a `Authorization` header in the request.
375
+ if (!fetcher) fetcher = fetch;
376
+ // Check if there is already a `Authorization` header in the request.
389
377
  // If so, then go directly to the next middleware.
390
-
391
378
  if (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) {
392
379
  next(request, response);
393
380
  return;
394
- } // If there was a token in the tokenCache, and it's not expired, append
381
+ }
382
+ // If there was a token in the tokenCache, and it's not expired, append
395
383
  // the token in the `Authorization` header.
396
-
397
-
398
384
  const tokenObj = tokenCache.get(tokenCacheKey);
399
-
400
385
  if (tokenObj && tokenObj.token && Date.now() < tokenObj.expirationTime) {
401
386
  const requestWithAuth = mergeAuthHeader(tokenObj.token, request);
402
387
  next(requestWithAuth, response);
403
388
  return;
404
389
  }
390
+
405
391
  /**
406
392
  * Keep pending tasks until a token is fetched
407
393
  * Save next function as well, to call it once the token has been fetched, which prevents
408
394
  * unexpected behaviour in a context in which the next function uses global vars
409
395
  * or Promises to capture the token to hand it to other libraries, e.g. Apollo
410
396
  */
411
-
412
-
413
397
  pendingTasks.push({
414
398
  request,
415
399
  response,
416
400
  next
417
- }); // If a token is currently being fetched, just wait ;)
401
+ });
418
402
 
419
- if (requestState.get()) return; // Mark that a token is being fetched
403
+ // If a token is currently being fetched, just wait ;)
404
+ if (requestState.get()) return;
420
405
 
406
+ // Mark that a token is being fetched
421
407
  requestState.set(true);
408
+
422
409
  /**
423
410
  * If there was a refreshToken in the tokenCache, and there was an expired
424
411
  * token or no token in the tokenCache, use the refreshToken flow
425
412
  */
426
-
427
413
  if (tokenObj && tokenObj.refreshToken && (!tokenObj.token || tokenObj.token && Date.now() > tokenObj.expirationTime)) {
428
414
  if (!userOptions) throw new Error('Missing required options');
429
415
  executeRequest({
430
416
  fetcher,
431
- ...buildRequestForRefreshTokenFlow({ ...userOptions,
417
+ ...buildRequestForRefreshTokenFlow({
418
+ ...userOptions,
432
419
  refreshToken: tokenObj.refreshToken
433
420
  }),
434
421
  tokenCacheKey,
@@ -438,9 +425,9 @@ function authMiddlewareBase({
438
425
  response
439
426
  });
440
427
  return;
441
- } // Token and refreshToken are not present or invalid. Request a new token...
442
-
428
+ }
443
429
 
430
+ // Token and refreshToken are not present or invalid. Request a new token...
444
431
  executeRequest({
445
432
  fetcher,
446
433
  url,
@@ -457,16 +444,18 @@ function authMiddlewareBase({
457
444
  function store(initVal) {
458
445
  let value = initVal;
459
446
  return {
460
- get: () => value,
461
- set: val => {
447
+ get: TokenCacheOption => value,
448
+ set: (val, TokenCacheOption) => {
462
449
  value = val;
463
- return value;
464
450
  }
465
451
  };
466
452
  }
467
453
 
468
454
  function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
469
- const tokenCache = options.tokenCache || store({});
455
+ const tokenCache = options.tokenCache || store({
456
+ token: '',
457
+ expirationTime: -1
458
+ });
470
459
  const pendingTasks = [];
471
460
  const requestState = store(false);
472
461
  return next => (request, response) => {
@@ -476,7 +465,6 @@ function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
476
465
  next(request, response);
477
466
  return;
478
467
  }
479
-
480
468
  const params = {
481
469
  request,
482
470
  response,
@@ -512,7 +500,6 @@ function createAuthMiddlewareForClientCredentialsFlow$1(options) {
512
500
  next(request, response);
513
501
  return;
514
502
  }
515
-
516
503
  const params = {
517
504
  request,
518
505
  response,
@@ -531,17 +518,18 @@ function createAuthMiddlewareWithExistingToken$1(authorization = '', options = {
531
518
  return next => (request, response) => {
532
519
  if (typeof authorization !== 'string') throw new Error('authorization must be a string');
533
520
  const force = options.force === undefined ? true : options.force;
521
+
534
522
  /** The request will not be modified if:
535
523
  * 1. no argument is passed
536
524
  * 2. force is false and authorization header exists
537
525
  */
538
-
539
526
  if (!authorization || (request.headers && request.headers.authorization || request.headers && request.headers.Authorization) && force === false) {
540
527
  return next(request, response);
541
528
  }
542
-
543
- const requestWithAuth = { ...request,
544
- headers: { ...request.headers,
529
+ const requestWithAuth = {
530
+ ...request,
531
+ headers: {
532
+ ...request.headers,
545
533
  Authorization: authorization
546
534
  }
547
535
  };
@@ -560,7 +548,6 @@ function createAuthMiddlewareForPasswordFlow$1(options) {
560
548
  next(request, response);
561
549
  return;
562
550
  }
563
-
564
551
  const params = {
565
552
  request,
566
553
  response,
@@ -575,7 +562,10 @@ function createAuthMiddlewareForPasswordFlow$1(options) {
575
562
  }
576
563
 
577
564
  function createAuthMiddlewareForRefreshTokenFlow$1(options) {
578
- const tokenCache = options.tokenCache || store({});
565
+ const tokenCache = options.tokenCache || store({
566
+ token: '',
567
+ expirationTime: -1
568
+ });
579
569
  const pendingTasks = [];
580
570
  const requestState = store(false);
581
571
  return next => (request, response) => {
@@ -585,7 +575,6 @@ function createAuthMiddlewareForRefreshTokenFlow$1(options) {
585
575
  next(request, response);
586
576
  return;
587
577
  }
588
-
589
578
  const params = {
590
579
  request,
591
580
  response,
@@ -610,8 +599,10 @@ var authMiddlewares = /*#__PURE__*/Object.freeze({
610
599
 
611
600
  function createCorrelationIdMiddleware(options) {
612
601
  return next => (request, response) => {
613
- const nextRequest = { ...request,
614
- headers: { ...request.headers,
602
+ const nextRequest = {
603
+ ...request,
604
+ headers: {
605
+ ...request.headers,
615
606
  'X-Correlation-ID': options.generate()
616
607
  }
617
608
  };
@@ -627,16 +618,11 @@ function defineError(statusCode, message, meta = {}) {
627
618
  this.constructor.prototype.__proto__ = Error.prototype;
628
619
  if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
629
620
  }
630
-
631
621
  function NetworkError(...args) {
632
- defineError.call(this, 0
633
- /* special code to indicate network errors */
634
- , ...args);
622
+ defineError.call(this, 0 /* special code to indicate network errors */, ...args);
635
623
  }
636
624
  function HttpError(...args) {
637
- defineError.call(this,
638
- /* code will be passed as arg */
639
- ...args);
625
+ defineError.call(this, /* code will be passed as arg */...args);
640
626
  }
641
627
  function BadRequest(...args) {
642
628
  defineError.call(this, 400, ...args);
@@ -663,39 +649,34 @@ function getErrorByCode(code) {
663
649
  switch (code) {
664
650
  case 0:
665
651
  return NetworkError;
666
-
667
652
  case 400:
668
653
  return BadRequest;
669
-
670
654
  case 401:
671
655
  return Unauthorized;
672
-
673
656
  case 403:
674
657
  return Forbidden;
675
-
676
658
  case 404:
677
659
  return NotFound;
678
-
679
660
  case 409:
680
661
  return ConcurrentModification;
681
-
682
662
  case 500:
683
663
  return InternalServerError;
684
-
685
664
  case 503:
686
665
  return ServiceUnavailable;
687
-
688
666
  default:
689
667
  return undefined;
690
668
  }
691
669
  }
692
670
 
693
671
  function parseHeaders(headers) {
694
- if (headers.raw) // node-fetch
695
- return headers.raw(); // Tmp fix for Firefox until it supports iterables
672
+ if (headers.raw)
673
+ // node-fetch
674
+ return headers.raw();
696
675
 
697
- if (!headers.forEach) return {}; // whatwg-fetch
676
+ // Tmp fix for Firefox until it supports iterables
677
+ if (!headers.forEach) return {};
698
678
 
679
+ // whatwg-fetch
699
680
  const map = {};
700
681
  headers.forEach((value, name) => {
701
682
  map[name] = value;
@@ -703,10 +684,10 @@ function parseHeaders(headers) {
703
684
  return map;
704
685
  }
705
686
 
687
+ // performs a proper buffer check
706
688
  function isBuffer(obj) {
707
689
  return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj);
708
690
  }
709
-
710
691
  function createError({
711
692
  statusCode,
712
693
  message,
@@ -717,23 +698,21 @@ function createError({
717
698
  const ResponseError = getErrorByCode(statusCode);
718
699
  if (ResponseError) return new ResponseError(errorMessage, rest);
719
700
  return new HttpError(statusCode, errorMessage, rest);
720
- } // calculates the delay duration exponentially
721
- // More info about the algorithm use here https://goo.gl/Xk8h5f
722
-
701
+ }
723
702
 
703
+ // calculates the delay duration exponentially
704
+ // More info about the algorithm use here https://goo.gl/Xk8h5f
724
705
  function calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay) {
725
706
  if (backoff) return retryCount !== 0 // do not increase if it's the first retry
726
707
  ? Math.min(Math.round((Math.random() + 1) * retryDelay * 2 ** retryCount), maxDelay) : retryDelay;
727
708
  return retryDelay;
728
709
  }
729
-
730
710
  function maskAuthData(request, maskSensitiveHeaderData) {
731
711
  if (maskSensitiveHeaderData) {
732
712
  if (request && request.headers && request.headers.authorization) request.headers.authorization = 'Bearer ********';
733
713
  if (request && request.headers && request.headers.Authorization) request.headers.Authorization = 'Bearer ********';
734
714
  }
735
715
  }
736
-
737
716
  function createHttpMiddleware({
738
717
  host,
739
718
  credentialsMode,
@@ -749,6 +728,8 @@ function createHttpMiddleware({
749
728
  backoff = true,
750
729
  retryDelay = 200,
751
730
  maxDelay = Infinity,
731
+ // If set to true reinitialize the abort controller when the timeout is reached and apply the retry config
732
+ retryOnAbort = false,
752
733
  retryCodes = [503]
753
734
  } = {},
754
735
  fetch: fetcher,
@@ -758,7 +739,6 @@ function createHttpMiddleware({
758
739
  if (!fetcher) throw new Error('`fetch` is not available. Please pass in `fetch` as an option or have it globally available.');
759
740
  if (timeout && !getAbortController) throw new Error('`AbortController` is not available. Please pass in `getAbortController` as an option or have AbortController globally available when using timeout.');
760
741
  let fetchFunction;
761
-
762
742
  if (fetcher) {
763
743
  fetchFunction = fetcher;
764
744
  } else {
@@ -767,71 +747,65 @@ function createHttpMiddleware({
767
747
  // For reference of this pattern: https://github.com/apollographql/apollo-link/blob/498b413a5b5199b0758ce898b3bb55451f57a2fa/packages/apollo-link-http/src/httpLink.ts#L49
768
748
  fetchFunction = fetch;
769
749
  }
770
-
771
750
  if (!Array.isArray(retryCodes)) {
772
751
  throw new Error('`retryCodes` option must be an array of retry status (error) codes.');
773
752
  }
774
-
775
753
  return next => (request, response) => {
776
- let abortController;
777
- if (timeout || getAbortController) abortController = (getAbortController ? getAbortController() : null) || new AbortController();
778
754
  const url = host.replace(/\/$/, '') + request.uri;
779
- const requestHeader = { ...request.headers
780
- }; // Unset the content-type header if explicitly asked to (passing `null` as value).
755
+ const requestHeader = {
756
+ ...request.headers
757
+ };
781
758
 
759
+ // Unset the content-type header if explicitly asked to (passing `null` as value).
782
760
  if (requestHeader['Content-Type'] === null) {
783
761
  delete requestHeader['Content-Type'];
784
762
  }
785
-
786
763
  if (!(Object.prototype.hasOwnProperty.call(requestHeader, 'Content-Type') || Object.prototype.hasOwnProperty.call(requestHeader, 'content-type'))) {
787
764
  requestHeader['Content-Type'] = 'application/json';
788
- } // Ensure body is a string if content type is application/json
789
-
765
+ }
790
766
 
767
+ // Ensure body is a string if content type is application/json
791
768
  const body = ['application/json', 'application/graphql'].indexOf(requestHeader['Content-Type']) > -1 && typeof request.body === 'string' || isBuffer(request.body) ? request.body : JSON.stringify(request.body || undefined);
792
-
793
769
  if (body && (typeof body === 'string' || isBuffer(body))) {
794
770
  requestHeader['Content-Length'] = Buffer$2.byteLength(body).toString();
795
771
  }
796
-
797
772
  const fetchOptions = {
798
773
  method: request.method,
799
774
  headers: requestHeader
800
775
  };
801
-
802
776
  if (credentialsMode) {
803
777
  fetchOptions.credentialsMode = credentialsMode;
804
778
  }
805
-
806
- if (abortController) {
807
- fetchOptions.signal = abortController.signal;
808
- }
809
-
810
779
  if (body) {
811
780
  fetchOptions.body = body;
812
781
  }
813
-
814
- let retryCount = 0; // wrap in a fn so we can retry if error occur
815
-
782
+ let retryCount = 0;
783
+ // wrap in a fn so we can retry if error occur
816
784
  function executeFetch() {
817
785
  // Kick off timer for abortController directly before fetch.
818
786
  let timer;
819
- if (timeout) timer = setTimeout(() => {
820
- abortController.abort();
821
- }, timeout);
787
+ let abortController;
788
+ if (timeout) {
789
+ // Initialize the abort controller in case we do a retry on an aborted request to rest the signal
790
+ abortController = (getAbortController ? getAbortController() : null) || new AbortController();
791
+ fetchOptions.signal = abortController.signal;
792
+ // Set the timer
793
+ timer = setTimeout(() => {
794
+ abortController.abort();
795
+ }, timeout);
796
+ }
822
797
  fetchFunction(url, fetchOptions).then(res => {
823
798
  if (res.ok) {
824
799
  if (fetchOptions.method === 'HEAD') {
825
- next(request, { ...response,
800
+ next(request, {
801
+ ...response,
826
802
  statusCode: res.status
827
803
  });
828
804
  return;
829
805
  }
830
-
831
806
  res.text().then(result => {
832
807
  // Try to parse the response as JSON
833
808
  let parsed;
834
-
835
809
  try {
836
810
  parsed = result.length > 0 ? JSON.parse(result) : {};
837
811
  } catch (err) {
@@ -840,39 +814,35 @@ function createHttpMiddleware({
840
814
  retryCount += 1;
841
815
  return;
842
816
  }
843
-
844
817
  parsed = result;
845
818
  }
846
-
847
- const parsedResponse = { ...response,
819
+ const parsedResponse = {
820
+ ...response,
848
821
  body: parsed,
849
822
  statusCode: res.status
850
823
  };
851
824
  if (includeResponseHeaders) parsedResponse.headers = parseHeaders(res.headers);
852
-
853
825
  if (includeOriginalRequest) {
854
- parsedResponse.request = { ...fetchOptions
826
+ parsedResponse.request = {
827
+ ...fetchOptions
855
828
  };
856
829
  maskAuthData(parsedResponse.request, maskSensitiveHeaderData);
857
830
  }
858
-
859
831
  next(request, parsedResponse);
860
832
  });
861
833
  return;
862
- } // Server responded with an error. Try to parse it as JSON, then
863
- // return a proper error type with all necessary meta information.
864
-
834
+ }
865
835
 
836
+ // Server responded with an error. Try to parse it as JSON, then
837
+ // return a proper error type with all necessary meta information.
866
838
  res.text().then(text => {
867
839
  // Try to parse the error response as JSON
868
840
  let parsed;
869
-
870
841
  try {
871
842
  parsed = JSON.parse(text);
872
843
  } catch (error) {
873
844
  parsed = text;
874
845
  }
875
-
876
846
  const error = createError({
877
847
  statusCode: res.status,
878
848
  ...(includeRequestInErrorResponse ? {
@@ -888,7 +858,6 @@ function createHttpMiddleware({
888
858
  body: parsed
889
859
  })
890
860
  });
891
-
892
861
  if (enableRetry && (retryCodes.indexOf(error.statusCode) !== -1 || (retryCodes === null || retryCodes === void 0 ? void 0 : retryCodes.indexOf(error.message)) !== -1)) {
893
862
  if (retryCount < maxRetries) {
894
863
  setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
@@ -896,29 +865,35 @@ function createHttpMiddleware({
896
865
  return;
897
866
  }
898
867
  }
899
-
900
- maskAuthData(error.originalRequest, maskSensitiveHeaderData); // Let the final resolver to reject the promise
901
-
902
- const parsedResponse = { ...response,
868
+ maskAuthData(error.originalRequest, maskSensitiveHeaderData);
869
+ // Let the final resolver to reject the promise
870
+ const parsedResponse = {
871
+ ...response,
903
872
  error,
904
873
  statusCode: res.status
905
874
  };
906
875
  next(request, parsedResponse);
907
876
  });
908
- }, // We know that this is a "network" error thrown by the `fetch` library
877
+ },
878
+ // We know that this is a "network" error thrown by the `fetch` library
909
879
  e => {
910
- if (enableRetry) if (retryCount < maxRetries) {
911
- setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
912
- retryCount += 1;
913
- return;
880
+ // Retry when enabled and either the request was not aborted or retryOnAbort is enabled
881
+ if (enableRetry && (retryOnAbort || !abortController || !abortController.signal)) {
882
+ if (retryCount < maxRetries) {
883
+ setTimeout(executeFetch, calcDelayDuration(retryCount, retryDelay, maxRetries, backoff, maxDelay));
884
+ retryCount += 1;
885
+ return;
886
+ }
914
887
  }
915
- const error = new NetworkError(e.message, { ...(includeRequestInErrorResponse ? {
888
+ const error = new NetworkError(e.message, {
889
+ ...(includeRequestInErrorResponse ? {
916
890
  originalRequest: request
917
891
  } : {}),
918
892
  retryCount
919
893
  });
920
894
  maskAuthData(error.originalRequest, maskSensitiveHeaderData);
921
- next(request, { ...response,
895
+ next(request, {
896
+ ...response,
922
897
  error,
923
898
  statusCode: 0
924
899
  });
@@ -926,7 +901,6 @@ function createHttpMiddleware({
926
901
  clearTimeout(timer);
927
902
  });
928
903
  }
929
-
930
904
  executeFetch();
931
905
  };
932
906
  }
@@ -953,42 +927,41 @@ function createQueueMiddleware({
953
927
  }) {
954
928
  const queue = [];
955
929
  let runningCount = 0;
956
-
957
930
  const dequeue = next => {
958
931
  // We assume here that this task has been completed
959
- runningCount -= 1; // Check if there are any other pending tasks and execute them
932
+ runningCount -= 1;
960
933
 
934
+ // Check if there are any other pending tasks and execute them
961
935
  if (queue.length && runningCount <= concurrency) {
962
936
  const nextTask = queue.shift();
963
937
  runningCount += 1;
964
938
  next(nextTask.request, nextTask.response);
965
939
  }
966
940
  };
967
-
968
941
  return next => (request, response) => {
969
942
  // Override response `resolve` and `reject` to know when the request has
970
943
  // been completed and therefore trigger a pending task in the queue.
971
- const patchedResponse = { ...response,
972
-
944
+ const patchedResponse = {
945
+ ...response,
973
946
  resolve(data) {
974
947
  // Resolve original promise
975
948
  response.resolve(data);
976
949
  dequeue(next);
977
950
  },
978
-
979
951
  reject(error) {
980
952
  // Reject original promise
981
953
  response.reject(error);
982
954
  dequeue(next);
983
955
  }
956
+ };
984
957
 
985
- }; // Add task to the queue
986
-
958
+ // Add task to the queue
987
959
  queue.push({
988
960
  request,
989
961
  response: patchedResponse
990
- }); // If possible, run the task straight away
962
+ });
991
963
 
964
+ // If possible, run the task straight away
992
965
  if (runningCount < concurrency) {
993
966
  const nextTask = queue.shift();
994
967
  runningCount += 1;
@@ -999,7 +972,7 @@ function createQueueMiddleware({
999
972
 
1000
973
  var packageJson = {
1001
974
  name: "@commercetools/sdk-client-v2",
1002
- version: "2.0.2",
975
+ version: "2.1.0",
1003
976
  engines: {
1004
977
  node: ">=14"
1005
978
  },
@@ -1051,7 +1024,7 @@ var packageJson = {
1051
1024
  "abort-controller": "3.0.0",
1052
1025
  "common-tags": "1.8.2",
1053
1026
  dotenv: "16.0.3",
1054
- jest: "29.2.1",
1027
+ jest: "29.3.0",
1055
1028
  nock: "12.0.3",
1056
1029
  "organize-imports-cli": "0.10.0"
1057
1030
  },
@@ -1071,10 +1044,8 @@ var packageJson = {
1071
1044
  the specific test.
1072
1045
  */
1073
1046
  const isBrowser = () => window.document && window.document.nodeType === 9;
1074
-
1075
1047
  function getSystemInfo() {
1076
1048
  var _process;
1077
-
1078
1049
  if (isBrowser()) return window.navigator.userAgent;
1079
1050
  const nodeVersion = ((_process = process) === null || _process === void 0 ? void 0 : _process.version.slice(1)) || '12'; // temporary fix for rn environment
1080
1051
  // const platformInfo = `(${process.platform}; ${process.arch})`
@@ -1082,31 +1053,38 @@ function getSystemInfo() {
1082
1053
 
1083
1054
  return `node.js/${nodeVersion}`;
1084
1055
  }
1085
-
1086
1056
  function createUserAgent(options) {
1087
- if (!options || Object.keys(options).length === 0 || !{}.hasOwnProperty.call(options, 'name')) throw new Error('Missing required option `name`'); // Main info
1057
+ if (!options || Object.keys(options).length === 0 || !{}.hasOwnProperty.call(options, 'name')) throw new Error('Missing required option `name`');
1088
1058
 
1089
- const baseInfo = options.version ? `${options.name}/${options.version}` : options.name; // Library info
1059
+ // Main info
1060
+ const baseInfo = options.version ? `${options.name}/${options.version}` : options.name;
1090
1061
 
1062
+ // Library info
1091
1063
  let libraryInfo = null;
1092
- if (options.libraryName && !options.libraryVersion) libraryInfo = options.libraryName;else if (options.libraryName && options.libraryVersion) libraryInfo = `${options.libraryName}/${options.libraryVersion}`; // Contact info
1064
+ if (options.libraryName && !options.libraryVersion) libraryInfo = options.libraryName;else if (options.libraryName && options.libraryVersion) libraryInfo = `${options.libraryName}/${options.libraryVersion}`;
1093
1065
 
1066
+ // Contact info
1094
1067
  let contactInfo = null;
1095
- if (options.contactUrl && !options.contactEmail) contactInfo = `(+${options.contactUrl})`;else if (!options.contactUrl && options.contactEmail) contactInfo = `(+${options.contactEmail})`;else if (options.contactUrl && options.contactEmail) contactInfo = `(+${options.contactUrl}; +${options.contactEmail})`; // System info
1068
+ if (options.contactUrl && !options.contactEmail) contactInfo = `(+${options.contactUrl})`;else if (!options.contactUrl && options.contactEmail) contactInfo = `(+${options.contactEmail})`;else if (options.contactUrl && options.contactEmail) contactInfo = `(+${options.contactUrl}; +${options.contactEmail})`;
1096
1069
 
1097
- const systemInfo = getSystemInfo(); // customName
1070
+ // System info
1071
+ const systemInfo = getSystemInfo();
1098
1072
 
1073
+ // customName
1099
1074
  const customAgent = options.customAgent || '';
1100
1075
  return [baseInfo, systemInfo, libraryInfo, contactInfo, customAgent].filter(Boolean).join(' ');
1101
1076
  }
1102
1077
 
1103
1078
  function createUserAgentMiddleware(options) {
1104
- const userAgent = createUserAgent({ ...options,
1079
+ const userAgent = createUserAgent({
1080
+ ...options,
1105
1081
  name: `commercetools-sdk-javascript-v2/${packageJson.version}`
1106
1082
  });
1107
1083
  return next => (request, response) => {
1108
- const requestWithUserAgent = { ...request,
1109
- headers: { ...request.headers,
1084
+ const requestWithUserAgent = {
1085
+ ...request,
1086
+ headers: {
1087
+ ...request.headers,
1110
1088
  'User-Agent': userAgent
1111
1089
  }
1112
1090
  };
@@ -1124,27 +1102,18 @@ const {
1124
1102
  class ClientBuilder {
1125
1103
  constructor() {
1126
1104
  _defineProperty(this, "projectKey", void 0);
1127
-
1128
1105
  _defineProperty(this, "authMiddleware", void 0);
1129
-
1130
1106
  _defineProperty(this, "httpMiddleware", void 0);
1131
-
1132
1107
  _defineProperty(this, "userAgentMiddleware", void 0);
1133
-
1134
1108
  _defineProperty(this, "correlationIdMiddleware", void 0);
1135
-
1136
1109
  _defineProperty(this, "loggerMiddleware", void 0);
1137
-
1138
1110
  _defineProperty(this, "queueMiddleware", void 0);
1139
-
1140
1111
  _defineProperty(this, "middlewares", []);
1141
1112
  }
1142
-
1143
1113
  withProjectKey(key) {
1144
1114
  this.projectKey = key;
1145
1115
  return this;
1146
1116
  }
1147
-
1148
1117
  defaultClient(baseUri, credentials, oauthUri, projectKey) {
1149
1118
  return this.withClientCredentialsFlow({
1150
1119
  host: oauthUri,
@@ -1155,17 +1124,14 @@ class ClientBuilder {
1155
1124
  fetch: fetch$1
1156
1125
  }).withLoggerMiddleware();
1157
1126
  }
1158
-
1159
1127
  withAuthMiddleware(authMiddleware) {
1160
1128
  this.authMiddleware = authMiddleware;
1161
1129
  return this;
1162
1130
  }
1163
-
1164
1131
  withMiddleware(middleware) {
1165
1132
  this.middlewares.push(middleware);
1166
1133
  return this;
1167
1134
  }
1168
-
1169
1135
  withClientCredentialsFlow(options) {
1170
1136
  return this.withAuthMiddleware(createAuthMiddlewareForClientCredentialsFlow({
1171
1137
  host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
@@ -1180,7 +1146,6 @@ class ClientBuilder {
1180
1146
  ...options
1181
1147
  }));
1182
1148
  }
1183
-
1184
1149
  withPasswordFlow(options) {
1185
1150
  return this.withAuthMiddleware(createAuthMiddlewareForPasswordFlow({
1186
1151
  host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
@@ -1197,7 +1162,6 @@ class ClientBuilder {
1197
1162
  ...options
1198
1163
  }));
1199
1164
  }
1200
-
1201
1165
  withAnonymousSessionFlow(options) {
1202
1166
  return this.withAuthMiddleware(createAuthMiddlewareForAnonymousSessionFlow({
1203
1167
  host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
@@ -1211,7 +1175,6 @@ class ClientBuilder {
1211
1175
  ...options
1212
1176
  }));
1213
1177
  }
1214
-
1215
1178
  withRefreshTokenFlow(options) {
1216
1179
  return this.withAuthMiddleware(createAuthMiddlewareForRefreshTokenFlow({
1217
1180
  host: options.host || 'https://auth.europe-west1.gcp.commercetools.com',
@@ -1225,14 +1188,12 @@ class ClientBuilder {
1225
1188
  ...options
1226
1189
  }));
1227
1190
  }
1228
-
1229
1191
  withExistingTokenFlow(authorization, options) {
1230
1192
  return this.withAuthMiddleware(createAuthMiddlewareWithExistingToken(authorization, {
1231
1193
  force: options.force || true,
1232
1194
  ...options
1233
1195
  }));
1234
1196
  }
1235
-
1236
1197
  withHttpMiddleware(options) {
1237
1198
  this.httpMiddleware = createHttpMiddleware({
1238
1199
  host: options.host || 'https://api.europe-west1.gcp.commercetools.com',
@@ -1241,12 +1202,10 @@ class ClientBuilder {
1241
1202
  });
1242
1203
  return this;
1243
1204
  }
1244
-
1245
1205
  withUserAgentMiddleware(options) {
1246
1206
  this.userAgentMiddleware = createUserAgentMiddleware(options);
1247
1207
  return this;
1248
1208
  }
1249
-
1250
1209
  withQueueMiddleware(options) {
1251
1210
  this.queueMiddleware = createQueueMiddleware({
1252
1211
  concurrency: options.concurrency || 20,
@@ -1254,12 +1213,10 @@ class ClientBuilder {
1254
1213
  });
1255
1214
  return this;
1256
1215
  }
1257
-
1258
1216
  withLoggerMiddleware() {
1259
1217
  this.loggerMiddleware = createLoggerMiddleware();
1260
1218
  return this;
1261
1219
  }
1262
-
1263
1220
  withCorrelationIdMiddleware(options) {
1264
1221
  this.correlationIdMiddleware = createCorrelationIdMiddleware({
1265
1222
  generate: options.generate || null,
@@ -1267,7 +1224,6 @@ class ClientBuilder {
1267
1224
  });
1268
1225
  return this;
1269
1226
  }
1270
-
1271
1227
  build() {
1272
1228
  const middlewares = this.middlewares.slice();
1273
1229
  if (this.correlationIdMiddleware) middlewares.push(this.correlationIdMiddleware);
@@ -1280,7 +1236,6 @@ class ClientBuilder {
1280
1236
  middlewares
1281
1237
  });
1282
1238
  }
1283
-
1284
1239
  }
1285
1240
 
1286
1241
  export { ClientBuilder, process$1 as Process, createAuthMiddlewareForAnonymousSessionFlow$1 as createAuthForAnonymousSessionFlow, createAuthMiddlewareForClientCredentialsFlow$1 as createAuthForClientCredentialsFlow, createAuthMiddlewareForPasswordFlow$1 as createAuthForPasswordFlow, createAuthMiddlewareForRefreshTokenFlow$1 as createAuthForRefreshTokenFlow, createAuthMiddlewareWithExistingToken$1 as createAuthWithExistingToken, createClient, createCorrelationIdMiddleware, createHttpMiddleware as createHttpClient, createLoggerMiddleware, createQueueMiddleware, createUserAgentMiddleware, getErrorByCode };