@commercetools/ts-client 0.0.0-beta.9 → 1.0.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.
Files changed (49) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/LICENSE +1 -1
  3. package/dist/commercetools-ts-client.browser.cjs.js +1643 -0
  4. package/dist/commercetools-ts-client.browser.esm.js +1620 -0
  5. package/dist/commercetools-ts-client.cjs.d.ts +1 -11
  6. package/dist/commercetools-ts-client.cjs.dev.js +1643 -0
  7. package/dist/commercetools-ts-client.cjs.js +6 -15
  8. package/dist/commercetools-ts-client.cjs.prod.js +1643 -0
  9. package/dist/commercetools-ts-client.esm.js +1620 -0
  10. package/dist/declarations/src/client/builder.d.ts +31 -0
  11. package/dist/declarations/src/client/client.d.ts +3 -0
  12. package/dist/declarations/src/client/index.d.ts +3 -0
  13. package/dist/declarations/src/index.d.ts +12 -0
  14. package/dist/declarations/src/middleware/auth-middleware/anonymous-session-flow.d.ts +2 -0
  15. package/dist/declarations/src/middleware/auth-middleware/auth-request-builder.d.ts +24 -0
  16. package/dist/declarations/src/middleware/auth-middleware/auth-request-executor.d.ts +2 -0
  17. package/dist/declarations/src/middleware/auth-middleware/client-credentials-flow.d.ts +2 -0
  18. package/dist/declarations/src/middleware/auth-middleware/existing-token-flow.d.ts +2 -0
  19. package/dist/declarations/src/middleware/auth-middleware/index.d.ts +6 -0
  20. package/dist/declarations/src/middleware/auth-middleware/password-flow.d.ts +2 -0
  21. package/dist/declarations/src/middleware/auth-middleware/refresh-token-flow.d.ts +2 -0
  22. package/dist/declarations/src/middleware/create-concurrent-modification-middleware.d.ts +2 -0
  23. package/dist/declarations/src/middleware/create-correlation-id-middleware.d.ts +2 -0
  24. package/dist/declarations/src/middleware/create-error-middleware.d.ts +2 -0
  25. package/dist/declarations/src/middleware/create-http-middleware.d.ts +2 -0
  26. package/dist/declarations/src/middleware/create-logger-middleware.d.ts +2 -0
  27. package/dist/declarations/src/middleware/create-queue-middleware.d.ts +2 -0
  28. package/dist/declarations/src/middleware/create-user-agent-middleware.d.ts +2 -0
  29. package/dist/declarations/src/middleware/index.d.ts +8 -0
  30. package/dist/declarations/src/types/types.d.ts +329 -0
  31. package/dist/declarations/src/utils/constants.d.ts +5 -0
  32. package/dist/declarations/src/utils/createError.d.ts +8 -0
  33. package/dist/declarations/src/utils/errors.d.ts +10 -0
  34. package/dist/declarations/src/utils/executor.d.ts +2 -0
  35. package/dist/declarations/src/utils/generateID.d.ts +1 -0
  36. package/dist/declarations/src/utils/headers.d.ts +2 -0
  37. package/dist/declarations/src/utils/index.d.ts +17 -0
  38. package/dist/declarations/src/utils/isBuffer.d.ts +1 -0
  39. package/dist/declarations/src/utils/maskAuthData.d.ts +2 -0
  40. package/dist/declarations/src/utils/mergeAuthHeader.d.ts +2 -0
  41. package/dist/declarations/src/utils/methods.d.ts +2 -0
  42. package/dist/declarations/src/utils/retryDelay.d.ts +8 -0
  43. package/dist/declarations/src/utils/sleep.d.ts +1 -0
  44. package/dist/declarations/src/utils/tokenCacheKey.d.ts +2 -0
  45. package/dist/declarations/src/utils/tokenExpirationTime.d.ts +1 -0
  46. package/dist/declarations/src/utils/tokenStore.d.ts +2 -0
  47. package/dist/declarations/src/utils/userAgent.d.ts +2 -0
  48. package/dist/declarations/src/utils/validate.d.ts +25 -0
  49. package/package.json +4 -4
