@commercetools/ts-client 2.1.0-alpha.0 → 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.
@@ -1,9 +1,7 @@
1
1
  import fetch$1 from 'node-fetch';
2
- import { v4 } from 'uuid';
3
- import { Buffer } from 'buffer/';
4
2
  import AbortController from 'abort-controller';
5
3
 
6
- function toPrimitive(t, r) {
4
+ function _toPrimitive(t, r) {
7
5
  if ("object" != typeof t || !t) return t;
8
6
  var e = t[Symbol.toPrimitive];
9
7
  if (void 0 !== e) {
@@ -14,24 +12,18 @@ function toPrimitive(t, r) {
14
12
  return ("string" === r ? String : Number)(t);
15
13
  }
16
14
 
17
- function toPropertyKey(t) {
18
- var i = toPrimitive(t, "string");
15
+ function _toPropertyKey(t) {
16
+ var i = _toPrimitive(t, "string");
19
17
  return "symbol" == typeof i ? i : i + "";
20
18
  }
21
19
 
22
- function _defineProperty(obj, key, value) {
23
- key = toPropertyKey(key);
24
- if (key in obj) {
25
- Object.defineProperty(obj, key, {
26
- value: value,
27
- enumerable: true,
28
- configurable: true,
29
- writable: true
30
- });
31
- } else {
32
- obj[key] = value;
33
- }
34
- return obj;
20
+ function _defineProperty(e, r, t) {
21
+ return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, {
22
+ value: t,
23
+ enumerable: !0,
24
+ configurable: !0,
25
+ writable: !0
26
+ }) : e[r] = t, e;
35
27
  }
36
28
 
37
29
  const HEADERS_CONTENT_TYPES = ['application/json', 'application/graphql'];
@@ -183,10 +175,12 @@ async function executor(request) {
183
175
  let _response = {};
184
176
  try {
185
177
  _response = await execute();
186
- if (_response.status > 399 && hasResponseRetryCode(retryCodes, _response)) return {
187
- _response,
188
- shouldRetry: true
189
- };
178
+ if (_response.status > 399 && hasResponseRetryCode(retryCodes, _response)) {
179
+ return {
180
+ _response,
181
+ shouldRetry: true
182
+ };
183
+ }
190
184
  } catch (e) {
191
185
  if (e.name.includes('AbortError') && retryWhenAborted) {
192
186
  return {
@@ -231,7 +225,7 @@ async function executor(request) {
231
225
  try {
232
226
  // try to parse the `fetch` response as text
233
227
  if (response.text && typeof response.text == 'function') {
234
- result = await response.text();
228
+ result = (await response.text()) || response[Object.getOwnPropertySymbols(response)[1]];
235
229
  data = JSON.parse(result);
236
230
  } else {
237
231
  // axios response
@@ -257,7 +251,8 @@ async function executor(request) {
257
251
  }
258
252
 
259
253
  function generateID() {
260
- return v4();
254
+ // @ts-ignore
255
+ return ([1e6] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c => (parseInt(c) ^ Math.floor(Math.random() * 256) & 15 >> parseInt(c) / 4).toString(16));
261
256
  }
262
257
 
263
258
  function parse(headers) {
@@ -446,16 +441,11 @@ function createUserAgent(options) {
446
441
  return [baseInfo, systemInfo, libraryInfo, contactInfo, customAgent].filter(Boolean).join(' ');
447
442
  }
448
443
 
449
- function responseCache() {
450
- let val;
451
- return {
452
- set(response) {
453
- val = response;
454
- },
455
- get() {
456
- return val;
457
- }
458
- };
444
+ function byteLength(body) {
445
+ if (typeof body === 'string') return body.length.toString();
446
+ if (body && typeof body === 'object') return new TextEncoder().encode(JSON.stringify(body)).length.toString();
447
+ if (body instanceof Uint8Array) return body.length.toString();
448
+ return '0';
459
449
  }
460
450
 
461
451
  /**
@@ -518,7 +508,8 @@ function buildRequestForClientCredentialsFlow(options) {
518
508
  } = options.credentials || {};
519
509
  if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
520
510
  const scope = options.scopes ? options.scopes.join(' ') : undefined;
521
- const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
511
+ const basicAuth = btoa(`${clientId}:${clientSecret}`);
512
+
522
513
  // This is mostly useful for internal testing purposes to be able to check
523
514
  // other oauth endpoints.
524
515
  const oauthUri = options.oauthUri || '/oauth/token';
@@ -564,9 +555,10 @@ function buildRequestForRefreshTokenFlow(options) {
564
555
  clientSecret
565
556
  } = options.credentials;
566
557
  if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
567
- const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
568
- // This is mostly useful for internal testing purposes to be able to check
569
- // other oauth endpoints.
558
+ const basicAuth = btoa(`${clientId}:${clientSecret}`);
559
+
560
+ // This is mostly useful for internal testing
561
+ // purposes to be able to check other oauth endpoints.
570
562
  const oauthUri = options.oauthUri || '/oauth/token';
571
563
  const url = options.host.replace(/\/$/, '') + oauthUri;
572
564
  const body = `grant_type=refresh_token&refresh_token=${encodeURIComponent(options.refreshToken)}`;
@@ -600,7 +592,7 @@ function buildRequestForPasswordFlow(options) {
600
592
  if (!(username && password)) throw new Error('Missing required user credentials (username, password)');
601
593
  const scope = (options.scopes || []).join(' ');
602
594
  const scopeStr = scope ? `&scope=${scope}` : '';
603
- const basicAuth = Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
595
+ const basicAuth = btoa(`${clientId}:${clientSecret}`);
604
596
 
605
597
  /**
606
598
  * This is mostly useful for internal testing purposes to be able to check
@@ -620,48 +612,16 @@ function buildRequestForPasswordFlow(options) {
620
612
 
621
613
  async function executeRequest$1(options) {
622
614
  const {
623
- request,
624
615
  httpClient,
625
616
  tokenCache,
626
- tokenCacheKey,
627
617
  userOption,
628
- tokenCacheObject,
629
- next
618
+ tokenCacheObject
630
619
  } = options;
631
620
  let url = options.url;
632
621
  let body = options.body;
633
622
  let basicAuth = options.basicAuth;
634
-
635
- // get the pending object from option
636
- // let pendingTasks: Array<Task> = options.pendingTasks
637
-
638
623
  if (!httpClient || typeof httpClient !== 'function') throw new Error('an `httpClient` is not available, please pass in a `fetch` or `axios` instance as an option or have them globally available.');
639
624
 
640
- /**
641
- * If there is a token in the tokenCache, and it's not
642
- * expired, append the token in the `Authorization` header.
643
- */
644
- // const tokenCacheObject = tokenCache.get(tokenCacheKey)
645
-
646
- // if (
647
- // tokenCacheObject && tokenCacheObject.token
648
- // && Date.now() < tokenCacheObject.expirationTime
649
- // ) {
650
- // return next(
651
- // mergeAuthHeader(
652
- // tokenCacheObject.token, request
653
- // )
654
- // );
655
- // }
656
-
657
- /**
658
- * Keep pending tasks until a token is fetched
659
- * Save next function as well, to call it once the token has been fetched, which prevents
660
- * unexpected behaviour in a context in which the next function uses global vars
661
- * or Promises to capture the token to hand it to other libraries, e.g. Apollo
662
- */
663
- // pendingTasks.push({ request, next })
664
-
665
625
  /**
666
626
  * use refreshToken flow if there is refresh-token
667
627
  * and there's either no token or the token is expired
@@ -692,7 +652,7 @@ async function executeRequest$1(options) {
692
652
  headers: {
693
653
  Authorization: `Basic ${basicAuth}`,
694
654
  'Content-Type': 'application/x-www-form-urlencoded',
695
- 'Content-Length': Buffer.byteLength(body).toString()
655
+ 'Content-Length': byteLength(body)
696
656
  },
697
657
  httpClient,
698
658
  body
@@ -713,74 +673,23 @@ async function executeRequest$1(options) {
713
673
  expirationTime,
714
674
  refreshToken
715
675
  });
716
-
717
- /**
718
- * Freeze and copy pending queue, reset
719
- * original one for accepting new pending tasks
720
- */
721
- // const requestQueue = pendingTasks.slice()
722
-
723
- // // reset pendingTask queue
724
- // pendingTasks = []
725
-
726
- // if (requestQueue.length === 1) {
727
- // return mergeAuthHeader(token, requestQueue.pop().request)
728
- // }
729
-
730
- // // execute all pending tasks if any
731
- // for (let i = 0; i < pendingTasks.length; i++) {
732
- // const task: Task = pendingTasks[i];
733
- // const requestWithAuth = mergeAuthHeader(token, task.request)
734
-
735
- // // execute task
736
- // // task.next(requestWithAuth)
737
-
738
- // pendingTasks[i].request = requestWithAuth;
739
- // }
740
-
741
- // return pendingTasks;
742
676
  return Promise.resolve(true);
743
677
  }
744
- const error = new Error(response.data.message ? response.data.message : JSON.stringify(response.data));
745
- /**
746
- * reject the error immediately
747
- * and free up the middleware chain
748
- */
749
- return request.reject({
750
- ...request,
751
- headers: {
752
- ...request.headers
753
- },
754
- response: {
755
- statusCode: response.statusCode || response.data.statusCode,
756
- error: {
757
- error,
758
- body: response
759
- }
760
- }
678
+
679
+ // bubble up the error for the catch block
680
+ throw createError({
681
+ code: response.data.error,
682
+ statusCode: response.data.statusCode,
683
+ message: response.data.message,
684
+ error: response.data.errors
761
685
  });
762
686
  } catch (error) {
763
- request.reject({
764
- ...request,
765
- headers: {
766
- ...request.headers
767
- },
768
- response: {
769
- body: null,
770
- statusCode: error.statusCode || 0,
771
- error: {
772
- ...response,
773
- error,
774
- body: response
775
- }
776
- }
777
- });
687
+ // throw error and free up the middleware chain
688
+ throw error;
778
689
  }
779
690
  }
780
691
 
781
692
  function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
782
- // const pendingTasks: Array<Task> = []
783
- // const requestState = new Mutex()
784
693
  const tokenCache = options.tokenCache || store({
785
694
  token: '',
786
695
  expirationTime: -1
@@ -795,6 +704,11 @@ function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
795
704
  // move on
796
705
  return next(request);
797
706
  }
707
+
708
+ /**
709
+ * If there is a token in the tokenCache, and it's not
710
+ * expired, append the token in the `Authorization` header.
711
+ */
798
712
  tokenCacheObject = tokenCache.get(tokenCacheKey);
799
713
  if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
800
714
  return next(mergeAuthHeader(tokenCacheObject.token, request));
@@ -802,8 +716,6 @@ function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
802
716
 
803
717
  // prepare request options
804
718
  const requestOptions = {
805
- // requestState,
806
- // pendingTasks,
807
719
  request,
808
720
  tokenCache,
809
721
  tokenCacheKey,
@@ -823,18 +735,14 @@ function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
823
735
  tokenFetchPromise = null;
824
736
  }
825
737
 
826
- // Now the token is present in the tokenCache
738
+ // Now the token is present in the tokenCache and can be accessed
827
739
  tokenCacheObject = tokenCache.get(tokenCacheKey);
828
- if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
829
- return next(mergeAuthHeader(tokenCacheObject.token, request));
830
- }
740
+ return next(mergeAuthHeader(tokenCacheObject.token, request));
831
741
  };
832
742
  };
833
743
  }
834
744
 
835
745
  function createAuthMiddlewareForClientCredentialsFlow$1(options) {
836
- // const requestState = new Mutex()
837
- // const pendingTasks: Array<Task> = []
838
746
  const tokenCache = options.tokenCache || store({
839
747
  token: '',
840
748
  expirationTime: -1
@@ -849,6 +757,11 @@ function createAuthMiddlewareForClientCredentialsFlow$1(options) {
849
757
  // move on
850
758
  return next(request);
851
759
  }
760
+
761
+ /**
762
+ * If there is a token in the tokenCache, and it's not
763
+ * expired, append the token in the `Authorization` header.
764
+ */
852
765
  tokenCacheObject = tokenCache.get(tokenCacheKey);
853
766
  if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
854
767
  return next(mergeAuthHeader(tokenCacheObject.token, request));
@@ -856,8 +769,6 @@ function createAuthMiddlewareForClientCredentialsFlow$1(options) {
856
769
 
857
770
  // prepare request options
858
771
  const requestOptions = {
859
- // requestState,
860
- // pendingTasks,
861
772
  request,
862
773
  tokenCache,
863
774
  tokenCacheKey,
@@ -879,9 +790,7 @@ function createAuthMiddlewareForClientCredentialsFlow$1(options) {
879
790
 
880
791
  // Now the token is present in the tokenCache
881
792
  tokenCacheObject = tokenCache.get(tokenCacheKey);
882
- if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
883
- return next(mergeAuthHeader(tokenCacheObject.token, request));
884
- }
793
+ return next(mergeAuthHeader(tokenCacheObject.token, request));
885
794
  };
886
795
  };
887
796
  }
@@ -922,12 +831,20 @@ function createAuthMiddlewareForPasswordFlow$1(options) {
922
831
  const tokenCacheKey = buildTokenCacheKey(options);
923
832
  return next => {
924
833
  return async request => {
834
+ // if here is a token in the header, then move on to the next middleware
925
835
  if (request.headers && (request.headers.Authorization || request.headers.authorization)) {
926
836
  return next(request);
927
837
  }
838
+
839
+ /**
840
+ * If there is a token in the tokenCache, and it's not
841
+ * expired, append the token in the `Authorization` header.
842
+ */
843
+ tokenCacheObject = tokenCache.get(tokenCacheKey);
844
+ if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
845
+ return next(mergeAuthHeader(tokenCacheObject.token, request));
846
+ }
928
847
  const requestOptions = {
929
- // requestState,
930
- // pendingTasks,
931
848
  request,
932
849
  tokenCache,
933
850
  tokenCacheKey,
@@ -949,9 +866,7 @@ function createAuthMiddlewareForPasswordFlow$1(options) {
949
866
 
950
867
  // Now the token is present in the tokenCache
951
868
  tokenCacheObject = tokenCache.get(tokenCacheKey);
952
- if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
953
- return next(mergeAuthHeader(tokenCacheObject.token, request));
954
- }
869
+ return next(mergeAuthHeader(tokenCacheObject.token, request));
955
870
  };
956
871
  };
957
872
  }
@@ -961,10 +876,6 @@ function createAuthMiddlewareForRefreshTokenFlow$1(options) {
961
876
  token: '',
962
877
  tokenCacheKey: null
963
878
  });
964
-
965
- // const pendingTasks: Array<Task> = []
966
- // const requestState = new Mutex()
967
-
968
879
  let tokenCacheObject;
969
880
  let tokenFetchPromise = null;
970
881
  const tokenCacheKey = buildTokenCacheKey(options);
@@ -974,10 +885,17 @@ function createAuthMiddlewareForRefreshTokenFlow$1(options) {
974
885
  return next(request);
975
886
  }
976
887
 
888
+ /**
889
+ * If there is a token in the tokenCache, and it's not
890
+ * expired, append the token in the `Authorization` header.
891
+ */
892
+ tokenCacheObject = tokenCache.get(tokenCacheKey);
893
+ if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
894
+ return next(mergeAuthHeader(tokenCacheObject.token, request));
895
+ }
896
+
977
897
  // prepare request options
978
898
  const requestOptions = {
979
- // pendingTasks,
980
- // requestState,
981
899
  request,
982
900
  tokenCache,
983
901
  httpClient: options.httpClient || fetch,
@@ -997,9 +915,7 @@ function createAuthMiddlewareForRefreshTokenFlow$1(options) {
997
915
 
998
916
  // Now the token is present in the tokenCache
999
917
  tokenCacheObject = tokenCache.get(tokenCacheKey);
1000
- if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
1001
- return next(mergeAuthHeader(tokenCacheObject.token, request));
1002
- }
918
+ return next(mergeAuthHeader(tokenCacheObject.token, request));
1003
919
  };
1004
920
  };
1005
921
  }
@@ -1007,7 +923,6 @@ function createAuthMiddlewareForRefreshTokenFlow$1(options) {
1007
923
  function createConcurrentModificationMiddleware$1(modifierFunction) {
1008
924
  return next => {
1009
925
  return async request => {
1010
- request['concurrent'] = true;
1011
926
  const response = await next(request);
1012
927
  if (response.statusCode == 409) {
1013
928
  /**
@@ -1015,11 +930,11 @@ function createConcurrentModificationMiddleware$1(modifierFunction) {
1015
930
  * from the error body and update
1016
931
  * request with the currentVersion
1017
932
  */
1018
- const version = response.error?.body?.errors?.[0]?.currentVersion;
933
+ const version = response.error.body?.errors?.[0]?.currentVersion;
1019
934
 
1020
935
  // update the resource version here
1021
936
  if (version) {
1022
- if (modifierFunction) {
937
+ if (modifierFunction && typeof modifierFunction == 'function') {
1023
938
  request.body = await modifierFunction(version, request, response);
1024
939
  } else {
1025
940
  request.body = typeof request.body == 'string' ? {
@@ -1030,18 +945,10 @@ function createConcurrentModificationMiddleware$1(modifierFunction) {
1030
945
  version
1031
946
  };
1032
947
  }
1033
- return next({
1034
- ...request,
1035
- response
1036
- });
948
+ return next(request);
1037
949
  }
1038
950
  }
1039
- request.continue = true;
1040
- delete request['concurrent'];
1041
- return next({
1042
- ...request,
1043
- response
1044
- });
951
+ return response;
1045
952
  };
1046
953
  };
1047
954
  }
@@ -1080,20 +987,12 @@ function createErrorMiddleware(options) {
1080
987
  };
1081
988
  }
1082
989
 
1083
- let result;
1084
- const cache = responseCache();
1085
990
  async function executeRequest({
1086
991
  url,
1087
992
  httpClient,
1088
993
  clientOptions
1089
994
  }) {
1090
995
  let timer;
1091
-
1092
- // don't make further api calls
1093
- if (clientOptions.request['continue']) {
1094
- delete clientOptions.request['continue'];
1095
- return cache.get();
1096
- }
1097
996
  const {
1098
997
  timeout,
1099
998
  request,
@@ -1120,22 +1019,19 @@ async function executeRequest({
1120
1019
  }
1121
1020
  if (response.statusCode >= 200 && response.statusCode < 300) {
1122
1021
  if (clientOptions.method == 'HEAD') {
1123
- const _result = {
1022
+ return {
1124
1023
  body: null,
1125
1024
  statusCode: response.statusCode,
1126
1025
  retryCount: response.retryCount,
1127
1026
  headers: getHeaders(response.headers)
1128
1027
  };
1129
- cache.set(_result);
1130
- return _result;
1131
1028
  }
1132
- result = {
1029
+ return {
1133
1030
  body: response.data,
1134
1031
  statusCode: response.statusCode,
1135
1032
  retryCount: response.retryCount,
1136
1033
  headers: getHeaders(response.headers)
1137
1034
  };
1138
- return result;
1139
1035
  }
1140
1036
  const error = createError({
1141
1037
  message: response?.data?.message || response?.message,
@@ -1155,18 +1051,17 @@ async function executeRequest({
1155
1051
  * handle non-ok (error) response
1156
1052
  * build error body
1157
1053
  */
1158
- result = {
1054
+ return {
1159
1055
  body: response.data,
1160
1056
  code: response.statusCode,
1161
1057
  statusCode: response.statusCode,
1162
1058
  headers: getHeaders(response.headers),
1163
1059
  error
1164
1060
  };
1165
- return result;
1166
1061
  } catch (e) {
1167
1062
  // We know that this is a network error
1168
1063
  const headers = includeResponseHeaders ? getHeaders(e.response?.headers) : null;
1169
- const statusCode = e.response?.status || e.response?.data || 0;
1064
+ const statusCode = e.response?.status || e.response?.data0 || 0;
1170
1065
  const message = e.response?.data?.message;
1171
1066
  const error = createError({
1172
1067
  statusCode,
@@ -1182,16 +1077,11 @@ async function executeRequest({
1182
1077
  uri: request.uri
1183
1078
  })
1184
1079
  });
1185
- result = {
1080
+ throw {
1186
1081
  body: error,
1187
1082
  error
1188
1083
  };
1189
- return result;
1190
1084
  } finally {
1191
- /**
1192
- * finally cache the response
1193
- */
1194
- cache.set(result);
1195
1085
  clearTimeout(timer);
1196
1086
  }
1197
1087
  }
@@ -1234,7 +1124,7 @@ function createHttpMiddleware$1(options) {
1234
1124
  // Ensure body is a string if content type is application/{json|graphql}
1235
1125
  const body = HEADERS_CONTENT_TYPES.indexOf(requestHeader['Content-Type']) > -1 && typeof request.body === 'string' || isBuffer(request.body) ? request.body : JSON.stringify(request.body || undefined);
1236
1126
  if (body && (typeof body === 'string' || isBuffer(body))) {
1237
- requestHeader['Content-Length'] = Buffer.byteLength(body).toString();
1127
+ requestHeader['Content-Length'] = byteLength(body);
1238
1128
  }
1239
1129
  const clientOptions = {
1240
1130
  enableRetry,
@@ -1267,9 +1157,6 @@ function createHttpMiddleware$1(options) {
1267
1157
  clientOptions,
1268
1158
  httpClient
1269
1159
  });
1270
- if (request['concurrent']) {
1271
- return response;
1272
- }
1273
1160
  const responseWithRequest = {
1274
1161
  ...request,
1275
1162
  includeOriginalRequest,
@@ -1302,48 +1189,56 @@ function createQueueMiddleware$1({
1302
1189
  }) {
1303
1190
  let runningCount = 0;
1304
1191
  const queue = [];
1305
- const dequeue = next => {
1192
+ const waitForSlot = () => {
1193
+ if (0 >= concurrency) return Promise.resolve();
1194
+ return new Promise(resolve => {
1195
+ const tryNext = () => {
1196
+ if (runningCount < concurrency) {
1197
+ runningCount++;
1198
+ resolve();
1199
+ } else {
1200
+ queue.push(tryNext);
1201
+ }
1202
+ };
1203
+ tryNext();
1204
+ });
1205
+ };
1206
+
1207
+ // Function to free up a slot after a request is completed
1208
+ const freeSlot = () => {
1306
1209
  runningCount--;
1307
- if (queue.length && runningCount <= concurrency) {
1308
- const nextTask = queue.shift();
1309
- runningCount++;
1310
- return next(nextTask.request);
1210
+ if (queue.length > 0) {
1211
+ const nextInQueue = queue.shift();
1212
+ if (nextInQueue) {
1213
+ nextInQueue();
1214
+ }
1311
1215
  }
1312
1216
  };
1313
- const enqueue = ({
1314
- request
1315
- }) => queue.push({
1316
- request
1317
- });
1318
1217
  return next => request => {
1319
- // wrap and override resolve and reject functions
1320
- const patchedRequest = {
1321
- ...request,
1322
- resolve(data) {
1323
- request.resolve(data);
1324
- dequeue(next);
1325
- },
1326
- reject(error) {
1327
- request.reject(error);
1328
- dequeue(next);
1329
- }
1330
- };
1218
+ return waitForSlot().then(() => {
1219
+ const patchedRequest = {
1220
+ ...request,
1221
+ resolve(data) {
1222
+ request.resolve(data);
1223
+ freeSlot();
1224
+ },
1225
+ reject(error) {
1226
+ request.reject(error);
1227
+ freeSlot();
1228
+ }
1229
+ };
1331
1230
 
1332
- // enqueue requests
1333
- enqueue({
1334
- request: patchedRequest
1231
+ // Process the next middleware
1232
+ return next(patchedRequest).finally(() => {
1233
+ freeSlot();
1234
+ });
1335
1235
  });
1336
- if (runningCount < concurrency) {
1337
- runningCount++;
1338
- const nextTask = queue.shift();
1339
- return next(nextTask.request);
1340
- }
1341
1236
  };
1342
1237
  }
1343
1238
 
1344
1239
  var packageJson = {
1345
1240
  name: "@commercetools/ts-client",
1346
- version: "2.1.0-alpha.0",
1241
+ version: "2.1.0",
1347
1242
  engines: {
1348
1243
  node: ">=14"
1349
1244
  },
@@ -1377,16 +1272,11 @@ var packageJson = {
1377
1272
  },
1378
1273
  dependencies: {
1379
1274
  "abort-controller": "3.0.0",
1380
- buffer: "^6.0.3",
1381
- "node-fetch": "^2.6.1",
1382
- uuid: "10.0.0"
1275
+ "node-fetch": "^2.6.1"
1383
1276
  },
1384
1277
  files: [
1385
1278
  "dist",
1386
- "CHANGELOG.md",
1387
- "LICENSE",
1388
- "README.md",
1389
- "package.json"
1279
+ "CHANGELOG.md"
1390
1280
  ],
1391
1281
  author: "Chukwuemeka Ajima <meeky.ae@gmail.com>",
1392
1282
  main: "dist/commercetools-ts-client.cjs.js",
@@ -1541,6 +1431,7 @@ function process$1(request, fn, processOpt) {
1541
1431
  function createClient(middlewares) {
1542
1432
  _options = middlewares;
1543
1433
  validateClient(middlewares);
1434
+ let _maskSensitiveHeaderData = false;
1544
1435
  const resolver = {
1545
1436
  async resolve(rs) {
1546
1437
  const {
@@ -1553,25 +1444,20 @@ function createClient(middlewares) {
1553
1444
  retryCount,
1554
1445
  ...rest
1555
1446
  } = response;
1556
- // _maskSensitiveHeaderData = maskSensitiveHeaderData
1557
-
1447
+ _maskSensitiveHeaderData = maskSensitiveHeaderData;
1558
1448
  const res = {
1559
1449
  body: null,
1560
1450
  error: null,
1561
1451
  reject: rs.reject,
1562
1452
  resolve: rs.resolve,
1563
1453
  ...rest,
1454
+ ...(includeOriginalRequest ? {
1455
+ originalRequest: request
1456
+ } : {}),
1564
1457
  ...(response?.retryCount ? {
1565
1458
  retryCount: response.retryCount
1566
- } : {}),
1567
- ...(includeOriginalRequest ? {
1568
- originalRequest: maskSensitiveHeaderData ? maskAuthData(request) : request
1569
1459
  } : {})
1570
1460
  };
1571
- if (res.error) {
1572
- rs.reject(res.error);
1573
- }
1574
- rs.resolve(res);
1575
1461
  return res;
1576
1462
  }
1577
1463
  };
@@ -1581,11 +1467,20 @@ function createClient(middlewares) {
1581
1467
  execute(request) {
1582
1468
  validate('exec', request);
1583
1469
  return new Promise(async (resolve, reject) => {
1584
- return dispatch({
1585
- reject,
1586
- resolve,
1587
- ...request
1588
- });
1470
+ try {
1471
+ const response = await dispatch({
1472
+ reject,
1473
+ resolve,
1474
+ ...request
1475
+ });
1476
+ if (response.error) return reject(response.error);
1477
+ if (response.originalRequest && _maskSensitiveHeaderData) {
1478
+ response.originalRequest = maskAuthData(response.originalRequest);
1479
+ }
1480
+ resolve(response);
1481
+ } catch (err) {
1482
+ reject(err);
1483
+ }
1589
1484
  });
1590
1485
  }
1591
1486
  };