@@ -0,0 +1,1643 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var qs = require('querystring');
6
+ var crytpo = require('crypto');
7
+ var fetch$1 = require('node-fetch');
8
+ var _ = require('buffer/');
9
+ var AbortController = require('abort-controller');
10
+
11
+ function _interopDefault (e) { return e && e.__esModule ? e : { 'default': e }; }
12
+
13
+ var qs__default = /*#__PURE__*/_interopDefault(qs);
14
+ var crytpo__default = /*#__PURE__*/_interopDefault(crytpo);
15
+ var fetch__default = /*#__PURE__*/_interopDefault(fetch$1);
16
+ var AbortController__default = /*#__PURE__*/_interopDefault(AbortController);
17
+
18
+ const HEADERS_CONTENT_TYPES = ['application/json', 'application/graphql'];
19
+ const CONCURRENCT_REQUEST = 20;
20
+ const CTP_API_URL = 'https://api.europe-west1.gcp.commercetools.com';
21
+ const CTP_AUTH_URL = 'https://auth.europe-west1.gcp.commercetools.com';
22
+ const DEFAULT_HEADERS = ['content-type', 'access-control-allow-origin', 'access-control-allow-headers', 'access-control-allow-methods', 'access-control-expose-headers', 'access-control-max-ag', 'x-correlation-id', 'server-timing', 'date', 'server', 'transfer-encoding', 'access-control-max-age', 'content-encoding', 'x-envoy-upstream-service-time', 'via', 'alt-svc', 'connection'];
23
+
24
+ function parse(headers) {
25
+ return DEFAULT_HEADERS.reduce((result, key) => {
26
+ let val = headers[key] ? headers[key] : typeof headers.get == 'function' ? headers.get(key) : null;
27
+ if (val) result[key] = val;
28
+ return result;
29
+ }, {});
30
+ }
31
+ function getHeaders(headers) {
32
+ if (!headers) return null;
33
+
34
+ // node-fetch
35
+ if (headers.raw && typeof headers.raw == 'function') return headers.raw();
36
+
37
+ // Tmp fix for Firefox until it supports iterables
38
+ if (!headers.forEach) return parse(headers);
39
+ return headers.forEach((value, name) => value);
40
+ }
41
+
42
+ function isBuffer(obj) {
43
+ return obj != null && obj.constructor != null && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj);
44
+ }
45
+
46
+ function calculateRetryDelay({
47
+ retryCount,
48
+ retryDelay,
49
+ // maxRetries,
50
+ backoff,
51
+ maxDelay
52
+ }) {
53
+ if (backoff) {
54
+ return retryCount !== 0 // do not increase if it's the first retry
55
+ ? Math.min(Math.round((Math.random() + 1) * retryDelay * 2 ** retryCount), maxDelay) : retryDelay;
56
+ }
57
+ return retryDelay;
58
+ }
59
+
60
+ // TODO: Polyfill crypto for browsers
61
+ function generateID() {
62
+ return crytpo__default["default"].randomBytes(32).toString('base64').replace(/[\/\-=+]/gi, '');
63
+ }
64
+
65
+ // import { validateUserAgentOptions } from '../utils'
66
+
67
+ /*
68
+ This is the easiest way, for this use case, to detect if we're running in
69
+ Node.js or in a browser environment. In other cases, this won't be even a
70
+ problem as Rollup will provide the correct polyfill in the bundle.
71
+ The main advantage by doing it this way is that it allows to easily test
72
+ the code running in both environments, by overriding `global.window` in
73
+ the specific test.
74
+ */
75
+ const isBrowser = () => typeof window !== 'undefined' && window.document && window.document.nodeType === 9;
76
+ function getSystemInfo() {
77
+ var _process;
78
+ if (isBrowser()) return window.navigator.userAgent;
79
+ const nodeVersion = ((_process = process) === null || _process === void 0 ? void 0 : _process.version.slice(1)) || 'unknow'; // unknow environment like React Native etc
80
+ const platformInfo = `(${process.platform}; ${process.arch})`;
81
+
82
+ // return `node.js/${nodeVersion}`
83
+ return `node.js/${nodeVersion} ${platformInfo}`;
84
+ }
85
+ function createUserAgent(options) {
86
+ let libraryInfo = null;
87
+ let contactInfo = null;
88
+
89
+ // validateUserAgentOptions(options)
90
+ if (!options) {
91
+ throw new Error('Missing required option `name`');
92
+ }
93
+
94
+ // Main info
95
+ const baseInfo = options.version ? `${options.name}/${options.version}` : options.name;
96
+
97
+ // Library info
98
+ if (options.libraryName && !options.libraryVersion) {
99
+ libraryInfo = options.libraryName;
100
+ } else if (options.libraryName && options.libraryVersion) {
101
+ libraryInfo = `${options.libraryName}/${options.libraryVersion}`;
102
+ }
103
+
104
+ // Contact info
105
+ if (options.contactUrl && !options.contactEmail) {
106
+ contactInfo = `(+${options.contactUrl})`;
107
+ } else if (!options.contactUrl && options.contactEmail) {
108
+ contactInfo = `(+${options.contactEmail})`;
109
+ } else if (options.contactUrl && options.contactEmail) {
110
+ contactInfo = `(+${options.contactUrl}; +${options.contactEmail})`;
111
+ }
112
+
113
+ // System info
114
+ const systemInfo = getSystemInfo();
115
+
116
+ // customName
117
+ const customAgent = options.customAgent || '';
118
+ return [baseInfo, systemInfo, libraryInfo, contactInfo, customAgent].filter(Boolean).join(' ');
119
+ }
120
+
121
+ function maskAuthData(request) {
122
+ const _request = Object.assign({}, request);
123
+ if (_request !== null && _request !== void 0 && _request.headers) {
124
+ if (_request.headers.Authorization) {
125
+ _request.headers['Authorization'] = 'Bearer ********';
126
+ }
127
+ if (_request.headers.authorization) {
128
+ _request.headers['authorization'] = 'Bearer ********';
129
+ }
130
+ }
131
+ return _request;
132
+ }
133
+
134
+ function calculateExpirationTime(expiresIn) {
135
+ return Date.now() +
136
+ // Add a gap of 5 minutes before expiration time.
137
+ expiresIn * 1000 - 5 * 60 * 1000;
138
+ }
139
+
140
+ function buildTokenCacheKey(options) {
141
+ var _options$credentials;
142
+ if (!(options !== null && options !== void 0 && (_options$credentials = options.credentials) !== null && _options$credentials !== void 0 && _options$credentials.clientId) || !options.projectKey || !options.host) throw new Error('Missing required options.');
143
+ return {
144
+ clientId: options.credentials.clientId,
145
+ host: options.host,
146
+ projectKey: options.projectKey
147
+ };
148
+ }
149
+
150
+ function store(initVal) {
151
+ let value = initVal;
152
+ return {
153
+ get: TokenCacheOption => value,
154
+ set: (val, TokenCacheOption) => {
155
+ value = val;
156
+ }
157
+ };
158
+ }
159
+
160
+ function mergeAuthHeader(token, req) {
161
+ return {
162
+ ...req,
163
+ headers: {
164
+ ...req.headers,
165
+ Authorization: `Bearer ${token}`
166
+ }
167
+ };
168
+ }
169
+
170
+ function predicate(retryCodes, response) {
171
+ return !
172
+ // retryCodes.includes(response?.error?.message) ||
173
+ [503, ...retryCodes].includes((response === null || response === void 0 ? void 0 : response.status) || (response === null || response === void 0 ? void 0 : response.statusCode));
174
+ }
175
+ async function executeHttpClientRequest(fetcher, config) {
176
+ async function sendRequest() {
177
+ const response = await fetcher({
178
+ ...config,
179
+ headers: {
180
+ ...config.headers
181
+ }
182
+ });
183
+
184
+ // validations and error handlings can also be done here
185
+ return response;
186
+ }
187
+
188
+ // Attempt to send the request.
189
+ return sendRequest().catch(error => Promise.reject(error));
190
+ }
191
+ async function executor(request) {
192
+ const {
193
+ url,
194
+ httpClient,
195
+ ...rest
196
+ } = request;
197
+ const data = await executeHttpClientRequest(async options => {
198
+ const {
199
+ enableRetry,
200
+ retryConfig
201
+ } = rest;
202
+ const {
203
+ retryCodes = [],
204
+ maxDelay = Infinity,
205
+ maxRetries = 3,
206
+ backoff = true,
207
+ retryDelay = 200
208
+ } = retryConfig || {};
209
+ let result,
210
+ data,
211
+ retryCount = 0;
212
+
213
+ // validate the `retryCodes` option
214
+ validateRetryCodes(retryCodes);
215
+ async function execute() {
216
+ return httpClient(url, {
217
+ ...rest,
218
+ ...options,
219
+ headers: {
220
+ ...rest.headers,
221
+ ...options.headers,
222
+ // axios header encoding
223
+ 'Accept-Encoding': 'application/json'
224
+ },
225
+ // for axios
226
+ ...(rest.body ? {
227
+ data: rest.body
228
+ } : {}),
229
+ withCredentials: options.credentialsMode === 'include'
230
+ });
231
+ }
232
+ async function executeWithRetry() {
233
+ // first attempt
234
+ let _response = await execute();
235
+ if (predicate(retryCodes, _response)) return _response;
236
+
237
+ // retry attempts
238
+ while (enableRetry && retryCount < maxRetries) {
239
+ retryCount++;
240
+ _response = await execute();
241
+ if (predicate(retryCodes, _response)) return _response;
242
+
243
+ // delay next execution
244
+ const timer = calculateRetryDelay({
245
+ retryCount,
246
+ retryDelay,
247
+ maxRetries,
248
+ backoff,
249
+ maxDelay
250
+ });
251
+ await sleep(timer);
252
+ }
253
+ return _response;
254
+ }
255
+ const response = await executeWithRetry();
256
+ try {
257
+ // try to parse the `fetch` response as text
258
+ if (response.text && typeof response.text == 'function') {
259
+ result = await response.text();
260
+ data = JSON.parse(result);
261
+ } else {
262
+ // axios response
263
+ data = response.data || response;
264
+ }
265
+ } catch (err) {
266
+ data = result;
267
+ }
268
+ return {
269
+ data,
270
+ retryCount,
271
+ statusCode: response.status || response.statusCode || data.statusCode,
272
+ headers: response.headers
273
+ };
274
+ },
275
+ /**
276
+ * get this object from the
277
+ * middleware options or from
278
+ * http client config
279
+ */
280
+ {});
281
+ return data;
282
+ }
283
+
284
+ function sleep(ms) {
285
+ return new Promise(resolve => {
286
+ setTimeout(resolve, ms);
287
+ });
288
+ }
289
+
290
+ var METHODS = ['ACL', 'BIND', 'CHECKOUT', 'CONNECT', 'COPY', 'DELETE', 'GET', 'HEAD', 'LINK', 'LOCK', 'M-SEARCH', 'MERGE', 'MKACTIVITY', 'MKCALENDAR', 'MKCOL', 'MOVE', 'NOTIFY', 'OPTIONS', 'PATCH', 'POST', 'PROPFIND', 'PROPPATCH', 'PURGE', 'PUT', 'REBIND', 'REPORT', 'SEARCH', 'SOURCE', 'SUBSCRIBE', 'TRACE', 'UNBIND', 'UNLINK', 'UNLOCK', 'UNSUBSCRIBE'];
291
+
292
+ function DefineError(statusCode, message, meta = {}) {
293
+ // eslint-disable-next-line no-multi-assign
294
+ this.status = this.statusCode = this.code = statusCode;
295
+ this.message = message;
296
+ Object.assign(this, meta);
297
+ this.name = this.constructor.name;
298
+ // eslint-disable-next-line no-proto
299
+ this.constructor.prototype.__proto__ = Error.prototype;
300
+ if (Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
301
+ }
302
+ function NetworkError(...args) {
303
+ DefineError.call(this, 0, ...args);
304
+ }
305
+ function HttpError(...args) {
306
+ DefineError.call(this, ...args);
307
+ }
308
+ function BadRequest(...args) {
309
+ DefineError.call(this, 400, ...args);
310
+ }
311
+ function Unauthorized(...args) {
312
+ DefineError.call(this, 401, ...args);
313
+ }
314
+ function Forbidden(...args) {
315
+ DefineError.call(this, 403, ...args);
316
+ }
317
+ function NotFound(...args) {
318
+ DefineError.call(this, 404, ...args);
319
+ }
320
+ function ConcurrentModification(...args) {
321
+ DefineError.call(this, 409, ...args);
322
+ }
323
+ function InternalServerError(...args) {
324
+ DefineError.call(this, 500, ...args);
325
+ }
326
+ function ServiceUnavailable(...args) {
327
+ DefineError.call(this, 503, ...args);
328
+ }
329
+ function getErrorByCode(code) {
330
+ switch (code) {
331
+ case 0:
332
+ return NetworkError;
333
+ case 400:
334
+ return BadRequest;
335
+ case 401:
336
+ return Unauthorized;
337
+ case 403:
338
+ return Forbidden;
339
+ case 404:
340
+ return NotFound;
341
+ case 409:
342
+ return ConcurrentModification;
343
+ case 500:
344
+ return InternalServerError;
345
+ case 503:
346
+ return ServiceUnavailable;
347
+ default:
348
+ return undefined;
349
+ }
350
+ }
351
+
352
+ function createError({
353
+ statusCode,
354
+ message,
355
+ ...rest
356
+ }) {
357
+ var _rest$originalRequest;
358
+ let errorMessage = message || 'Unexpected non-JSON error response';
359
+ if (statusCode === 404) errorMessage = `URI not found: ${((_rest$originalRequest = rest.originalRequest) === null || _rest$originalRequest === void 0 ? void 0 : _rest$originalRequest.uri) || rest.uri}`;
360
+ const ResponseError = getErrorByCode(statusCode);
361
+ if (ResponseError) return new ResponseError(errorMessage, rest);
362
+ return new HttpError(statusCode, errorMessage, rest);
363
+ }
364
+
365
+ /**
366
+ * validate some essential http options
367
+ * @param options
368
+ */
369
+ function validateHttpOptions(options) {
370
+ if (!options.host) throw new Error('Request `host` or `url` is missing or invalid, please pass in a valid host e.g `host: http://a-valid-host-url`');
371
+ if (!options.httpClient && typeof options.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.');
372
+ if (options.timeout && !options.getAbortController) throw new Error('`AbortController` is not available. Please pass in `getAbortController` as an option or have AbortController globally available when using timeout.');
373
+ }
374
+
375
+ /**
376
+ *
377
+ * @param retryCodes
378
+ * @example
379
+ * const retryCodes = [500, 504, "ETIMEDOUT"]
380
+ */
381
+ function validateRetryCodes(retryCodes) {
382
+ if (!Array.isArray(retryCodes)) {
383
+ throw new Error('`retryCodes` option must be an array of retry status (error) codes and/or messages.');
384
+ }
385
+ }
386
+
387
+ /**
388
+ * @param options
389
+ */
390
+ function validateClient(options) {
391
+ if (!options) throw new Error('Missing required options');
392
+ if (options.middlewares && !Array.isArray(options.middlewares)) throw new Error('Middlewares should be an array');
393
+ if (!options.middlewares || !Array.isArray(options.middlewares) || !options.middlewares.length) {
394
+ throw new Error('You need to provide at least one middleware');
395
+ }
396
+ }
397
+
398
+ /**
399
+ * @param options
400
+ */
401
+ function validate(funcName, request, options = {
402
+ allowedMethods: METHODS
403
+ }) {
404
+ if (!request) throw new Error(`The "${funcName}" function requires a "Request" object as an argument. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);
405
+ if (typeof request.uri !== 'string') throw new Error(`The "${funcName}" Request object requires a valid uri. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);
406
+ if (!options.allowedMethods.includes(request.method)) throw new Error(`The "${funcName}" Request object requires a valid method. See https://commercetools.github.io/nodejs/sdk/Glossary.html#clientrequest`);
407
+ }
408
+
409
+ function compose({
410
+ middlewares
411
+ }) {
412
+ if (middlewares.length === 1) return middlewares[0];
413
+ const _middlewares = middlewares.slice();
414
+ return _middlewares.reduce((ac, cv) => (...args) => ac(cv.apply(null, args)));
415
+ }
416
+
417
+ // process batch requests
418
+ let _options;
419
+ function process$1(request, fn, processOpt) {
420
+ validate('process', request, {
421
+ allowedMethods: ['GET']
422
+ });
423
+ 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');
424
+
425
+ // Set default process options
426
+ const opt = {
427
+ total: Number.POSITIVE_INFINITY,
428
+ accumulate: true,
429
+ ...processOpt
430
+ };
431
+ return new Promise((resolve, reject) => {
432
+ let _path,
433
+ _queryString = '';
434
+ if (request && request.uri) {
435
+ const [path, queryString] = request.uri.split('?');
436
+ _path = path;
437
+ _queryString = queryString;
438
+ }
439
+ const requestQuery = {
440
+ ...qs__default["default"].parse(_queryString)
441
+ };
442
+ const query = {
443
+ // defaults
444
+ limit: 20,
445
+ // merge given query params
446
+ ...requestQuery
447
+ };
448
+ let itemsToGet = opt.total;
449
+ let hasFirstPageBeenProcessed = false;
450
+ const processPage = async (lastId, acc = []) => {
451
+ // Use the lesser value between limit and itemsToGet in query
452
+ const limit = query.limit < itemsToGet ? query.limit : itemsToGet;
453
+ const originalQueryString = qs__default["default"].stringify({
454
+ ...query,
455
+ limit
456
+ });
457
+ const enhancedQuery = {
458
+ sort: 'id asc',
459
+ withTotal: false,
460
+ ...(lastId ? {
461
+ where: `id > "${lastId}"`
462
+ } : {})
463
+ };
464
+ const enhancedQueryString = qs__default["default"].stringify(enhancedQuery);
465
+ const enhancedRequest = {
466
+ ...request,
467
+ uri: `${_path}?${enhancedQueryString}&${originalQueryString}`
468
+ };
469
+ try {
470
+ const payload = await createClient(_options).execute(enhancedRequest);
471
+ const {
472
+ results,
473
+ count: resultsLength
474
+ } = (payload === null || payload === void 0 ? void 0 : payload.body) || {};
475
+ if (!resultsLength && hasFirstPageBeenProcessed) {
476
+ return resolve(acc || []);
477
+ }
478
+ const result = await Promise.resolve(fn(payload));
479
+ let accumulated;
480
+ hasFirstPageBeenProcessed = true;
481
+ if (opt.accumulate) accumulated = acc.concat(result || []);
482
+ itemsToGet -= resultsLength;
483
+ // If there are no more items to get, it means the total number
484
+ // of items in the original request have been fetched so we
485
+ // resolve the promise.
486
+ // Also, if we get less results in a page then the limit set it
487
+ // means that there are no more pages and that we can finally
488
+ // resolve the promise.
489
+ if (resultsLength < query.limit || !itemsToGet) {
490
+ return resolve(accumulated || []);
491
+ }
492
+ const last = results[resultsLength - 1];
493
+ const newLastId = last && last.id;
494
+ processPage(newLastId, accumulated);
495
+ } catch (error) {
496
+ reject(error);
497
+ }
498
+ };
499
+
500
+ // Start iterating through pages
501
+ processPage();
502
+ });
503
+ }
504
+ function createClient(middlewares) {
505
+ _options = middlewares;
506
+ validateClient(middlewares);
507
+ const resolver = {
508
+ async resolve(rs) {
509
+ const {
510
+ response,
511
+ includeOriginalRequest,
512
+ maskSensitiveHeaderData,
513
+ ...request
514
+ } = rs;
515
+ const {
516
+ retryCount,
517
+ ...rest
518
+ } = response;
519
+ const res = {
520
+ body: null,
521
+ error: null,
522
+ reject: rs.reject,
523
+ resolve: rs.resolve,
524
+ ...rest,
525
+ ...(includeOriginalRequest ? {
526
+ originalRequest: maskSensitiveHeaderData ? maskAuthData(request) : request
527
+ } : {}),
528
+ ...(response !== null && response !== void 0 && response.retryCount ? {
529
+ retryCount: response.retryCount
530
+ } : {})
531
+ };
532
+ if (res.error) {
533
+ res.reject(res.error);
534
+ return res;
535
+ }
536
+ res.resolve(res);
537
+ return res;
538
+ }
539
+ };
540
+ const dispatch = compose(middlewares)(resolver.resolve);
541
+ return {
542
+ process: process$1,
543
+ execute(request) {
544
+ validate('exec', request);
545
+ return new Promise((resolve, reject) => {
546
+ return dispatch({
547
+ reject,
548
+ resolve,
549
+ ...request
550
+ });
551
+ });
552
+ }
553
+ };
554
+ }
555
+
556
+ function _toPrimitive(input, hint) {
557
+ if (typeof input !== "object" || input === null) return input;
558
+ var prim = input[Symbol.toPrimitive];
559
+ if (prim !== undefined) {
560
+ var res = prim.call(input, hint || "default");
561
+ if (typeof res !== "object") return res;
562
+ throw new TypeError("@@toPrimitive must return a primitive value.");
563
+ }
564
+ return (hint === "string" ? String : Number)(input);
565
+ }
566
+
567
+ function _toPropertyKey(arg) {
568
+ var key = _toPrimitive(arg, "string");
569
+ return typeof key === "symbol" ? key : String(key);
570
+ }
571
+
572
+ function _defineProperty(obj, key, value) {
573
+ key = _toPropertyKey(key);
574
+ if (key in obj) {
575
+ Object.defineProperty(obj, key, {
576
+ value: value,
577
+ enumerable: true,
578
+ configurable: true,
579
+ writable: true
580
+ });
581
+ } else {
582
+ obj[key] = value;
583
+ }
584
+ return obj;
585
+ }
586
+
587
+ function createCorrelationIdMiddleware$1(options) {
588
+ return next => request => {
589
+ const nextRequest = {
590
+ ...request,
591
+ headers: {
592
+ ...request.headers,
593
+ 'X-Correlation-ID': options.generate && typeof options.generate == 'function' ? options.generate() : generateID()
594
+ }
595
+ };
596
+ return next(nextRequest);
597
+ };
598
+ }
599
+
600
+ async function executeRequest$1({
601
+ url,
602
+ httpClient,
603
+ clientOptions
604
+ }) {
605
+ let timer;
606
+ const {
607
+ timeout,
608
+ request,
609
+ abortController,
610
+ maskSensitiveHeaderData,
611
+ includeRequestInErrorResponse
612
+ } = clientOptions;
613
+ try {
614
+ var _response$data, _response$data2;
615
+ if (timeout) timer = setTimeout(() => {
616
+ abortController.abort();
617
+ }, timeout);
618
+ const response = await executor({
619
+ url,
620
+ ...clientOptions,
621
+ httpClient,
622
+ method: clientOptions.method,
623
+ ...(clientOptions.body ? {
624
+ body: clientOptions.body
625
+ } : {})
626
+ });
627
+ if (response.statusCode >= 200 && response.statusCode < 300) {
628
+ if (clientOptions.method == 'HEAD') {
629
+ return {
630
+ body: null,
631
+ statusCode: response.statusCode,
632
+ retryCount: response.retryCount,
633
+ headers: getHeaders(response.headers)
634
+ };
635
+ }
636
+ return {
637
+ body: response.data,
638
+ statusCode: response.statusCode,
639
+ retryCount: response.retryCount,
640
+ headers: getHeaders(response.headers)
641
+ };
642
+ }
643
+ const error = createError({
644
+ message: (response === null || response === void 0 ? void 0 : (_response$data = response.data) === null || _response$data === void 0 ? void 0 : _response$data.message) || (response === null || response === void 0 ? void 0 : response.message),
645
+ statusCode: response.statusCode || (response === null || response === void 0 ? void 0 : (_response$data2 = response.data) === null || _response$data2 === void 0 ? void 0 : _response$data2.statusCode),
646
+ headers: getHeaders(response.headers),
647
+ method: clientOptions.method,
648
+ body: response.data,
649
+ retryCount: response.retryCount,
650
+ ...(includeRequestInErrorResponse ? {
651
+ originalRequest: maskSensitiveHeaderData ? maskAuthData(request) : request
652
+ } : {
653
+ uri: request.uri
654
+ })
655
+ });
656
+
657
+ /**
658
+ * handle non-ok (error) response
659
+ * build error body
660
+ */
661
+ return {
662
+ body: response.data,
663
+ code: response.statusCode,
664
+ statusCode: response.statusCode,
665
+ headers: getHeaders(response.headers),
666
+ error
667
+ };
668
+ } catch (e) {
669
+ var _e$response, _e$response2, _e$response3, _e$response4, _e$response4$data, _e$response5, _e$response6;
670
+ // We know that this is a network error
671
+ const headers = getHeaders((_e$response = e.response) === null || _e$response === void 0 ? void 0 : _e$response.headers);
672
+ const statusCode = ((_e$response2 = e.response) === null || _e$response2 === void 0 ? void 0 : _e$response2.status) || ((_e$response3 = e.response) === null || _e$response3 === void 0 ? void 0 : _e$response3.data0) || 0;
673
+ const message = (_e$response4 = e.response) === null || _e$response4 === void 0 ? void 0 : (_e$response4$data = _e$response4.data) === null || _e$response4$data === void 0 ? void 0 : _e$response4$data.message;
674
+ const error = createError({
675
+ statusCode,
676
+ code: statusCode,
677
+ status: statusCode,
678
+ message: message || e.message,
679
+ headers,
680
+ body: ((_e$response5 = e.response) === null || _e$response5 === void 0 ? void 0 : _e$response5.data) || e,
681
+ error: (_e$response6 = e.response) === null || _e$response6 === void 0 ? void 0 : _e$response6.data,
682
+ ...(includeRequestInErrorResponse ? {
683
+ originalRequest: maskSensitiveHeaderData ? maskAuthData(request) : request
684
+ } : {
685
+ uri: request.uri
686
+ })
687
+ });
688
+ return {
689
+ body: error,
690
+ error
691
+ };
692
+ } finally {
693
+ clearTimeout(timer);
694
+ }
695
+ }
696
+ function createHttpMiddleware$1(options) {
697
+ // validate response
698
+ validateHttpOptions(options);
699
+ const {
700
+ host,
701
+ credentialsMode,
702
+ httpClient,
703
+ timeout,
704
+ enableRetry,
705
+ retryConfig,
706
+ getAbortController,
707
+ includeOriginalRequest,
708
+ includeRequestInErrorResponse,
709
+ maskSensitiveHeaderData,
710
+ httpClientOptions
711
+ } = options;
712
+ return next => {
713
+ return async request => {
714
+ let abortController;
715
+ if (timeout || getAbortController) abortController = (getAbortController ? getAbortController() : null) || new AbortController__default["default"]();
716
+ const url = host.replace(/\/$/, '') + request.uri;
717
+ const requestHeader = {
718
+ ...request.headers
719
+ };
720
+
721
+ // validate header
722
+ if (!(Object.prototype.hasOwnProperty.call(requestHeader, 'Content-Type') || Object.prototype.hasOwnProperty.call(requestHeader, 'content-type'))) {
723
+ requestHeader['Content-Type'] = 'application/json';
724
+ }
725
+
726
+ // Unset the content-type header if explicitly asked to (passing `null` as value).
727
+ if (requestHeader['Content-Type'] === null) {
728
+ delete requestHeader['Content-Type'];
729
+ }
730
+
731
+ // Ensure body is a string if content type is application/{json|graphql}
732
+ const body = HEADERS_CONTENT_TYPES.indexOf(requestHeader['Content-Type']) > -1 && typeof request.body === 'string' || isBuffer(request.body) ? request.body : JSON.stringify(request.body || undefined);
733
+ if (body && (typeof body === 'string' || isBuffer(body))) {
734
+ requestHeader['Content-Length'] = _.Buffer.byteLength(body).toString();
735
+ }
736
+ const clientOptions = {
737
+ enableRetry,
738
+ retryConfig,
739
+ request: request,
740
+ method: request.method,
741
+ headers: requestHeader,
742
+ includeRequestInErrorResponse,
743
+ maskSensitiveHeaderData,
744
+ ...httpClientOptions
745
+ };
746
+ if (credentialsMode) {
747
+ clientOptions.credentialsMode = credentialsMode;
748
+ }
749
+ if (abortController) {
750
+ clientOptions.signal = abortController.signal;
751
+ }
752
+ if (timeout) {
753
+ clientOptions.timeout = timeout;
754
+ clientOptions.abortController = abortController;
755
+ }
756
+ if (body) {
757
+ clientOptions.body = body;
758
+ }
759
+
760
+ // get result from executed request
761
+ const response = await executeRequest$1({
762
+ url,
763
+ clientOptions,
764
+ httpClient
765
+ });
766
+ const responseWithRequest = {
767
+ ...request,
768
+ includeOriginalRequest,
769
+ maskSensitiveHeaderData,
770
+ response
771
+ };
772
+ return next(responseWithRequest);
773
+ };
774
+ };
775
+ }
776
+
777
+ function createQueueMiddleware$1({
778
+ concurrency = 20
779
+ }) {
780
+ let runningCount = 0;
781
+ const queue = [];
782
+ const dequeue = next => {
783
+ runningCount--;
784
+ if (queue.length && runningCount <= concurrency) {
785
+ const nextTask = queue.shift();
786
+ runningCount++;
787
+ return next(nextTask.request);
788
+ }
789
+ };
790
+ const enqueue = ({
791
+ request
792
+ }) => queue.push({
793
+ request
794
+ });
795
+ return next => request => {
796
+ // wrap and override resolve and reject functions
797
+ const patchedRequest = {
798
+ ...request,
799
+ resolve(data) {
800
+ request.resolve(data);
801
+ dequeue(next);
802
+ },
803
+ reject(error) {
804
+ request.reject(error);
805
+ dequeue(next);
806
+ }
807
+ };
808
+
809
+ // enqueue requests
810
+ enqueue({
811
+ request: patchedRequest
812
+ });
813
+ if (runningCount < concurrency) {
814
+ runningCount++;
815
+ const nextTask = queue.shift();
816
+ return next(nextTask.request);
817
+ }
818
+ };
819
+ }
820
+
821
+ // error, info, success
822
+ function createLoggerMiddleware$1(options) {
823
+ return next => {
824
+ return async request => {
825
+ let response = await next(request);
826
+ const originalResponse = Object.assign({}, response);
827
+ const {
828
+ loggerFn = console.log,
829
+ // logLevel = 'ERROR',
830
+ maskSensitiveHeaderData = true,
831
+ includeOriginalRequest = true,
832
+ includeResponseHeaders = true
833
+ // includeRequestInErrorResponse
834
+ } = options || {};
835
+ if (includeOriginalRequest && maskSensitiveHeaderData) {
836
+ maskAuthData(response.request);
837
+ }
838
+ if (!includeOriginalRequest) {
839
+ const {
840
+ request,
841
+ ...rest
842
+ } = response;
843
+ response = rest;
844
+ }
845
+ if (!includeResponseHeaders) {
846
+ const {
847
+ headers,
848
+ ...rest
849
+ } = response;
850
+ response = rest;
851
+ }
852
+ if (loggerFn && typeof loggerFn == 'function') {
853
+ loggerFn(response);
854
+ // return originalResponse
855
+ }
856
+
857
+ // console.log({ Response: response })
858
+ return originalResponse;
859
+ };
860
+ };
861
+ }
862
+
863
+ var packageJson = {
864
+ name: "@commercetools/ts-client",
865
+ version: "1.0.0",
866
+ engines: {
867
+ node: ">=14"
868
+ },
869
+ description: "commercetools Composable Commerce TypeScript SDK client.",
870
+ keywords: [
871
+ "commercetools",
872
+ "composable commerce",
873
+ "sdk",
874
+ "typescript",
875
+ "client",
876
+ "middleware",
877
+ "http",
878
+ "oauth",
879
+ "auth"
880
+ ],
881
+ homepage: "https://github.com/commercetools/commercetools-sdk-typescript",
882
+ license: "MIT",
883
+ directories: {
884
+ lib: "lib",
885
+ test: "test"
886
+ },
887
+ publishConfig: {
888
+ access: "public"
889
+ },
890
+ repository: {
891
+ type: "git",
892
+ url: "git+https://github.com/commercetools/commercetools-sdk-typescript.git"
893
+ },
894
+ bugs: {
895
+ url: "https://github.com/commercetools/commercetools-sdk-typescript/issues"
896
+ },
897
+ dependencies: {
898
+ "abort-controller": "3.0.0",
899
+ buffer: "^6.0.3",
900
+ "node-fetch": "^2.6.1",
901
+ querystring: "^0.2.1"
902
+ },
903
+ files: [
904
+ "dist",
905
+ "CHANGELOG.md"
906
+ ],
907
+ author: "Chukwuemeka Ajima <meeky.ae@gmail.com>",
908
+ main: "dist/commercetools-ts-client.cjs.js",
909
+ module: "dist/commercetools-ts-client.esm.js",
910
+ browser: {
911
+ "./dist/commercetools-ts-client.cjs.js": "./dist/commercetools-ts-client.browser.cjs.js",
912
+ "./dist/commercetools-ts-client.esm.js": "./dist/commercetools-ts-client.browser.esm.js"
913
+ },
914
+ devDependencies: {
915
+ "common-tags": "1.8.2",
916
+ dotenv: "16.0.3",
917
+ jest: "29.5.0",
918
+ nock: "12.0.3",
919
+ "organize-imports-cli": "0.10.0"
920
+ },
921
+ scripts: {
922
+ organize_imports: "find src -type f -name '*.ts' | xargs organize-imports-cli",
923
+ postbuild: "yarn organize_imports",
924
+ post_process_generate: "yarn organize_imports"
925
+ }
926
+ };
927
+
928
+ function createUserAgentMiddleware$1(options) {
929
+ return next => async request => {
930
+ const userAgent = createUserAgent({
931
+ ...options,
932
+ name: `commercetools-sdk-javascript-v3/${packageJson.version}`
933
+ });
934
+ const requestWithUserAgent = {
935
+ ...request,
936
+ headers: {
937
+ ...request.headers,
938
+ 'User-Agent': userAgent
939
+ }
940
+ };
941
+ return next(requestWithUserAgent);
942
+ };
943
+ }
944
+
945
+ function createConcurrentModificationMiddleware$1() {
946
+ return next => {
947
+ return async request => {
948
+ const response = await next(request);
949
+ if (response.statusCode == 409) {
950
+ var _response$error, _response$error$body, _response$error$body$, _response$error$body$2;
951
+ /**
952
+ * extract the currentVersion
953
+ * from the error body and update
954
+ * request with the currentVersion
955
+ */
956
+ const version = (_response$error = response.error) === null || _response$error === void 0 ? void 0 : (_response$error$body = _response$error.body) === null || _response$error$body === void 0 ? void 0 : (_response$error$body$ = _response$error$body.errors) === null || _response$error$body$ === void 0 ? void 0 : (_response$error$body$2 = _response$error$body$[0]) === null || _response$error$body$2 === void 0 ? void 0 : _response$error$body$2.currentVersion;
957
+
958
+ // update the resource version here
959
+ if (version) {
960
+ request.body = typeof request.body == 'string' ? {
961
+ ...JSON.parse(request.body),
962
+ version
963
+ } : {
964
+ ...request.body,
965
+ version
966
+ };
967
+ return next(request);
968
+ }
969
+ }
970
+ return response;
971
+ };
972
+ };
973
+ }
974
+
975
+ function createErrorMiddleware$1(options) {
976
+ return next => async request => {
977
+ const response = await next(request);
978
+ if (response.error) {
979
+ const {
980
+ error
981
+ } = response;
982
+ return {
983
+ ...response,
984
+ statusCode: error.statusCode || 0,
985
+ headers: error.headers || getHeaders({}),
986
+ error: {
987
+ ...error,
988
+ body: error.data || error
989
+ }
990
+ };
991
+ }
992
+ return response;
993
+ };
994
+ }
995
+
996
+ /**
997
+ *
998
+ * @param {AuthMiddlewareOptions} options
999
+ * @returns { IBuiltRequestParams } *
1000
+ */
1001
+ function buildRequestForClientCredentialsFlow(options) {
1002
+ // Validate options
1003
+ if (!options) throw new Error('Missing required options');
1004
+ if (!options.host) throw new Error('Missing required option (host)');
1005
+ if (!options.projectKey) throw new Error('Missing required option (projectKey)');
1006
+ if (!options.credentials) throw new Error('Missing required option (credentials)');
1007
+ const {
1008
+ clientId,
1009
+ clientSecret
1010
+ } = options.credentials || {};
1011
+ if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
1012
+ const scope = options.scopes ? options.scopes.join(' ') : undefined;
1013
+ const basicAuth = _.Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
1014
+ // This is mostly useful for internal testing purposes to be able to check
1015
+ // other oauth endpoints.
1016
+ const oauthUri = options.oauthUri || '/oauth/token';
1017
+ const url = options.host.replace(/\/$/, '') + oauthUri;
1018
+ const body = `grant_type=client_credentials${scope ? `&scope=${scope}` : ''}`;
1019
+ return {
1020
+ url,
1021
+ body,
1022
+ basicAuth
1023
+ };
1024
+ }
1025
+
1026
+ /**
1027
+ *
1028
+ * @param {AuthMiddlewareOptions} options
1029
+ * @returns {IBuiltRequestParams} *
1030
+ */
1031
+ function buildRequestForAnonymousSessionFlow(options) {
1032
+ if (!options) throw new Error('Missing required options');
1033
+ if (!options.projectKey) throw new Error('Missing required option (projectKey)');
1034
+ const projectKey = options.projectKey;
1035
+ options.oauthUri = options.oauthUri || `/oauth/${projectKey}/anonymous/token`;
1036
+ const result = buildRequestForClientCredentialsFlow(options);
1037
+ if (options.credentials.anonymousId) result.body += `&anonymous_id=${options.credentials.anonymousId}`;
1038
+ return {
1039
+ ...result
1040
+ };
1041
+ }
1042
+
1043
+ /**
1044
+ *
1045
+ * @param {RefreshAuthMiddlewareOptions} options
1046
+ * @returns {IBuiltRequestParams}
1047
+ */
1048
+ function buildRequestForRefreshTokenFlow(options) {
1049
+ if (!options) throw new Error('Missing required options');
1050
+ if (!options.host) throw new Error('Missing required option (host)');
1051
+ if (!options.projectKey) throw new Error('Missing required option (projectKey)');
1052
+ if (!options.credentials) throw new Error('Missing required option (credentials)');
1053
+ if (!options.refreshToken) throw new Error('Missing required option (refreshToken)');
1054
+ const {
1055
+ clientId,
1056
+ clientSecret
1057
+ } = options.credentials;
1058
+ if (!(clientId && clientSecret)) throw new Error('Missing required credentials (clientId, clientSecret)');
1059
+ const basicAuth = _.Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
1060
+ // This is mostly useful for internal testing purposes to be able to check
1061
+ // other oauth endpoints.
1062
+ const oauthUri = options.oauthUri || '/oauth/token';
1063
+ const url = options.host.replace(/\/$/, '') + oauthUri;
1064
+ const body = `grant_type=refresh_token&refresh_token=${encodeURIComponent(options.refreshToken)}`;
1065
+ return {
1066
+ basicAuth,
1067
+ url,
1068
+ body
1069
+ };
1070
+ }
1071
+
1072
+ /**
1073
+ * @param {PasswordAuthMiddlewareOptions} options
1074
+ * @returns {IBuiltRequestParams}
1075
+ */
1076
+ function buildRequestForPasswordFlow(options) {
1077
+ if (!options) throw new Error('Missing required options');
1078
+ if (!options.host) throw new Error('Missing required option (host)');
1079
+ if (!options.projectKey) throw new Error('Missing required option (projectKey)');
1080
+ if (!options.credentials) throw new Error('Missing required option (credentials)');
1081
+ const {
1082
+ clientId,
1083
+ clientSecret,
1084
+ user
1085
+ } = options.credentials;
1086
+ const projectKey = options.projectKey;
1087
+ if (!(clientId && clientSecret && user)) throw new Error('Missing required credentials (clientId, clientSecret, user)');
1088
+ const {
1089
+ username,
1090
+ password
1091
+ } = user;
1092
+ if (!(username && password)) throw new Error('Missing required user credentials (username, password)');
1093
+ const scope = (options.scopes || []).join(' ');
1094
+ const scopeStr = scope ? `&scope=${scope}` : '';
1095
+ const basicAuth = _.Buffer.from(`${clientId}:${clientSecret}`).toString('base64');
1096
+
1097
+ /**
1098
+ * This is mostly useful for internal testing purposes to be able to check
1099
+ * other oauth endpoints.
1100
+ */
1101
+ const oauthUri = options.oauthUri || `/oauth/${projectKey}/customers/token`;
1102
+ const url = options.host.replace(/\/$/, '') + oauthUri;
1103
+
1104
+ // encode username and password as requested by the system
1105
+ const body = `grant_type=password&username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}${scopeStr}`;
1106
+ return {
1107
+ basicAuth,
1108
+ url,
1109
+ body
1110
+ };
1111
+ }
1112
+
1113
+ async function executeRequest(options) {
1114
+ const {
1115
+ request,
1116
+ httpClient,
1117
+ tokenCache,
1118
+ tokenCacheKey,
1119
+ requestState,
1120
+ userOption,
1121
+ next
1122
+ } = options;
1123
+ let url = options.url;
1124
+ let body = options.body;
1125
+ let basicAuth = options.basicAuth;
1126
+
1127
+ // get the pending object from option
1128
+ let pendingTasks = options.pendingTasks;
1129
+ 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.');
1130
+
1131
+ /**
1132
+ * If there is a token in the tokenCache, and it's not
1133
+ * expired, append the token in the `Authorization` header.
1134
+ */
1135
+ const tokenCacheObject = tokenCache.get(tokenCacheKey);
1136
+ if (tokenCacheObject && tokenCacheObject.token && Date.now() < tokenCacheObject.expirationTime) {
1137
+ const requestWithAuth = mergeAuthHeader(tokenCacheObject.token, request);
1138
+ return {
1139
+ ...requestWithAuth
1140
+ };
1141
+ }
1142
+
1143
+ /**
1144
+ * Keep pending tasks until a token is fetched
1145
+ * Save next function as well, to call it once the token has been fetched, which prevents
1146
+ * unexpected behaviour in a context in which the next function uses global vars
1147
+ * or Promises to capture the token to hand it to other libraries, e.g. Apollo
1148
+ */
1149
+ pendingTasks.push({
1150
+ request,
1151
+ next
1152
+ });
1153
+
1154
+ // if a token is currently being fetched, then wait
1155
+ if (requestState.get()) return;
1156
+
1157
+ // signal that a token is being fetched
1158
+ requestState.set(true);
1159
+
1160
+ /**
1161
+ * use refreshToken flow if there is refresh-token
1162
+ * and there's either no token or the token is expired
1163
+ */
1164
+ if (tokenCacheObject && tokenCacheObject.refreshToken && (!tokenCacheObject.token || tokenCacheObject.token && Date.now() > tokenCacheObject.expirationTime)) {
1165
+ if (!userOption) throw new Error('Missing required options.');
1166
+ const opt = {
1167
+ ...buildRequestForRefreshTokenFlow({
1168
+ ...userOption,
1169
+ refreshToken: tokenCacheObject.refreshToken
1170
+ })
1171
+ };
1172
+
1173
+ // reassign values
1174
+ url = opt.url;
1175
+ body = opt.body;
1176
+ basicAuth = opt.basicAuth;
1177
+ }
1178
+
1179
+ // request a new token
1180
+ let response;
1181
+ try {
1182
+ response = await executor({
1183
+ url,
1184
+ method: 'POST',
1185
+ headers: {
1186
+ Authorization: `Basic ${basicAuth}`,
1187
+ 'Content-Type': 'application/x-www-form-urlencoded',
1188
+ 'Conent-Length': _.Buffer.byteLength(body).toString()
1189
+ },
1190
+ httpClient,
1191
+ body
1192
+ });
1193
+ if (response.statusCode >= 200 && response.statusCode < 300) {
1194
+ var _response;
1195
+ const {
1196
+ access_token: token,
1197
+ expires_in: expiresIn,
1198
+ refresh_token: refreshToken
1199
+ } = (_response = response) === null || _response === void 0 ? void 0 : _response.data;
1200
+
1201
+ // calculate token expiration time
1202
+ const expirationTime = calculateExpirationTime(expiresIn);
1203
+
1204
+ // cache new generated token, refreshToken and expiration time
1205
+ tokenCache.set({
1206
+ token,
1207
+ expirationTime,
1208
+ refreshToken
1209
+ });
1210
+
1211
+ // signal that a token fetch is complete
1212
+ requestState.set(false);
1213
+
1214
+ /**
1215
+ * Freeze and copy pending queue, reset
1216
+ * original one for accepting new pending tasks
1217
+ */
1218
+ const requestQueue = pendingTasks.slice();
1219
+
1220
+ // reset pendingTask queue
1221
+ pendingTasks = [];
1222
+ if (requestQueue.length === 1) {
1223
+ return mergeAuthHeader(token, requestQueue.pop().request);
1224
+ }
1225
+
1226
+ // execute all pending tasks if any
1227
+ for (let i = 0; i < requestQueue.length; i++) {
1228
+ const task = requestQueue[i];
1229
+ const requestWithAuth = mergeAuthHeader(token, task.request);
1230
+
1231
+ // execute task
1232
+ task.next(requestWithAuth);
1233
+ }
1234
+ return;
1235
+ }
1236
+ const error = new Error(response.data.message ? response.data.message : JSON.stringify(response.data));
1237
+ /**
1238
+ * reject the error immediately
1239
+ * and free up the middleware chain
1240
+ */
1241
+ request.reject({
1242
+ ...request,
1243
+ headers: {
1244
+ ...request.headers
1245
+ },
1246
+ response: {
1247
+ statusCode: response.statusCode || response.data.statusCode,
1248
+ error: {
1249
+ error,
1250
+ body: response
1251
+ }
1252
+ }
1253
+ });
1254
+ } catch (error) {
1255
+ return {
1256
+ ...request,
1257
+ headers: {
1258
+ ...request.headers
1259
+ },
1260
+ response: {
1261
+ body: null,
1262
+ statusCode: error.statusCode || 0,
1263
+ error: {
1264
+ ...response,
1265
+ error,
1266
+ body: response
1267
+ }
1268
+ }
1269
+ };
1270
+ }
1271
+ }
1272
+
1273
+ function createAuthMiddlewareForPasswordFlow$1(options) {
1274
+ const tokenCache = options.tokenCache || store({
1275
+ token: '',
1276
+ expirationTime: -1
1277
+ });
1278
+ const pendingTasks = [];
1279
+ const requestState = store(false);
1280
+ const tokenCacheKey = buildTokenCacheKey(options);
1281
+ return next => {
1282
+ return async request => {
1283
+ if (request.headers && (request.headers.Authorization || request.headers.authorization)) {
1284
+ return next(request);
1285
+ }
1286
+ const requestOptions = {
1287
+ request,
1288
+ requestState,
1289
+ tokenCache,
1290
+ pendingTasks,
1291
+ tokenCacheKey,
1292
+ httpClient: options.httpClient || fetch__default["default"],
1293
+ ...buildRequestForPasswordFlow(options),
1294
+ userOption: options,
1295
+ next
1296
+ };
1297
+
1298
+ // make request to coco
1299
+ const requestWithAuth = await executeRequest(requestOptions);
1300
+ if (requestWithAuth) {
1301
+ return next(requestWithAuth);
1302
+ }
1303
+ };
1304
+ };
1305
+ }
1306
+
1307
+ function createAuthMiddlewareForAnonymousSessionFlow$1(options) {
1308
+ const pendingTasks = [];
1309
+ const requestState = store(false);
1310
+ const tokenCache = options.tokenCache || store({
1311
+ token: '',
1312
+ expirationTime: -1
1313
+ });
1314
+ const tokenCacheKey = buildTokenCacheKey(options);
1315
+ return next => {
1316
+ return async request => {
1317
+ // if here is a token in the header, then move on to the next middleware
1318
+ if (request.headers && (request.headers.Authorization || request.headers.authorization)) {
1319
+ // move on
1320
+ return next(request);
1321
+ }
1322
+
1323
+ // prepare request options
1324
+ const requestOptions = {
1325
+ request,
1326
+ requestState,
1327
+ tokenCache,
1328
+ pendingTasks,
1329
+ tokenCacheKey,
1330
+ httpClient: options.httpClient || fetch__default["default"],
1331
+ ...buildRequestForAnonymousSessionFlow(options),
1332
+ userOption: options,
1333
+ next
1334
+ };
1335
+
1336
+ // make request to coco
1337
+ const requestWithAuth = await executeRequest(requestOptions);
1338
+ if (requestWithAuth) {
1339
+ return next(requestWithAuth);
1340
+ }
1341
+ };
1342
+ };
1343
+ }
1344
+
1345
+ function createAuthMiddlewareForClientCredentialsFlow$1(options) {
1346
+ const requestState = store(false);
1347
+ const pendingTasks = [];
1348
+ const tokenCache = options.tokenCache || store({
1349
+ token: '',
1350
+ expirationTime: -1
1351
+ });
1352
+ const tokenCacheKey = buildTokenCacheKey(options);
1353
+ return next => {
1354
+ return async request => {
1355
+ // if here is a token in the header, then move on to the next middleware
1356
+ if (request.headers && (request.headers.Authorization || request.headers.authorization)) {
1357
+ // move on
1358
+ return next(request);
1359
+ }
1360
+
1361
+ // prepare request options
1362
+ const requestOptions = {
1363
+ request,
1364
+ requestState,
1365
+ tokenCache,
1366
+ pendingTasks,
1367
+ tokenCacheKey,
1368
+ httpClient: options.httpClient || fetch__default["default"],
1369
+ ...buildRequestForClientCredentialsFlow(options),
1370
+ next
1371
+ };
1372
+
1373
+ // make request to coco
1374
+ const requestWithAuth = await executeRequest(requestOptions);
1375
+ if (requestWithAuth) {
1376
+ // make the request and inject the token into the header
1377
+ return next(requestWithAuth);
1378
+ }
1379
+ };
1380
+ };
1381
+ }
1382
+
1383
+ function createAuthMiddlewareForRefreshTokenFlow$1(options) {
1384
+ const tokenCache = options.tokenCache || store({
1385
+ token: '',
1386
+ tokenCacheKey: null
1387
+ });
1388
+ const pendingTasks = [];
1389
+ const requestState = store(false);
1390
+ return next => {
1391
+ return async request => {
1392
+ if (request.headers && (request.headers.Authorization || request.headers.authorization)) {
1393
+ return next(request);
1394
+ }
1395
+
1396
+ // prepare request options
1397
+ const requestOptions = {
1398
+ request,
1399
+ requestState,
1400
+ tokenCache,
1401
+ pendingTasks,
1402
+ httpClient: options.httpClient || fetch,
1403
+ ...buildRequestForRefreshTokenFlow(options),
1404
+ next
1405
+ };
1406
+
1407
+ // make request to coco
1408
+ const requestWithAuth = await executeRequest(requestOptions);
1409
+ if (requestWithAuth) {
1410
+ return next(requestWithAuth);
1411
+ }
1412
+ };
1413
+ };
1414
+ }
1415
+
1416
+ function createAuthMiddlewareForExistingTokenFlow$1(authorization, options) {
1417
+ return next => {
1418
+ return async request => {
1419
+ if (typeof authorization !== 'string') throw new Error('authorization must be a string');
1420
+ const isForce = (options === null || options === void 0 ? void 0 : options.force) === undefined ? true : options.force;
1421
+
1422
+ /**
1423
+ * The request will not be modified if:
1424
+ * 1. no argument is passed
1425
+ * 2. force is false and authorization header exists
1426
+ */
1427
+ if (!authorization || request.headers && (request.headers.Authorization || request.headers.authorization) && isForce === false) {
1428
+ return next(request);
1429
+ }
1430
+ const requestWithAuth = {
1431
+ ...request,
1432
+ headers: {
1433
+ ...request.headers,
1434
+ Authorization: authorization
1435
+ }
1436
+ };
1437
+ return next(requestWithAuth);
1438
+ };
1439
+ };
1440
+ }
1441
+
1442
+ var middleware = /*#__PURE__*/Object.freeze({
1443
+ __proto__: null,
1444
+ createCorrelationIdMiddleware: createCorrelationIdMiddleware$1,
1445
+ createHttpMiddleware: createHttpMiddleware$1,
1446
+ createQueueMiddleware: createQueueMiddleware$1,
1447
+ createLoggerMiddleware: createLoggerMiddleware$1,
1448
+ createUserAgentMiddleware: createUserAgentMiddleware$1,
1449
+ createConcurrentModificationMiddleware: createConcurrentModificationMiddleware$1,
1450
+ createErrorMiddleware: createErrorMiddleware$1,
1451
+ createAuthMiddlewareForPasswordFlow: createAuthMiddlewareForPasswordFlow$1,
1452
+ createAuthMiddlewareForClientCredentialsFlow: createAuthMiddlewareForClientCredentialsFlow$1,
1453
+ createAuthMiddlewareForAnonymousSessionFlow: createAuthMiddlewareForAnonymousSessionFlow$1,
1454
+ createAuthMiddlewareForExistingTokenFlow: createAuthMiddlewareForExistingTokenFlow$1,
1455
+ createAuthMiddlewareForRefreshTokenFlow: createAuthMiddlewareForRefreshTokenFlow$1
1456
+ });
1457
+
1458
+ const {
1459
+ createAuthMiddlewareForPasswordFlow,
1460
+ createAuthMiddlewareForAnonymousSessionFlow,
1461
+ createAuthMiddlewareForClientCredentialsFlow,
1462
+ createAuthMiddlewareForRefreshTokenFlow,
1463
+ createAuthMiddlewareForExistingTokenFlow,
1464
+ createCorrelationIdMiddleware,
1465
+ createHttpMiddleware,
1466
+ createLoggerMiddleware,
1467
+ createQueueMiddleware,
1468
+ createUserAgentMiddleware,
1469
+ createConcurrentModificationMiddleware,
1470
+ createErrorMiddleware
1471
+ } = middleware;
1472
+ class ClientBuilder {
1473
+ constructor() {
1474
+ _defineProperty(this, "projectKey", void 0);
1475
+ _defineProperty(this, "authMiddleware", void 0);
1476
+ _defineProperty(this, "httpMiddleware", void 0);
1477
+ _defineProperty(this, "userAgentMiddleware", void 0);
1478
+ _defineProperty(this, "correlationIdMiddleware", void 0);
1479
+ _defineProperty(this, "loggerMiddleware", void 0);
1480
+ _defineProperty(this, "queueMiddleware", void 0);
1481
+ _defineProperty(this, "concurrentMiddleware", void 0);
1482
+ _defineProperty(this, "errorMiddleware", void 0);
1483
+ _defineProperty(this, "middlewares", []);
1484
+ this.userAgentMiddleware = createUserAgentMiddleware({});
1485
+ }
1486
+ withProjectKey(key) {
1487
+ this.projectKey = key;
1488
+ return this;
1489
+ }
1490
+ defaultClient(baseUri, credentials, oauthUri, projectKey, scopes, httpClient) {
1491
+ return this.withClientCredentialsFlow({
1492
+ host: oauthUri,
1493
+ projectKey: projectKey || this.projectKey,
1494
+ credentials,
1495
+ scopes
1496
+ }).withHttpMiddleware({
1497
+ host: baseUri,
1498
+ httpClient: httpClient || fetch__default["default"]
1499
+ });
1500
+ }
1501
+ withAuthMiddleware(authMiddleware) {
1502
+ this.authMiddleware = authMiddleware;
1503
+ return this;
1504
+ }
1505
+ withMiddleware(middleware) {
1506
+ this.middlewares.push(middleware);
1507
+ return this;
1508
+ }
1509
+ withClientCredentialsFlow(options) {
1510
+ return this.withAuthMiddleware(createAuthMiddlewareForClientCredentialsFlow({
1511
+ host: options.host || CTP_AUTH_URL,
1512
+ projectKey: options.projectKey || this.projectKey,
1513
+ credentials: {
1514
+ clientId: options.credentials.clientId || null,
1515
+ clientSecret: options.credentials.clientSecret || null
1516
+ },
1517
+ oauthUri: options.oauthUri || null,
1518
+ scopes: options.scopes,
1519
+ httpClient: options.httpClient || fetch__default["default"],
1520
+ ...options
1521
+ }));
1522
+ }
1523
+ withPasswordFlow(options) {
1524
+ return this.withAuthMiddleware(createAuthMiddlewareForPasswordFlow({
1525
+ host: options.host || CTP_AUTH_URL,
1526
+ projectKey: options.projectKey || this.projectKey,
1527
+ credentials: {
1528
+ clientId: options.credentials.clientId || null,
1529
+ clientSecret: options.credentials.clientSecret || null,
1530
+ user: {
1531
+ username: options.credentials.user.username || null,
1532
+ password: options.credentials.user.password || null
1533
+ }
1534
+ },
1535
+ httpClient: options.httpClient || fetch__default["default"],
1536
+ ...options
1537
+ }));
1538
+ }
1539
+ withAnonymousSessionFlow(options) {
1540
+ return this.withAuthMiddleware(createAuthMiddlewareForAnonymousSessionFlow({
1541
+ host: options.host || CTP_AUTH_URL,
1542
+ projectKey: this.projectKey || options.projectKey,
1543
+ credentials: {
1544
+ clientId: options.credentials.clientId || null,
1545
+ clientSecret: options.credentials.clientSecret || null,
1546
+ anonymousId: options.credentials.anonymousId || null
1547
+ },
1548
+ httpClient: options.httpClient || fetch__default["default"],
1549
+ ...options
1550
+ }));
1551
+ }
1552
+ withRefreshTokenFlow(options) {
1553
+ return this.withAuthMiddleware(createAuthMiddlewareForRefreshTokenFlow({
1554
+ host: options.host || CTP_AUTH_URL,
1555
+ projectKey: this.projectKey || options.projectKey,
1556
+ credentials: {
1557
+ clientId: options.credentials.clientId || null,
1558
+ clientSecret: options.credentials.clientSecret || null
1559
+ },
1560
+ httpClient: options.httpClient || fetch__default["default"],
1561
+ refreshToken: options.refreshToken || null,
1562
+ ...options
1563
+ }));
1564
+ }
1565
+ withExistingTokenFlow(authorization, options) {
1566
+ return this.withAuthMiddleware(createAuthMiddlewareForExistingTokenFlow(authorization, {
1567
+ force: options.force || true,
1568
+ ...options
1569
+ }));
1570
+ }
1571
+ withHttpMiddleware(options) {
1572
+ this.httpMiddleware = createHttpMiddleware({
1573
+ host: options.host || CTP_API_URL,
1574
+ httpClient: options.httpClient || fetch__default["default"],
1575
+ ...options
1576
+ });
1577
+ return this;
1578
+ }
1579
+ withUserAgentMiddleware(options) {
1580
+ this.userAgentMiddleware = createUserAgentMiddleware(options);
1581
+ return this;
1582
+ }
1583
+ withQueueMiddleware(options) {
1584
+ this.queueMiddleware = createQueueMiddleware({
1585
+ concurrency: options.concurrency || CONCURRENCT_REQUEST,
1586
+ ...options
1587
+ });
1588
+ return this;
1589
+ }
1590
+ withLoggerMiddleware(options) {
1591
+ this.loggerMiddleware = createLoggerMiddleware(options);
1592
+ return this;
1593
+ }
1594
+ withCorrelationIdMiddleware(options) {
1595
+ this.correlationIdMiddleware = createCorrelationIdMiddleware({
1596
+ generate: options === null || options === void 0 ? void 0 : options.generate,
1597
+ ...options
1598
+ });
1599
+ return this;
1600
+ }
1601
+ withConcurrentModificationMiddleware() {
1602
+ this.concurrentMiddleware = createConcurrentModificationMiddleware();
1603
+ return this;
1604
+ }
1605
+ withErrorMiddleware(options) {
1606
+ this.errorMiddleware = createErrorMiddleware(options);
1607
+ return this;
1608
+ }
1609
+ build() {
1610
+ const middlewares = this.middlewares.slice();
1611
+
1612
+ /**
1613
+ * - use default retry policy if not explicity added
1614
+ * - add retry middleware to be used by concurrent modification
1615
+ * middleware if not explicitly added as part of the middleware
1616
+ */
1617
+ if (this.correlationIdMiddleware) middlewares.push(this.correlationIdMiddleware);
1618
+ if (this.userAgentMiddleware) middlewares.push(this.userAgentMiddleware);
1619
+ if (this.authMiddleware) middlewares.push(this.authMiddleware);
1620
+ if (this.queueMiddleware) middlewares.push(this.queueMiddleware);
1621
+ if (this.loggerMiddleware) middlewares.push(this.loggerMiddleware);
1622
+ if (this.errorMiddleware) middlewares.push(this.errorMiddleware);
1623
+ if (this.concurrentMiddleware) middlewares.push(this.concurrentMiddleware);
1624
+ if (this.httpMiddleware) middlewares.push(this.httpMiddleware);
1625
+ return createClient({
1626
+ middlewares
1627
+ });
1628
+ }
1629
+ }
1630
+
1631
+ exports.ClientBuilder = ClientBuilder;
1632
+ exports.Process = process$1;
1633
+ exports.createAuthMiddlewareForAnonymousSessionFlow = createAuthMiddlewareForAnonymousSessionFlow$1;
1634
+ exports.createAuthMiddlewareForClientCredentialsFlow = createAuthMiddlewareForClientCredentialsFlow$1;
1635
+ exports.createAuthMiddlewareForExistingTokenFlow = createAuthMiddlewareForExistingTokenFlow$1;
1636
+ exports.createAuthMiddlewareForPasswordFlow = createAuthMiddlewareForPasswordFlow$1;
1637
+ exports.createAuthMiddlewareForRefreshTokenFlow = createAuthMiddlewareForRefreshTokenFlow$1;
1638
+ exports.createClient = createClient;
1639
+ exports.createCorrelationIdMiddleware = createCorrelationIdMiddleware$1;
1640
+ exports.createHttpMiddleware = createHttpMiddleware$1;
1641
+ exports.createLoggerMiddleware = createLoggerMiddleware$1;
1642
+ exports.createQueueMiddleware = createQueueMiddleware$1;
1643
+ exports.createUserAgentMiddleware = createUserAgentMiddleware$1;